ModelSpec
The declarative object that connects a non-preset custom model to a Tracer / Logger / DataFilter, together with the Schema classes its fields take.
For how to write one, field by field, see
ModelSpec (Custom Model Support); the leaves and structure nodes
used to build a structure (S.Coords, S.BatchAxis, …) are listed in the
Cheat Sheet.
from ml_debugger.spec import ModelSpec, HeadSpec, LabelSchema, GroundTruthSchema, InputSchema, RawOutputSchema, OutputSchema
from ml_debugger.spec import Invoke, NMS, TopK, PostProcess, Decode, InModelNMS
from ml_debugger.spec import schema as S
ml_debugger.spec.ModelSpec
Bases: _SpecBaseModel
One declarative Spec for a model, reused across every purpose class.
Follows the model's own dataflow: Invoke(InputSchema) + LabelSchema ->
PostProcess(RawOutput) -> Output. The task (classification / object detection /
3D) comes from the facade class the Spec is passed to (or from task=); the same
ModelSpec type serves them all.
A model with several heads declares one :class:HeadSpec per head under heads=
instead of the parsing declarations above: inputs / invoke stay here (the
model runs once) and each head carries its own labels / raw_output / postprocess /
output. Each head is recorded under its own name, '<model name>[<head name>]'.
verify(model, sample_batch, ground_truth=None)
Dry-run this Spec against a model + sample batch (delegates to validate_spec).
Named verify rather than validate so it does not shadow Pydantic v1's
BaseModel.validate classmethod, which pydantic uses internally for parsing.
labels
ml_debugger.spec.LabelSchema
Bases: _SpecBaseModel
The label space the model's outputs and ground truth share.
Attributes:
| Name | Type | Description |
|---|---|---|
n_class |
Union[int, NClassFrom]
|
Number of classes (or :class: |
ground_truth |
Optional[GroundTruthSchema]
|
Structure of the ground-truth container
(:class: |
ml_debugger.spec.GroundTruthSchema
Bases: _SpecBaseModel
Structure of the ground-truth container, declared with the schema grammar.
Symmetric with :class:InputSchema / :class:RawOutputSchema / :class:OutputSchema,
and attached through labels=: LabelSchema(..., ground_truth=...) names how one
call's ground truth is shaped (a bare structure node is wrapped automatically).
Training records ground truth alongside every prediction, so the declaration is read
on every traced call; purposes that see no ground truth (production monitoring) omit it.
Omitting the declaration is also fine for the common container shapes -- per-sample
dict lists, key-per-field dicts, and framework-batched containers are recognised at
call time. Declare the structure when the container deviates from those, or when the
values need a meaning the shape alone cannot carry: a Coords / Coords3D leaf
states the box layout, scale and coordinate frame, and a 3D frame declared here must
agree with the one the prediction side declares -- both sides are converted with the
same mapping, and a disagreement is refused when the component is built.
Attributes:
| Name | Type | Description |
|---|---|---|
structure |
Any
|
Structure of the ground-truth container (the schema grammar --
|
inputs / invoke
ml_debugger.spec.InputSchema
Bases: _SpecBaseModel
Structure of the model input, declared with the schema grammar.
Attributes:
| Name | Type | Description |
|---|---|---|
structure |
Optional[Any]
|
The input container structure. |
resolve |
Optional[Callable[..., Any]]
|
For calls that accept non-tensor SOURCES (file paths, URLs) the
model resolves itself: |
ml_debugger.spec.Invoke
Bases: _SpecBaseModel
Declares HOW a model (or an in-model method) is called.
Attributes:
| Name | Type | Description |
|---|---|---|
method |
str
|
The method to call. Default |
unpack_input |
bool
|
When True, a mapping |
kwargs |
Dict[str, Any]
|
The call's keyword arguments. Values are literals or placeholders the
SDK fills per call (:class: |
container |
Optional[str]
|
Framework-specific container convention for the model's inputs / outputs /
ground truth. |
raw_output
ml_debugger.spec.RawOutputSchema
Bases: _SpecBaseModel
The model's raw output: its structure and where it comes from.
Attributes:
| Name | Type | Description |
|---|---|---|
structure |
Optional[Any]
|
Structure of the raw-output container, declared with the schema
grammar ( |
hook |
Optional[Union[LayerHook, HeadHook]]
|
Where the raw output is captured: |
The activation of confidence values is declared on the structure's ClassConfs
leaf, never schema-wide: activation names the transform the model uses to turn
the values into scores ("sigmoid" / "softmax", or "raw" for none), and
applied says whether the values that are read already carry it -- e.g.
ClassConfs(activation="sigmoid", applied=True) for values that are already
probabilities.
postprocess
ml_debugger.spec.NMS
Bases: _SpecBaseModel
Declares that the model's post-process is an NMS, and where its thresholds live.
Attributes:
| Name | Type | Description |
|---|---|---|
score_thresh_attr |
/ iou_thresh_attr / max_det_attr
|
Model attribute paths holding the score threshold / IoU threshold / detection cap. |
apply_func |
Optional[Callable[..., Any]]
|
For models whose thresholds are not reachable as attributes:
|
custom |
Any
|
Where a NON-standard NMS lives. Omit for a standard NMS (nothing else to declare). Set to:
A model that reports its kept candidate indices in the output declares a
|
score_thresh |
/ iou_thresh / max_det
|
The threshold VALUES themselves, for an
NMS whose thresholds are not held by the model (for example a post-process
function that takes them as arguments). They are the values used unless
the corresponding tracer keyword is given, which takes precedence. A value
and the |
min_box_edge_px |
Optional[float]
|
Minimum candidate box edge length in PIXELS; smaller boxes are dropped before selection. |
prenms_topk_per_class |
Optional[int]
|
Per-class candidate cap (score-descending) applied before the NMS. |
clip_boxes_to_image |
bool
|
Clip candidate boxes into the image bounds (pixels) before selection. |
nms_mode |
Optional[str]
|
What ONE candidate may become. |
The three candidate-preparation fields above shape the SDK-selected candidate
set; when an InModelNMS.returns structure declares a KeepIndex leaf, the
method's own selection is kept as-is and these fields do not participate.
The background column position of the candidate score matrix is not declared
here: it is derived from the Spec's ClassConfs / LabelId declarations.
ml_debugger.spec.TopK
Bases: _SpecBaseModel
Declares a top-k selection over the raw output (query-based heads).
The class/box tensor semantics (activation, background channel, box layout,
denormalization range) are read from the raw_output structure's ClassConfs /
Coords / Coords3D leaves; this DTO carries only the selection itself.
Attributes:
| Name | Type | Description |
|---|---|---|
score_thresh |
Optional[float]
|
Minimum score of a kept detection. |
max_num |
Optional[int]
|
Maximum number of kept detections. |
topk_mode |
Optional[str]
|
|
center_range |
Optional[List[float]]
|
3D object detection only. |
ml_debugger.spec.PostProcess
Bases: _SpecBaseModel
Your own post-process stage: fn(raw_output, **declared_kwargs) -> final output.
The bare-callable form (postprocess=my_fn) is the no-kwargs shorthand: the fn
receives the raw output only, on every task. Extra context is opt-in and declared
exactly like Invoke.kwargs -- the VALUE names the role the SDK fills::
postprocess=PostProcess(my_fn, kwargs={"img_sizes": ImageShapes()})
calls my_fn(raw, img_sizes=[(h, w), ...]). The output declaration
describes the fn's return value, exactly as for a bare callable.
The traced call returns the fn's return value: a tracer / logger / data filter takes the
place of my_fn(model(x)) in your code, so the post-process runs once and the line that
applied it after the model call is removed. This matches a declared NMS / TopK
with output=, where the call returns the final detections too. Set
return_model_output=True to keep receiving the model's own output instead (the fn is
then still run for what gets recorded, and your code applies it as before).
Attributes:
| Name | Type | Description |
|---|---|---|
fn |
Callable[..., Any]
|
The post-process callable. Its first argument is always the raw output. |
kwargs |
Dict[str, Any]
|
Extra keyword arguments the SDK fills, declared per role marker
(currently :class: |
return_model_output |
bool
|
Return the model's own output from the traced call instead of
the fn's return value. Defaults to |
ml_debugger.spec.Decode
Bases: _SpecBaseModel
Converts a raw output into the candidate container a postprocess stage reads.
Declared on a stage (NMS(decode=...) / TopK(decode=...)) when the raw
output does not directly carry the box coordinates / scores the stage selects
from. The conversion function returns any container; its returns structure
declaration (the same schema leaves as output / raw_output) tells the
stage where its candidates live.
When the raw output already is the candidate container, no decode is needed: declare
its structure as raw_output and the stage (NMS / TopK) selects from it.
Attributes:
| Name | Type | Description |
|---|---|---|
kwargs |
Dict[str, Any]
|
Extra keyword arguments the SDK fills, declared per role marker -- the
same contract |
fn |
Callable[..., Any]
|
|
returns |
Any
|
The structure declaration of the returned container. An |
ml_debugger.spec.InModelNMS
Bases: _SpecBaseModel
Declares an NMS that lives INSIDE the model, as a method the SDK intercepts.
Used as NMS(custom=InModelNMS(...)). The SDK wraps the named method for the
tracer's lifetime, reads its candidate arguments, and records which candidates the
method kept.
Attributes:
| Name | Type | Description |
|---|---|---|
template |
The name of a known post-process convention (also accepted as the
first positional argument, |
|
method |
str
|
The in-model method holding the post-process, as an attribute path on
the model (e.g. |
kwargs |
Dict[str, Any]
|
Argument-role markers naming the method's parameters that carry the
candidate tensors: :class: |
decoder |
str
|
The model's own box-decode method, as a path relative to the
intercepted method's parent object (e.g. |
decode |
str
|
How that decoder is called: |
activation |
Optional[str]
|
The activation turning the method's class logits into candidate
scores ( |
returns |
Any
|
The structure of the method's return value, declared with the
structure-declaration schema (:mod: |
keep_fn |
Optional[Callable[..., Any]]
|
Your own selection function |
The activation of the candidate scores is read from the ClassConfs leaf of
raw_output when that leaf names one (e.g. S.ClassConfs(activation="softmax",
background="index0")), and from activation here otherwise; written in both
places it must be the same kind. A leaf declaring applied=True says the logits
argument already carries it, and the values are then used as they are. When the
method reports its kept candidates (a KeepIndex leaf in returns) no score is
computed and nothing needs declaring; otherwise one of the two is required.
output
ml_debugger.spec.OutputSchema
Bases: _SpecBaseModel
The model's final output: its structure (and, rarely, how to cut its rows).
Symmetric with :class:InputSchema / :class:RawOutputSchema; a bare structure
node passed to output= is wrapped automatically, and an OutputSchema
instance can be defined once and reused across several ModelSpecs.
The traced call returns the model's own output with the rows your operational
thresholds discard removed -- the structure is never transformed. How rows are
removed is derived from the declared structure (whole-container integer indexing;
dict/list rebuild; attribute-object shallow copy); slice_with is the escape
hatch for containers none of those fit.
When structure describes a post-process callable's return value, the traced call
returns that value as the callable returned it (see :class:PostProcess).
Attributes:
| Name | Type | Description |
|---|---|---|
structure |
Any
|
The final-output container structure (the schema grammar). |
slice_with |
Optional[Callable[..., Any]]
|
Your own |
heads
ml_debugger.spec.HeadSpec
Bases: _SpecBaseModel
One head of a multi-head model: everything that describes that head's prediction.
A head declares its own label space, raw output, post-process and final output --
the same declarations a single-head :class:ModelSpec carries. How the model is
called (inputs / invoke) is shared by every head and stays on the ModelSpec:
the model runs once and each head reads its own part of that one output.
On a Keras model with several classification outputs, state each head's activation
in its own declaration -- ClassConfs(activation="raw") for a plain linear
Dense head, ClassConfs(activation="softmax", applied=True) for one that
already produces probabilities (for a classification head, "softmax" alone means
the same). What a single-output model leaves out is read off the model's LAST layer,
which is one layer and cannot answer for several heads.
Attributes:
| Name | Type | Description |
|---|---|---|
labels |
LabelSchema
|
The label space this head predicts (:class: |
raw_output |
Optional[RawOutputSchema]
|
The structure of this head's raw output and where it comes from. |
postprocess |
List[Any]
|
The transformations between this head's raw output and its final
output: a single :class: |
output |
Optional[OutputSchema]
|
The structure of this head's final output. |
task |
Optional[str]
|
The task this head serves ( |
Validation & inference
ml_debugger.spec.validate_spec(spec, model, sample_batch, ground_truth=None)
Dry-run a Spec against a model + sample batch and return a findings report.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
|
Any
|
A :class: |
required |
|
Any
|
The model the Spec describes. |
required |
|
Any
|
A representative input batch (a tensor, list, or dict). The model is called
directly (Keras models via |
required |
|
Any
|
Optional GT container; when given with a |
None
|
Returns:
| Name | Type | Description |
|---|---|---|
A |
SpecValidationReport
|
class: |
SpecValidationReport
|
turn error-severity findings into an exception. |
ml_debugger.spec.validate_capture(spec, model, sample_batch, ground_truth=None)
Check a Spec end to end: the declaration, then a real recording made under it.
First runs the same declaration checks as :func:~ml_debugger.spec.validate_spec on
the (first) sample batch. When those find no error, it records the sample through the
ordinary recording path into a throwaway local database, reads the rows back, and
checks them: whether every prediction was recorded with usable values, whether the
values recorded alongside them were filled in, whether the class confidences look
like what the declaration says they are, and how many rows each input produced. With
ground truth it also checks how the ground truth was stored, whether it shares the
predictions' coordinate space, and whether predictions land on it.
Nothing is sent anywhere and nothing is left behind: the recording is local, uses a name of its own, and is removed afterwards. A recording that cannot be made -- no active license, a model that fails on the sample -- is reported as a finding rather than raised, and a check that does not run always says so.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
|
Any
|
A :class: |
required |
|
Any
|
The model the Spec describes. |
required |
|
Any
|
A representative input batch, or a list of batches. Several batches
are recognised by their ground truth being a matching list (one entry per
batch); without ground truth, |
required |
|
Any
|
Optional ground truth for the sample, one entry per input (or, for
several batches, a list of those). For a Spec declaring |
None
|
Returns:
| Name | Type | Description |
|---|---|---|
A |
SpecValidationReport
|
class: |
SpecValidationReport
|
recorded-data findings together. Call :meth: |
|
SpecValidationReport
|
to turn error-severity findings into an exception. |
ml_debugger.spec.SpecValidationReport
dataclass
The collected findings of a :func:validate_spec dry run.
ok
property
Whether the Spec is safe to use (no error-severity findings).
errors
property
warnings
property
infos
property
summary()
A human-readable, multi-line summary of every finding.
raise_if_errors()
Raise :class:SpecValidationError with the full summary if any errors exist.
ml_debugger.spec.inspect_model(model, sample_batch=None, ground_truth=None, task=None, known=None, _call_cache=None)
Inspect model and return a resolvable :class:InspectionResult.
The entry point of Spec inference: instead of raising on the first uncertainty (as
:func:infer_spec does), it captures the ask(s) into result.questions for the
caller to answer (via :meth:InspectionResult.answer) and re-infer.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
|
Any
|
The model to instrument (PyTorch or Keras). |
required |
|
Any
|
One representative model input batch; the model is probed once on it. Omit it to run the model on a conventional image input built for its framework -- supplying the real input resolves more facts, and a model taking point clouds, several camera views or file paths needs one unless a built-in preset matches it. |
None
|
|
Any
|
Optional ground-truth sample matching |
None
|
|
Optional[str]
|
The facade task, or |
None
|
|
Optional[Dict[str, Any]]
|
Answers to previous asks, keyed by the ask name. |
None
|
Returns:
| Name | Type | Description |
|---|---|---|
An |
InspectionResult
|
class: |
ml_debugger.spec.InspectionResult
The outcome of :func:inspect_model: a resolved Spec, or open questions.
When questions is empty the inference resolved and spec is the adopted
:class:ModelSpec; otherwise spec is None and every entry of
questions names a fact to supply. :meth:answer merges answers and
re-infers WITHOUT re-executing the model probe; :meth:require_spec returns the
Spec or re-raises the original :class:SpecInferenceError;
:meth:render_spec_draft renders the inferred Spec as runnable code.
answer(**facts)
Merge facts into known= and re-infer, reusing the cached probe.
The model output captured on the first probe is threaded through, so the
model itself is not called again (the validate dry runs inside candidate
scoring may still call it). Answering sample_batch= is the exception: it
supplies the input to inspect the model on, so the model IS probed again on it.
render_spec_draft()
Render the inferred Spec as a runnable Python declaration.
Resolved inspections render a complete, executable ModelSpec(...): running
it rebuilds the same Spec. Unresolved ones fill every certain fact and mark each
open one with a <...> placeholder and a # TODO comment; the same
placeholder marks the rare value that cannot be written out (a function defined
inside another function, a value with no literal form), so a draft either
rebuilds the Spec exactly or does not run until you fill it in.
require_spec()
Return the adopted Spec, or re-raise the original inference error.
ml_debugger.spec.Question
dataclass
One fact inference could not determine with certainty.
Attributes:
| Name | Type | Description |
|---|---|---|
id |
str
|
The stable |
reason |
str
|
The human explanation -- the inference error's message text. |
choices |
Optional[List[Any]]
|
The allowed values when the vocabulary is closed and derivable
(e.g. |
evidence |
Dict[str, Any]
|
A short dict of cheaply observed facts, else |
ml_debugger.spec.infer_spec(model, sample_batch=None, ground_truth=None, task=None, known=None)
Infer a ready-to-use :class:ModelSpec for model.
The shorthand for the confident path: a thin wrapper over :func:inspect_model that
returns the adopted Spec, or raises :class:SpecInferenceError naming exactly what is
missing and how to supply it (known={...} for a single fact, or a full spec=
declaration). Use :func:inspect_model to work through the asks instead of raising.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
|
Any
|
The model to instrument (PyTorch or Keras). |
required |
|
Any
|
One representative model input batch; inference runs the model on it once (under the same guards the validators use). Omit it to run the model on a conventional image input built for its framework. |
None
|
|
Any
|
Optional ground-truth sample matching |
None
|
|
Optional[str]
|
The facade task ( |
None
|
|
Optional[Dict[str, Any]]
|
Answers to previous :class: |
None
|
Returns:
| Type | Description |
|---|---|
ModelSpec
|
A ModelSpec whose every field was determined with certainty and whose |
ModelSpec
|
|
Raises:
| Type | Description |
|---|---|
SpecInferenceError
|
When a field cannot be determined with certainty. |