コンテンツにスキップ

ModelSpec

プリセット非対応のカスタムモデルを Tracer / Logger / DataFilter に接続するための定義オブジェクトと、 その各フィールドに渡す Schema クラスの一覧です。

書き方とフィールドごとの解説は ModelSpec(カスタムモデル対応)、 構造を組み立てる leaf / 構造ノード(S.Coords / S.BatchAxis など)は チートシート を参照してください。

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.

属性:

名前 タイプ デスクリプション
n_class Union[int, NClassFrom]

Number of classes (or :class:NClassFrom to read it off a model attribute). Required even without ground truth -- it defines the label space the model outputs.

ground_truth Optional[GroundTruthSchema]

Structure of the ground-truth container (:class:GroundTruthSchema, or a schema node directly). Omit when no ground truth flows (e.g. production monitoring).

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.

属性:

名前 タイプ デスクリプション
structure Any

Structure of the ground-truth container (the schema grammar -- Coords / Coords3D / LabelId / Velocity leaves carry the per-object semantics).


inputs / invoke

ml_debugger.spec.InputSchema

Bases: _SpecBaseModel

Structure of the model input, declared with the schema grammar.

属性:

名前 タイプ デスクリプション
structure Optional[Any]

The input container structure. Array leaves may carry "H" / "W" labels, from which per-sample image sizes are derived. The size a normalized output box denormalizes against is declared on the OUTPUT side (Coords(size_from=...)), not here.

resolve Optional[Callable[..., Any]]

For calls that accept non-tensor SOURCES (file paths, URLs) the model resolves itself: resolve(model_input, model_output) -> per-sample input tensors recovers the actual inputs the model saw (the hash / size source). Prefer declaring the location with an Array(input_tensor=True) leaf in the output structure; resolve is the escape hatch when the inputs must be computed rather than picked.

ml_debugger.spec.Invoke

Bases: _SpecBaseModel

Declares HOW a model (or an in-model method) is called.

属性:

名前 タイプ デスクリプション
method str

The method to call. Default "__call__" (i.e. model(...)); an arbitrary method path (e.g. "forward_test", "roi_heads.postprocess_detections") is resolved via getattr.

unpack_input bool

When True, a mapping model_input is spread as keyword arguments (method(**model_input, ...)); when False (default), it is passed positionally (method(model_input, ...)).

kwargs Dict[str, Any]

The call's keyword arguments. Values are literals or placeholders the SDK fills per call (:class:NMSScoreThresh / :class:NMSIouThresh / :class:NMSMaxDet / :class:FromCall). Placeholder CLASSES may be written without parentheses.

container Optional[str]

Framework-specific container convention for the model's inputs / outputs / ground truth. "mmdet3d" unwraps mmcv DataContainer objects. None -> off.


raw_output

ml_debugger.spec.RawOutputSchema

Bases: _SpecBaseModel

The model's raw output: its structure and where it comes from.

属性:

名前 タイプ デスクリプション
structure Optional[Any]

Structure of the raw-output container, declared with the schema grammar (ClassConfs / Coords / Coords3D leaves carry the tensor semantics; a ClassConfMap leaf declares a spatial confidence map read out per detection). Omit when a registered post-process callable consumes the raw output directly.

hook Optional[Union[LayerHook, HeadHook]]

Where the raw output is captured: None (default) = the model's return value; a :class:LayerHook / :class:HeadHook = the forward output of that named module.

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.

属性:

名前 タイプ デスクリプション
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: apply_func(model, config) is called to apply a threshold configuration. This hook is yours for the SDK to drive, so it is left holding the last configuration applied; the declared attribute paths, which the model keeps for its own use, are put back to your own values when a call ends.

custom Any

Where a NON-standard NMS lives. Omit for a standard NMS (nothing else to declare). Set to:

  • an :class:InModelNMS -- the NMS lives inside the model as a method the SDK intercepts;
  • your own callable fn(candidates, config) -> kept indices -- an EXTERNAL custom NMS implementation, receiving a :class:~ml_debugger.spec.Candidates context.

A model that reports its kept candidate indices in the output declares a KeepIndex leaf there instead of custom. Those indices SELECT rows of a candidate confidence source, so that form needs the source declared too: raw_output=RawOutputSchema(hook=LayerHook('<module path>')). The leaf is read from the model's final output (or from an InModelNMS.returns when the intercepted method reports it); declared on any other structure it has no reader.

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 *_attr path of the same threshold cannot both be declared. Each threshold is resolved on its own: a declared value or *_attr path is used ahead of anything MLdebugger reads from the model by itself, and a threshold the declaration leaves open keeps that reading.

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. "flatten" (the default when omitted) makes one selection row per candidate x class, so a candidate can yield a detection under several classes -- the form models that score each class independently need. "per_candidate" keeps one row per candidate, at its strongest class, which is what single-stage detectors select from. The same distinction TopK.topk_mode draws for query heads.

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.

属性:

名前 タイプ デスクリプション
score_thresh Optional[float]

Minimum score of a kept detection. None = the value MLdebugger reads from the model, when the model holds one; otherwise keep by rank only.

max_num Optional[int]

Maximum number of kept detections. None = the value MLdebugger reads from the model, when the model holds one; otherwise no limit (every candidate that passes score_thresh is kept). A tracer keyword overrides either.

topk_mode Optional[str]

"per_query" (best class per query) or "flatten" (top-k over the flattened query x class scores; one query may yield several detections). Default None = the task's native mode (2D object detection -> "per_query", 3D -> "flatten"); an explicit value is honored on either task.

center_range Optional[List[float]]

3D object detection only. [x_min, y_min, z_min, x_max, y_max, z_max]: a selected detection is kept only when its box centre lies inside this range (mmdet3d's post_center_range). None keeps every detection.

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).

属性:

名前 タイプ デスクリプション
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:ImageShapes; 2D object detection only).

return_model_output bool

Return the model's own output from the traced call instead of the fn's return value. Defaults to False.

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.

属性:

名前 タイプ デスクリプション
kwargs Dict[str, Any]

Extra keyword arguments the SDK fills, declared per role marker -- the same contract PostProcess.kwargs uses, e.g. kwargs={"img_shapes": ImageShapes()} to receive the per-image input sizes. A decode that needs a fact about the CALL rather than about the model declares it here, so the Spec stays a declaration of confirmed facts instead of carrying a hand-set constant (a heatmap head's output stride, for instance, is the input height over the map height -- derived per image, never configured).

fn Callable[..., Any]

fn(raw_output, **declared kwargs) -> container -- called once per batch with the resolved raw output (the hooked capture when raw_output declares a hook, else the model's own raw output).

returns Any

The structure declaration of the returned container. An NMS stage needs Coords plus Score (or ClassConfs) leaves; a TopK stage needs ClassConfs plus Coords / Coords3D leaves.

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.

属性:

名前 タイプ デスクリプション
template

The name of a known post-process convention (also accepted as the first positional argument, InModelNMS("torchvision_roi_heads")). A template declares the whole in-model post-process convention of a known model family and fills every field below; any field you also pass explicitly overrides the template's value. Known templates: "torchvision_roi_heads" (torchvision Faster R-CNN) and "torchvision_ssd_head" (torchvision SSD). Give template or method (or both).

method str

The in-model method holding the post-process, as an attribute path on the model (e.g. "roi_heads.postprocess_detections").

kwargs Dict[str, Any]

Argument-role markers naming the method's parameters that carry the candidate tensors: :class:Logits / :class:BoxRegression / :class:Anchors / :class:ImageShapes / :class:Contains, keyed by the method's PARAMETER names. Omit when the torchvision positional convention applies. Marker CLASSES may be written without parentheses.

decoder str

The model's own box-decode method, as a path relative to the intercepted method's parent object (e.g. "box_coder.decode").

decode str

How that decoder is called: "batched" (once over the concatenated regression + the anchors list) or "per_image" (once per image).

activation Optional[str]

The activation turning the method's class logits into candidate scores ("softmax" / "sigmoid", or "raw" to use the values as they are). Optional when the ClassConfs leaf of raw_output names it; see below.

returns Any

The structure of the method's return value, declared with the structure-declaration schema (:mod:ml_debugger.spec.schema). A standard declaration names where the kept boxes / scores / labels sit, e.g. S.Seq(S.BatchAxis[S.DetAxis[S.Coords("xyxy", "pixel")]], ...) for a (boxes, scores, labels) tuple return, or S.BatchAxis[S.Dict(boxes=..., scores=..., labels=...)] for a per-image dict return. A :class:~ml_debugger.spec.schema.KeepIndex leaf in the structure declares that the method reports its kept candidates: the SDK then runs the method itself and keeps its selection, so the method's own return (its undeclared fields included) flows through reduced to the kept rows.

keep_fn Optional[Callable[..., Any]]

Your own selection function keep_fn(candidates, config) -> kept indices over the extracted candidates, for methods whose selection the SDK cannot reproduce; the SDK still records the candidate-to-detection correspondence around it.

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).

属性:

名前 タイプ デスクリプション
structure Any

The final-output container structure (the schema grammar).

slice_with Optional[Callable[..., Any]]

Your own slice_with(container, keep_indices) -> container returning the per-image container reduced to the kept rows.


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.

属性:

名前 タイプ デスクリプション
labels LabelSchema

The label space this head predicts (:class:LabelSchema, or the number of classes directly).

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:NMS / :class:TopK / your own callable.

output Optional[OutputSchema]

The structure of this head's final output.

task Optional[str]

The task this head serves ("classification" / "object_detection" / "object_detection_3d"). Omit it to let the declared structures decide, or to inherit the ModelSpec's own task.


検査・自動生成

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.

引数:

名前 タイプ デスクリプション デフォルト

spec

Any

A :class:ModelSpec.

必須

model

Any

The model the Spec describes.

必須

sample_batch

Any

A representative input batch (a tensor, list, or dict). The model is called directly (Keras models via predict) unless the Spec declares an Invoke, in which case its method / unpack / fixed-kwargs convention is honored. A declared raw_source head hook and container_mode are honored too.

必須

ground_truth

Any

Optional GT container; when given with a gt schema, the GT/prediction coordinate-space consistency check runs. For a Spec declaring heads, pass the GT per head as {head name: ground truth}.

None

戻り値:

名前 タイプ デスクリプション
A SpecValidationReport

class:SpecValidationReport. Call :meth:SpecValidationReport.raise_if_errors to

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.

引数:

名前 タイプ デスクリプション デフォルト

spec

Any

A :class:ModelSpec.

必須

model

Any

The model the Spec describes.

必須

sample_batch

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, sample_batch is one batch.

必須

ground_truth

Any

Optional ground truth for the sample, one entry per input (or, for several batches, a list of those). For a Spec declaring heads, pass it per head as {head name: ground truth}. Without it the predictions are recorded and checked alone, and the ground-truth checks are reported as not run -- supply it for full coverage.

None

戻り値:

名前 タイプ デスクリプション
A SpecValidationReport

class:SpecValidationReport holding the declaration findings and the

SpecValidationReport

recorded-data findings together. Call :meth:SpecValidationReport.raise_if_errors

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.

引数:

名前 タイプ デスクリプション デフォルト

model

Any

The model to instrument (PyTorch or Keras).

必須

sample_batch

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

ground_truth

Any

Optional ground-truth sample matching sample_batch.

None

task

Optional[str]

The facade task, or None to derive it from the output shape.

None

known

Optional[Dict[str, Any]]

Answers to previous asks, keyed by the ask name.

None

戻り値:

名前 タイプ デスクリプション
An InspectionResult

class:InspectionResult.

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.

属性:

名前 タイプ デスクリプション
id str

The stable known= key that answers it (e.g. "bbox_scale").

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. ["pixel", "normalized"]), else None.

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.

引数:

名前 タイプ デスクリプション デフォルト

model

Any

The model to instrument (PyTorch or Keras).

必須

sample_batch

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

ground_truth

Any

Optional ground-truth sample matching sample_batch (used by the detection tasks; unused for classification).

None

task

Optional[str]

The facade task ("classification" / "object_detection" / "object_detection_3d"). Omit to let the preset fingerprint or the output shape decide; pass it when inference asks for it.

None

known

Optional[Dict[str, Any]]

Answers to previous :class:SpecInferenceError asks, keyed by the ask name (e.g. known={"output_key": "logits"}).

None

戻り値:

タイプ デスクリプション
ModelSpec

A ModelSpec whose every field was determined with certainty and whose

ModelSpec

validate_spec dry run reported no errors.

発生:

タイプ デスクリプション
SpecInferenceError

When a field cannot be determined with certainty.