raidar 0.1.0a1__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
raidar/__init__.py ADDED
@@ -0,0 +1,76 @@
1
+ """Raidar: object detection across training backends, driven by one config.
2
+
3
+ **The core is backend-free.** ``pip install raidar`` gives you the CLI and the config surface;
4
+ a training framework arrives with the backend you select::
5
+
6
+ pip install 'raidar[lightning]' # PyTorch Lightning — the reference backend
7
+ pip install 'raidar[rfdetr]' # RF-DETR's own PTL loop (Apache-2.0)
8
+ pip install 'raidar[huggingface]' # + the D-FINE / RT-DETRv2 model wrappers
9
+
10
+ Which is why every backend-owned name below resolves LAZILY (PEP 562): importing ``raidar`` must
11
+ not require a framework the operator did not choose. Touching a name whose backend is missing
12
+ raises an :class:`ImportError` naming the exact extra, instead of a traceback from three
13
+ libraries down.
14
+ """
15
+
16
+ from importlib.metadata import PackageNotFoundError, version
17
+
18
+ from matrainer._exports import lazy_exports
19
+
20
+ try:
21
+ # Single source of truth: the installed distribution's metadata, i.e. pyproject.toml's
22
+ # `version` (the distribution is `raidar`). Never type the number in here as well.
23
+ __version__ = version("raidar")
24
+ except PackageNotFoundError: # pragma: no cover - uninstalled source checkout
25
+ __version__ = "0.0.0.dev0"
26
+
27
+
28
+ #: Backend-owned name -> (defining module, the extra that installs it). Resolved on first
29
+ #: attribute access. Keep in step with the extras in ``pyproject.toml``: a name here whose extra
30
+ #: does not exist would advertise an install command that fails.
31
+ _BACKEND_NAMES = {
32
+ "LightningDetector": ("raidar.lightning_detector", "lightning"),
33
+ "TorchDetector": ("raidar.torch_detector", "torch"),
34
+ "FastaiDetector": ("raidar.fastai_detector", "fastai"),
35
+ "HuggingFaceDetector": ("raidar.huggingface_detector", "huggingface"),
36
+ "RFDETRDetector": ("raidar.rfdetr_detector", "rfdetr"),
37
+ # The native RF-DETR model module (runs through the LIGHTNING backend; building it needs the
38
+ # `rfdetr` library, so its extra is the one that supplies the weights + architecture).
39
+ "RFDETRModel": ("raidar.rfdetr", "rfdetr"),
40
+ # The ONE Hub zoo wrapper — a `model_name` string reaches any object-detection checkpoint;
41
+ # it is the huggingface BACKEND's model (the model computes its own loss from `labels=`).
42
+ "HuggingFaceDetectionModel": ("raidar.huggingface_model", "huggingface"),
43
+ # The torchvision zoo behind ONE configured wrapper (weights/score cut/label numbering/
44
+ # checkpoint load) — the inference twin of the raw builder functions the trainers wire.
45
+ "TorchVisionDetectionModel": ("raidar.torchvision_model", "torch"),
46
+ # The torch engine's registered metric set (one module per engine). Batching is
47
+ # recordstream's — `collate_records` + `batch_boxes`, no raidar collate.
48
+ "DetectionConfusionMatrix": ("raidar.torch_detection", "torch"),
49
+ # The shared tiny-FCOS spec's torch implementation (serves the lightning/torch/fastai loops).
50
+ "TorchFcos": ("raidar.fcos.torch_fcos", "torch"),
51
+ # The Keras 3 backend + the spec's Keras implementation and its dense-target op.
52
+ "KerasDetector": ("raidar.keras_detector", "keras"),
53
+ "KerasFcos": ("raidar.fcos.keras_fcos", "keras"),
54
+ # The native TensorFlow loop + the spec in raw tf.nn ops.
55
+ "TensorFlowDetector": ("raidar.tensorflow_detector", "tensorflow"),
56
+ "TensorFlowFcos": ("raidar.fcos.tensorflow_fcos", "tensorflow"),
57
+ # The jitted optax loop + the spec in flax.nnx.
58
+ "JaxDetector": ("raidar.jax_detector", "jax"),
59
+ "FlaxFcos": ("raidar.fcos.flax_fcos", "jax"),
60
+ # Apple's MLX loop + the spec in mlx.nn (Apple silicon only).
61
+ "MlxDetector": ("raidar.mlx_detector", "mlx"),
62
+ "MlxFcos": ("raidar.fcos.mlx_fcos", "mlx"),
63
+ # FcosTargets is numpy + the spec only, but it reads Boxes targets the torch-shaped chain
64
+ # produced — its extra is torch (the smallest install that can feed it).
65
+ "FcosTargets": ("raidar.fcos.targets", "torch"),
66
+ # The on-disk YOLO-layout sink is numpy/PIL/yaml only — no framework — but it stays lazy so
67
+ # `import raidar` imports NOTHING. Its "extra" is the core install itself.
68
+ "YoloSink": ("raidar.yolo_sink", ""),
69
+ }
70
+
71
+ __all__ = [*_BACKEND_NAMES]
72
+
73
+ # The resolver is matrainer's `lazy_exports` (the machinery was identical in every training
74
+ # project's root); the `_BACKEND_NAMES` table above is the project DATA it runs on. An EMPTY
75
+ # extra (YoloSink) passes its ImportError through untranslated — a core name's failure is real.
76
+ __getattr__, __dir__ = lazy_exports(__name__, _BACKEND_NAMES)
raidar/_keras.py ADDED
@@ -0,0 +1,16 @@
1
+ """The ONE spelling of ``import keras`` in this package — re-exported from recordstream.
2
+
3
+ Keras 3 reads ``KERAS_BACKEND`` at **import time** and its own default is ``tensorflow``, which
4
+ this project does not require (Keras is an API; the compute engine is the operator's choice). So
5
+ something has to set the variable to an engine that is actually installed BEFORE keras is first
6
+ imported, and that something must sit in the lowest layer — ``recordstream.keras`` — because
7
+ import sorters put a third-party import above a first-party one: a shim here would sort BELOW
8
+ ``from recordstream.keras import RecordSequence`` and lose the race.
9
+
10
+ This module therefore adds nothing but a name. Every raidar module writes
11
+ ``from raidar._keras import keras`` and never ``import keras`` directly.
12
+ """
13
+
14
+ from recordstream.keras import keras, keras_backend
15
+
16
+ __all__ = ["keras", "keras_backend"]
raidar/_tensorflow.py ADDED
@@ -0,0 +1,26 @@
1
+ """The ONE place raidar imports TensorFlow — and the ``KERAS_BACKEND`` ordering that must precede it.
2
+
3
+ The twin of :mod:`raidar._keras`, for the mirror image of that module's problem.
4
+ :mod:`recordstream.keras` defaults ``KERAS_BACKEND`` to the first backend actually INSTALLED, in
5
+ the order ``torch`` -> ``tensorflow`` -> ``jax``. Right for a Keras run — any engine will do —
6
+ and WRONG here: on a machine carrying both ``raidar[lightning]`` and ``raidar[tensorflow]`` (the
7
+ workspace's own setup) torch wins, and the TensorFlow backend would then drive a torch-backed
8
+ ``keras.Model`` with ``tf.GradientTape``, which cannot work.
9
+
10
+ Keras reads the variable ONCE, at import time, so the default has to be in place before ANY
11
+ module imports keras — which is why this module hands over the ``keras`` handle **as well as**
12
+ ``tf``: importing keras from :mod:`raidar._keras` beside ``tf`` from here would let isort sort
13
+ ``_keras`` ahead of ``_tensorflow``, importing keras one line before the default that was
14
+ supposed to steer it. ``setdefault``, not an assignment: an explicit ``KERAS_BACKEND=jax`` still
15
+ wins, and the backend's ``initialize()`` then fails naming the mismatch.
16
+ """
17
+
18
+ import os
19
+
20
+ # BEFORE the imports below, and before anything else imports keras — see the module docstring.
21
+ os.environ.setdefault("KERAS_BACKEND", "tensorflow")
22
+
23
+ import tensorflow as tf # noqa: E402 - deliberately after the environment default above
24
+ from recordstream.keras import RecordSequence, keras, keras_backend # noqa: E402
25
+
26
+ __all__ = ["RecordSequence", "keras", "keras_backend", "tf"]
raidar/cli.py ADDED
@@ -0,0 +1,110 @@
1
+ """Raidar CLI — object detection across training backends.
2
+
3
+ Three verbs, and the training backend is a *config* dimension the CLI passes through::
4
+
5
+ raidar train cfg.yaml # the config's default backend
6
+ raidar train cfg.yaml --framework rfdetr # a `!scope:framework=rfdetr` block
7
+ raidar evaluate cfg.yaml
8
+ raidar predict cfg.yaml
9
+ raidar frameworks # what the backends are
10
+
11
+ What stays constant across backends is the point: the same ``runnable:`` + ``task:`` config, the
12
+ same three verbs, the same tracking. Only the runnable class named in the YAML changes. (A generic
13
+ ``matrainer train cfg.yaml`` or ``recordstream run cfg.yaml`` also works — the first is the same
14
+ machinery without this project's table.)
15
+
16
+ The MACHINERY is :mod:`matrainer.cli` (2026-08-07, the P4 lift) — the verb dispatch through
17
+ ``materialize_runnable``, the ``--framework`` → ``--scope`` rewrite, the keras engine pin, the
18
+ registration import and their load-bearing ORDER all live on the factory's own docstrings. Two
19
+ raidar notes on that machinery: the taskless-fit guard (a runnable with NO ``task`` attribute —
20
+ the ultralytics sibling's current trainer — trains as-is and RAISES on the other verbs) started
21
+ HERE and is now the shared default dispatch; and the keras engine pin, which this CLI never
22
+ carried (its tensorflow row registers nothing, and ``raidar._tensorflow`` sets the same default
23
+ at import), now rides along harmlessly — both are ``setdefault``, so they cannot disagree. What
24
+ this module owns is raidar's DATA: the FRAMEWORKS table and the verb help texts.
25
+
26
+ Adding a backend: write ``raidar/<name>_detector.py``, then add a row to ``FRAMEWORKS`` below.
27
+ """
28
+
29
+ from typing import Dict
30
+
31
+ from matrainer.cli import Framework, make_trainer_app, trainer_main
32
+
33
+ FRAMEWORKS: Dict[str, Framework] = {
34
+ "lightning": Framework(
35
+ "PyTorch Lightning — the reference backend (torchvision natives, RFDETRModel, TorchFcos).",
36
+ # The torch engine's TWO registration modules: the torchmetrics detection metric set +
37
+ # DetectionConfusionMatrix, and the torchvision detection BUILDERS — so a config may name
38
+ # any of them bare (the eager `!class:Foo()` form is built during config load, before any
39
+ # handler runs). A TUPLE keeps the coupling readable in the table instead of hiding it in
40
+ # a side-effect import inside one of them.
41
+ ("raidar.torch_detection", "raidar.torchvision_detection"),
42
+ ),
43
+ # Shares `lightning`'s registration modules, and that is the point rather than an economy: a
44
+ # torchmetrics detection metric does not care whether a Trainer or a hand-written loop feeds
45
+ # it, so the two backends differ ONLY in the loop.
46
+ "torch": Framework(
47
+ "PyTorch — a hand-written loop, no training framework at all (the control experiment).",
48
+ ("raidar.torch_detection", "raidar.torchvision_detection"),
49
+ ),
50
+ "fastai": Framework(
51
+ "fastai — a Learner with one-cycle scheduling over the same torch stack (no-op-loss "
52
+ "bridge for the loss-inside-forward contract).",
53
+ # The same torch registrations reach it — a torchmetrics collection and a torchvision
54
+ # builder do not care which loop feeds them.
55
+ ("raidar.torch_detection", "raidar.torchvision_detection"),
56
+ ),
57
+ "huggingface": Framework(
58
+ "Transformers `Trainer` + Accelerate — fine-tuning a Hub detection checkpoint by name.",
59
+ # No registrations: an `AutoModelForObjectDetection` computes its own loss from
60
+ # `labels=`, so there is nothing a config could wire.
61
+ ),
62
+ "rfdetr": Framework(
63
+ "RF-DETR's own PyTorch-Lightning loop (Apache-2.0) — COCO-mAP eval, EMA, LR schedule.",
64
+ # Nothing to register: the runnable and the model are wired by dotted path.
65
+ ),
66
+ "keras": Framework(
67
+ "Keras 3 — the shared FCOS spec on whichever engine KERAS_BACKEND names (torch / TF / jax).",
68
+ # Nothing to register: the spec model and the dense-target op are wired by dotted path,
69
+ # the loss is the spec's own (no compile-slot vocabulary), and scoring is numpy.
70
+ ),
71
+ "tensorflow": Framework(
72
+ "Native TensorFlow — tf.data + GradientTape steps under tf.function, SavedModel export.",
73
+ # Nothing to register, for the keras row's reason — and no second registration module:
74
+ # TF >= 2.16's tf.keras IS Keras 3, so one would only duplicate tags.
75
+ ),
76
+ "jax": Framework(
77
+ "JAX — an nnx.jit-traced optax loop over the shared FCOS spec in flax.nnx.",
78
+ # Nothing to register: optax ships plain functions/factories — no class for a tag.
79
+ ),
80
+ "mlx": Framework(
81
+ "Apple MLX — unified-memory training of the shared FCOS spec (Apple silicon only).",
82
+ # Nothing to register, for the jax row's reason.
83
+ ),
84
+ "ultralytics": Framework(
85
+ "Ultralytics YOLO (AGPL) — lives in the raidar-ultralytics sibling package; "
86
+ "`pip install raidar-ultralytics`.",
87
+ # Best-effort import — registers the sibling's models/trainer when it is installed;
88
+ # absent on a default checkout, which is the correct state for an AGPL opt-in.
89
+ ("raidar_ultralytics",),
90
+ ),
91
+ }
92
+
93
+ app = make_trainer_app(
94
+ name="raidar",
95
+ description="Object detection across training backends",
96
+ frameworks=FRAMEWORKS,
97
+ verb_docs={
98
+ "train": "Train an object-detection model",
99
+ "evaluate": "Evaluate a trained detector over the test set",
100
+ "predict": "Stream detection predictions from a trained detector to its sink",
101
+ },
102
+ )
103
+
104
+
105
+ def main() -> None:
106
+ trainer_main(app, FRAMEWORKS)
107
+
108
+
109
+ if __name__ == "__main__":
110
+ main()
@@ -0,0 +1,178 @@
1
+ """``DetectionBase`` — the task half of every raidar backend, written once.
2
+
3
+ The detection logic that used to exist per backend module: ``num_classes`` resolution
4
+ (concrete model head → explicit → lazy kwarg → the announced target walk over the ``Boxes``
5
+ column), the injected-only-when-accepted model flow (torchvision ships its detectors as
6
+ builder FUNCTIONS with differing signatures), the fork-safe split preparation, and the
7
+ fit/eval initialization split — including detection's own asymmetry, the missing train
8
+ metrics split (a native model in train mode returns only a loss dict).
9
+
10
+ It subclasses the trainer API base (`matrainer.runnable.TrainerRunnable`) and is deliberately
11
+ **torch-free** so the four spec engines (keras/tensorflow/jax/mlx) can import it. The
12
+ torch-family hook IMPLEMENTATIONS live in :mod:`raidar.detection_torch` — NOT to be confused
13
+ with :mod:`raidar.torch_detection`, which is the torch ENGINE's registered metric set + the
14
+ ``native_batch`` contract adapter; that one registers/adapts, this one carries task logic.
15
+ """
16
+
17
+ import inspect
18
+ from typing import TYPE_CHECKING, Any, List, Optional
19
+
20
+ from confluid import Fluid, flow
21
+ from confluid.registry import resolve_class
22
+ from loggair import get_logger
23
+ from matrainer.runnable import TrainerRunnable
24
+ from recordstream import Boxes, iter_key
25
+ from tqdm import tqdm
26
+
27
+ if TYPE_CHECKING: # annotation-only — this module must not import torch
28
+ import torch.nn as nn
29
+
30
+ logger = get_logger(__name__)
31
+
32
+ __all__ = ["DetectionBase", "_model_num_classes"]
33
+
34
+
35
+ def _model_num_classes(model: "nn.Module") -> Optional[int]:
36
+ """Best-effort read of a BUILT detector's class count (explicit attr or torchvision head), or ``None``."""
37
+ nc = getattr(model, "num_classes", None)
38
+ if nc:
39
+ return int(nc)
40
+ box_predictor = getattr(getattr(model, "roi_heads", None), "box_predictor", None)
41
+ out_features = getattr(getattr(box_predictor, "cls_score", None), "out_features", None)
42
+ if out_features:
43
+ return int(out_features)
44
+ return None
45
+
46
+
47
+ class DetectionBase(TrainerRunnable):
48
+ """The detection task base: ``num_classes`` resolution + the fit/eval initialization.
49
+
50
+ The attributes below are STORED by the concrete backend's own ``__init__`` (they are its
51
+ config surface); this base only declares their names/types for the methods that read them.
52
+ There is deliberately NO ``train_metrics`` attribute in any detection config surface — a
53
+ torchvision-native model in train mode returns ONLY the loss dict, so a slot would accept
54
+ a wired set and silently never call it.
55
+ """
56
+
57
+ log_label = "raidar"
58
+
59
+ @property
60
+ def train_metrics(self) -> None:
61
+ """Always ``None`` — detection has NO train-split metrics, structurally.
62
+
63
+ A torchvision-native model in train mode returns ONLY the loss dict, so there are no
64
+ train-split predictions to score. The shared trainer base carries the slot for the
65
+ tasks that have one; this property pins it to ``None`` here and makes WIRING one a
66
+ loud error instead of a set that would silently never be called.
67
+ """
68
+ return None
69
+
70
+ @train_metrics.setter
71
+ def train_metrics(self, value: Any) -> None:
72
+ if value is not None:
73
+ raise ValueError(
74
+ "detection has deliberately no train_metrics slot: a torchvision-native model "
75
+ "in train mode returns only its loss dict, so a wired train-split metric set "
76
+ "could never be called. Use val_metrics / test_metrics."
77
+ )
78
+
79
+ num_classes: Optional[int]
80
+ #: Labels for the per-class metric report, in class-id order (used when a
81
+ #: ``MeanAveragePrecision(class_metrics=True)`` emits per-class vectors). A detection
82
+ #: target carries ids, not names, so there is no label map to derive them from.
83
+ class_names: Optional[List[str]]
84
+ plot_metrics: bool
85
+
86
+ def initialize(self) -> None:
87
+ """Resolve ``num_classes``, flow the model, and build the per-split metric collections."""
88
+ if self.task == "fit":
89
+ self._initialize_fit()
90
+ else:
91
+ self._initialize_eval()
92
+
93
+ def _initialize_fit(self) -> None:
94
+ self.train_set = self._prepare(self.train_set)
95
+ self.val_set = self._prepare(self.val_set)
96
+ self.test_set = self._prepare(self.test_set)
97
+ nc = self._resolve_num_classes()
98
+ if nc is not None:
99
+ self.num_classes = int(nc)
100
+ if isinstance(self.model, Fluid):
101
+ # Injected ONLY when the deferred builder accepts it — torchvision ships its
102
+ # detectors as builder FUNCTIONS with differing signatures, so a builder without
103
+ # the param is flowed plainly rather than handed a kwarg it would reject.
104
+ if self.num_classes is not None and self._model_accepts_num_classes():
105
+ self.model = flow(self.model, num_classes=self.num_classes)
106
+ else:
107
+ self.model = flow(self.model)
108
+ self._resolve_task_defaults()
109
+ self._build_fit_metrics(include_train=False)
110
+
111
+ def _initialize_eval(self) -> None:
112
+ # The trained model's head is authoritative for eval — flow it first, read num_classes
113
+ # off it. Best-effort: the default MAP metric is class-count-agnostic, so an
114
+ # undeterminable count leaves `num_classes` as-is instead of raising.
115
+ self.model = flow(self.model)
116
+ nc = _model_num_classes(self.model)
117
+ if nc:
118
+ self.num_classes = int(nc)
119
+ self._resolve_task_defaults()
120
+ eval_slot = "val_set" if self.task == "evaluate" else "test_set"
121
+ setattr(self, eval_slot, self._prepare(getattr(self, eval_slot)))
122
+ self._build_eval_metrics()
123
+
124
+ def _model_accepts_num_classes(self) -> bool:
125
+ if not isinstance(self.model, Fluid):
126
+ return False
127
+ target = self.model.target
128
+ resolved = resolve_class(target) if isinstance(target, str) else target
129
+ if resolved is None or not callable(resolved):
130
+ return False
131
+ try:
132
+ params = inspect.signature(resolved).parameters
133
+ except (ValueError, TypeError):
134
+ return False
135
+ return "num_classes" in params or any(p.kind is inspect.Parameter.VAR_KEYWORD for p in params.values())
136
+
137
+ def _resolve_num_classes(self) -> Optional[int]:
138
+ if not isinstance(self.model, Fluid):
139
+ model_nc = _model_num_classes(self.model)
140
+ if model_nc:
141
+ if self.num_classes is not None and int(self.num_classes) != model_nc:
142
+ logger.warning(f"Trainer num_classes={self.num_classes} != model {model_nc}; using the model's.")
143
+ return model_nc
144
+ if self.num_classes is not None:
145
+ return int(self.num_classes)
146
+ if isinstance(self.model, Fluid):
147
+ pinned = self.model.kwargs.get("num_classes")
148
+ if pinned:
149
+ return int(pinned)
150
+ return self._num_classes_from_targets(self.train_set)
151
+
152
+ def _num_classes_from_targets(self, source: Any) -> Optional[int]:
153
+ if source is None:
154
+ return None
155
+ src = flow(source)
156
+ total = len(src) if hasattr(src, "__len__") else None
157
+ logger.info("raidar: deriving num_classes from detection targets (pin num_classes to skip)")
158
+ highest = -1
159
+ for target in tqdm(
160
+ iter_key(src, self.target_key), total=total, desc="raidar: deriving num_classes", unit="record"
161
+ ):
162
+ labels: Any
163
+ if isinstance(target, Boxes):
164
+ labels = target.labels
165
+ elif isinstance(target, dict):
166
+ labels = target.get("labels")
167
+ else:
168
+ continue
169
+ if labels is None:
170
+ continue
171
+ if hasattr(labels, "numel"):
172
+ if int(labels.numel()) == 0:
173
+ continue
174
+ highest = max(highest, int(labels.max()))
175
+ else:
176
+ for x in labels:
177
+ highest = max(highest, int(x))
178
+ return highest + 1 if highest >= 0 else None
@@ -0,0 +1,203 @@
1
+ """``DetectionKerasHooks`` — the detection task's KERAS-family hook implementations.
2
+
3
+ The keras twin of :mod:`raidar.detection_torch`: the task hooks written once for BOTH
4
+ Keras-family machinery bases — the compile/fit member (:class:`matrainer.keras.KerasRunnable`)
5
+ and the native-TensorFlow loop (:class:`matrainer.tensorflow.TensorFlowRunnable`) — so the two
6
+ spec-engine concretes cannot drift apart. A concrete composes
7
+ ``(DetectionKerasHooks, <Machinery>Runnable)``.
8
+
9
+ Detection is the family's odd member, and every oddity is a task fact:
10
+
11
+ * **The batch stacks DENSE MAPS, not ragged boxes** — a detection config's ops chain ends in
12
+ :class:`raidar.fcos.targets.FcosTargets`, which encodes each record's boxes through the
13
+ spec's numpy assignment into fixed-shape per-cell maps. :meth:`_to_arrays` only READS them
14
+ (and transposes the image: the chain keeps the shared CHW ``ToTensor`` — the RGB coercion
15
+ lives there — so the engine's channels-last layout is ONE transpose here).
16
+ * **There is no ``loss:`` slot** — the spec model and its loss are one design, exactly as an
17
+ HF detector's loss lives inside its forward. :meth:`_compiled_loss` hands ``compile()`` the
18
+ spec's three per-output functions positionally, and the TensorFlow concrete's traced step
19
+ sums the same three (from :mod:`raidar.fcos.keras_fcos` — ``keras.ops``, so ONE loss module
20
+ serves both engines).
21
+ * **Detection quality is the SPEC's numpy AP, not compile-slot metrics** — torchmetrics is
22
+ torch-only and Keras ships no variable-size detection metric, so :meth:`_score` decodes the
23
+ raw head maps (:func:`raidar.fcos.spec.decode_predictions`) and scores
24
+ :func:`raidar.fcos.spec.average_precision_50` against the ``Boxes`` ground truth
25
+ ``batch_boxes`` reads back. The engines differ only in HOW a batch is predicted, which is
26
+ the one seam (:meth:`_batch_predictor`).
27
+ * **``evaluate()`` scores the VAL split** (the fleet harmonization) and ``test()`` the
28
+ held-out one — both through :meth:`_score`; neither engine's own eval pass runs, because a
29
+ loss over dense maps is not a detection score.
30
+ """
31
+
32
+ from typing import Any, Callable, Dict, List, Optional
33
+
34
+ import numpy as np
35
+ from confluid import flow
36
+ from loggair import get_logger
37
+ from matrainer.metric_names import as_metric_names
38
+ from recordstream import PredictionsSink, batch_boxes, batch_metadata, batch_values
39
+ from recordstream.keras import keras
40
+
41
+ from raidar.detection_base import DetectionBase
42
+ from raidar.fcos import spec
43
+ from raidar.fcos.keras_fcos import fcos_box_loss, fcos_cls_loss, fcos_ctr_loss
44
+
45
+ logger = get_logger(__name__)
46
+
47
+ __all__ = ["DetectionKerasHooks"]
48
+
49
+
50
+ class DetectionKerasHooks(DetectionBase):
51
+ """The keras-typed detection hooks, shared by the Keras and TensorFlow concretes."""
52
+
53
+ #: Record keys of the dense maps ``FcosTargets`` wrote — stored by the concrete's ctor.
54
+ cls_key: str
55
+ box_key: str
56
+ ctr_key: str
57
+ #: Applied to a STRING-alias optimizer (an instance keeps its own).
58
+ learning_rate: float
59
+ #: The keras family base's members these hooks read/call — declared for the type checker
60
+ #: (the hooks class is always composed with a `<Machinery>Runnable` that provides them).
61
+ optimizer: Any
62
+ _sequence: Callable[..., Any]
63
+
64
+ # ---- the batch boundary ----------------------------------------------------------------- #
65
+ def _to_arrays(self, batch: Any, with_targets: bool = True) -> Any:
66
+ """Image transposed to channels-last; targets = the three dense maps, NESTED.
67
+
68
+ The nested ``(x, (cls, box, ctr))`` is what ``keras.Model.fit`` consumes against a
69
+ three-output model; the TensorFlow concrete overrides with the FLAT tuple its traced
70
+ step's arity wants.
71
+ """
72
+ x = np.transpose(np.asarray(batch_values(batch, self.input_key), dtype="float32"), (0, 2, 3, 1))
73
+ if not with_targets:
74
+ return (x,)
75
+ y = (
76
+ np.asarray(batch_values(batch, self.cls_key), dtype="float32"),
77
+ np.asarray(batch_values(batch, self.box_key), dtype="float32"),
78
+ np.asarray(batch_values(batch, self.ctr_key), dtype="float32"),
79
+ )
80
+ return x, y
81
+
82
+ # ---- the compile seams (the compile/fit member's) ---------------------------------------- #
83
+ def _spec_losses(self) -> Any:
84
+ """The spec's three per-output losses, positionally matched to the raw head maps.
85
+
86
+ The box loss is a closure (the raw-to-distance scale closes over the model's stride),
87
+ renamed after itself — Keras names history columns from the FUNCTION name, and a bare
88
+ ``loss`` there would log the box component as the ambiguous ``loss_loss``.
89
+ """
90
+ box_loss = fcos_box_loss(float(getattr(self.model, "spec_stride", spec.stride())))
91
+ box_loss.__name__ = "fcos_box_loss"
92
+ return [fcos_cls_loss, box_loss, fcos_ctr_loss]
93
+
94
+ def _compiled_loss(self) -> Any:
95
+ return self._spec_losses()
96
+
97
+ def _compiled_optimizer(self) -> Any:
98
+ """A string alias gets the task's ``learning_rate``; an instance keeps its own.
99
+
100
+ YAML floats like ``1e-3`` may arrive as strings, hence the coercion.
101
+ """
102
+ optimizer = flow(self.optimizer)
103
+ if isinstance(optimizer, str):
104
+ return keras.optimizers.get(
105
+ {"class_name": optimizer, "config": {"learning_rate": float(self.learning_rate)}}
106
+ )
107
+ return optimizer
108
+
109
+ # ---- the spec's eval path ---------------------------------------------------------------- #
110
+ def _batch_predictor(self) -> Callable[[np.ndarray], Any]:
111
+ """One callable mapping an image batch to the three raw head maps — THE engine seam.
112
+
113
+ The compile/fit member predicts through the compiled model; the TensorFlow concrete
114
+ overrides with its traced predict step (built ONCE — a fresh trace per batch retraces).
115
+ """
116
+ return lambda x: self.model.predict(x, verbose=0)
117
+
118
+ def _decode_config(self) -> Dict[str, Any]:
119
+ """The decode knobs, read off the model wrapper (spec defaults for a bare model)."""
120
+ return {
121
+ "input_shape": tuple(getattr(self.model, "input_shape", spec.INPUT_SHAPE)),
122
+ "widths": tuple(getattr(self.model, "widths", spec.BACKBONE_WIDTHS)),
123
+ "score_threshold": float(getattr(self.model, "score_threshold", 0.05)),
124
+ "iou_threshold": float(getattr(self.model, "iou_threshold", 0.5)),
125
+ "max_detections": int(getattr(self.model, "max_detections", 100)),
126
+ }
127
+
128
+ def _decoded_maps(self, maps: Any) -> List[Dict[str, np.ndarray]]:
129
+ """Raw head maps → per-image scored boxes, through the spec's numpy decode."""
130
+ cls_map, box_map, ctr_map = maps
131
+ config = self._decode_config()
132
+ return [
133
+ spec.decode_predictions(
134
+ np.asarray(cls_map[i]), np.asarray(box_map[i]), np.asarray(np.asarray(ctr_map[i])[..., 0]), **config
135
+ )
136
+ for i in range(len(cls_map))
137
+ ]
138
+
139
+ def _score(self, source: Any) -> Dict[str, float]:
140
+ """Decode a split and score it with the spec's AP50 — the numpy scoring path.
141
+
142
+ The ground truth comes from the batched record's ``target_key`` — the plain
143
+ ``{"boxes", "labels"}`` dicts ``FcosTargets`` left beside the dense maps, batched as a
144
+ per-record list and read back by ``batch_boxes``.
145
+ """
146
+ predict = self._batch_predictor()
147
+ sequence = self._sequence(source, with_targets=False)
148
+ predictions: List[Dict[str, np.ndarray]] = []
149
+ targets: List[Dict[str, np.ndarray]] = []
150
+ for index, batch in enumerate(sequence.batches()):
151
+ predictions.extend(self._decoded_maps(predict(sequence[index][0])))
152
+ targets.extend(batch_boxes(batch, self.target_key))
153
+ return spec.average_precision_50(predictions, targets)
154
+
155
+ # ---- the fit epilogue + the eval/predict entry points ------------------------------------ #
156
+ def _fit_scores(self, final: Dict[str, float]) -> Dict[str, float]:
157
+ """Append the spec's AP over the validation split — the engine's own history carries
158
+ losses only (no compile-slot metric can score variable-size detections)."""
159
+ if self.val_set is not None:
160
+ final.update({f"val_{k}": v for k, v in self._score(self.val_set).items()})
161
+ return final
162
+
163
+ def evaluate(self) -> None:
164
+ """Score the VALIDATION split with the spec's AP (the fleet harmonization)."""
165
+ if self.val_set is None:
166
+ raise ValueError(f"{type(self).__name__}.evaluate() requires a 'val_set'.")
167
+ self._computed_metrics = as_metric_names(self.metric_names)(
168
+ self._score(self.val_set), source="keras", split="val"
169
+ )
170
+ logger.info(f"Evaluation complete: {self._computed_metrics}")
171
+ self._write_eval_sidecar()
172
+
173
+ def test(self) -> None:
174
+ if self.test_set is None:
175
+ raise ValueError(f"{type(self).__name__}.test() requires a 'test_set'.")
176
+ self._computed_metrics = as_metric_names(self.metric_names)(
177
+ self._score(self.test_set), source="keras", split="test"
178
+ )
179
+ logger.info(f"Evaluation complete: {self._computed_metrics}")
180
+ self._write_eval_sidecar()
181
+
182
+ def _write_eval_sidecar(self) -> None:
183
+ from matrainer.artifacts import write_metrics_sidecar
184
+
185
+ write_metrics_sidecar(self.metrics_sidecar_path, self._computed_metrics, self.experiment_name, self.run_name)
186
+
187
+ def predict(self) -> None:
188
+ """Stream per-image DECODED detections to the sink — the spec's decode IS the task's
189
+ prediction contract, so there is nothing further to wrap."""
190
+ if self.test_set is None:
191
+ raise ValueError(f"{type(self).__name__}.predict() requires a 'test_set'.")
192
+ sink: Optional[PredictionsSink] = flow(self.predictions_sink)
193
+ predict = self._batch_predictor()
194
+ sequence = self._sequence(self.test_set, with_targets=False)
195
+ for index, batch in enumerate(sequence.batches()):
196
+ decoded = self._decoded_maps(predict(sequence[index][0]))
197
+ if sink is not None:
198
+ meta = batch_metadata(batch, exclude=(self.input_key, self.target_key))
199
+ for i, prediction in enumerate(decoded):
200
+ sink.write(prediction, meta[i] if meta and i < len(meta) else {})
201
+ if sink is not None and hasattr(sink, "close"):
202
+ sink.close()
203
+ logger.info("Prediction complete.")