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.
@@ -0,0 +1,78 @@
1
+ """``DetectionTorchHooks`` — the torch-family implementations of the task hooks.
2
+
3
+ The detection answers to the trainer API's typed hooks
4
+ (:class:`matrainer.torch.runnable.TorchTrainerRunnable`): the COCO-mAP default metric, the
5
+ ``_reportable`` strip of MAP's pseudo-metric ``classes`` key, and the per-class vector
6
+ reporting. Deliberately NO ``_targets`` implementation — a native detection model reads its
7
+ batch inside the (overridden) step functions via ``native_batch``, which is why the family
8
+ base's default raises with exactly that explanation.
9
+
10
+ NOT to be confused with :mod:`raidar.torch_detection` (the torch ENGINE's registered metric
11
+ set + ``native_batch``): that one registers/adapts, this one implements hooks. This module
12
+ imports torch, so the four spec engines must never import it.
13
+ """
14
+
15
+ from typing import Any, List, Mapping, Optional
16
+
17
+ import torch
18
+ from confluid import PartialClass
19
+ from loggair import get_logger
20
+ from matrainer.torch.metrics import MetricsSpec
21
+ from matrainer.torch.runnable import TorchTrainerRunnable
22
+ from matrainer.tracking.base import Tracker
23
+ from matrainer.tracking.render import report_vectors
24
+ from torchmetrics import Metric
25
+ from torchmetrics.detection import MeanAveragePrecision
26
+
27
+ from raidar.detection_base import DetectionBase
28
+ from raidar.torch_detection import reportable_metrics
29
+
30
+ logger = get_logger(__name__)
31
+
32
+ __all__ = ["DetectionTorchHooks"]
33
+
34
+
35
+ class DetectionTorchHooks(DetectionBase, TorchTrainerRunnable):
36
+ """The torch half of the detection task, mixed into every torch-family backend."""
37
+
38
+ #: Declared on each concrete's flat ctor (`seed: int = 0`) and stored there; applied ONCE
39
+ #: here so the three torchvision-family backends cannot drift apart on when it fires.
40
+ seed: int
41
+
42
+ def initialize(self) -> None:
43
+ """Seed torch's global RNG, THEN run the task base's setup — which builds the model.
44
+
45
+ The torchvision builders randomly reinitialize their ``num_classes`` head on every
46
+ build and no framework covers that draw (Lightning's ``seed_everything`` is not wired
47
+ and the other two loops are ours), so the zoo cells' losses moved between identical
48
+ sweep runs (measured 2026-08-08/09). Seeding at BUILD time without restoring the RNG
49
+ state is the workspace's wrapper-seeding idiom (the restoration project's 2026-08-06
50
+ precedent): a run-level seed applied at the earliest useful moment, covering the
51
+ DataLoader shuffle draws too. The spec model (``TorchFcos``) additionally seeds
52
+ itself — its knob binds the ARCHITECTURE comparison, this one binds the RUN.
53
+ """
54
+ torch.manual_seed(self.seed)
55
+ super().initialize()
56
+
57
+ def _default_metrics(self) -> MetricsSpec:
58
+ """COCO mAP, the field's primary detection score.
59
+
60
+ Class-count-agnostic, so unlike the classification/segmentation defaults it needs no
61
+ ``num_classes`` (and `_metric_flow_dims` stays the empty default: detection metrics
62
+ score box overlap, not a fixed-width head).
63
+ """
64
+ return {"map": PartialClass[Metric](MeanAveragePrecision, iou_type="bbox")}
65
+
66
+ def _reportable(self, values: Mapping[str, Any]) -> Mapping[str, Any]:
67
+ """Drop MAP's ``classes`` key on EVERY reporting path.
68
+
69
+ It is the OBSERVED class ids, not a metric: with one class seen it is a 0-dim int (a
70
+ bogus scalar), with several a vector that passes the shape-based per-class rule (a
71
+ bogus table).
72
+ """
73
+ return reportable_metrics(values)
74
+
75
+ def _report_nonscalars(self, values: Mapping[str, Any], step: Optional[int], trackers: List[Tracker]) -> None:
76
+ """Per-class VECTORS (``MeanAveragePrecision(class_metrics=True)``'s ``map_per_class``
77
+ / ``mar_100_per_class``) to the log + every tracker's text (and figure) channel."""
78
+ report_vectors(values, self.class_names or None, trackers, step=step, plot=self.plot_metrics)
@@ -0,0 +1,346 @@
1
+ """``FastaiDetector`` — the same detection run with a fastai ``Learner``.
2
+
3
+ The fastai member of the detection fleet, assembled from the workspace trainer bases
4
+ (2026-08-07): the Learner machinery — the ``DataLoaders``/``Learner`` assembly, the Recorder
5
+ read-back, the plain-function tracking hookup — is ``matrainer.fastai.FastaiRunnable``, and the
6
+ detection task is the SAME :mod:`raidar.detection_base` + :mod:`raidar.detection_torch` pair
7
+ every torch-family backend runs on. What remains HERE is the config surface (the full flat
8
+ constructor) plus the NO-OP-LOSS BRIDGE the loss-inside-forward contract needs:
9
+
10
+ * a fastai ``Learner`` computes ``loss_func(model(*xb), *yb)``, but the native detection
11
+ contract computes its loss INSIDE the train-mode forward — so :func:`fastai_detection_collate`
12
+ packs ``((images, targets), dummy_y)`` (both ride in ``xb``),
13
+ :class:`NativeDetectionAdapter`'s training forward returns the SUMMED loss dict as the
14
+ "prediction", and :func:`passthrough_loss` hands it to backprop unchanged — ONE forward, the
15
+ fit loop untouched;
16
+ * the eval forward returns the per-image prediction list and the pass-through loss returns a
17
+ ZERO scalar for fastai's bookkeeping — the recorded ``valid_loss`` is MEANINGLESS under this
18
+ contract and is DROPPED from what the run records rather than smoothed over;
19
+ * validation quality comes from the SAME torchmetrics collections every other backend builds
20
+ (the family builders are RESTORED here — the base leaves the metric slots as fastai name
21
+ lists, which this contract does not use), fed by :class:`DetectionMetricsCallback` because no
22
+ fastai metric consumes a per-image prediction list.
23
+
24
+ Run it with ``raidar train cfg.yaml --framework fastai``.
25
+ """
26
+
27
+ from functools import partial
28
+ from typing import Any, Callable, Dict, Iterable, List, Optional, Sequence, Tuple, Union, cast
29
+
30
+ import torch
31
+ import torch.nn as nn
32
+ from confluid import Mandatory, Partial, configurable
33
+ from fastai.callback.core import Callback as FastaiCallback
34
+ from fastai.data.core import DataLoaders
35
+ from fastai.learner import Learner
36
+ from loggair import get_logger
37
+ from matrainer.fastai import FastaiOptimizer, FastaiRunnable
38
+ from matrainer.metric_names import MetricNames, as_metric_names
39
+ from matrainer.torch import Device, resolve_device, scalar_metrics
40
+ from matrainer.torch.metrics import MetricsSpec
41
+ from matrainer.torch.runnable import TorchTrainerRunnable
42
+ from matrainer.tracking.base import Tracker
43
+ from recordstream import RecordSource, collate_list
44
+ from recordstream.items import Record
45
+ from recordstream.runnable import RunnableTask
46
+ from torchmetrics import Metric, MetricCollection
47
+
48
+ from raidar.detection_torch import DetectionTorchHooks
49
+ from raidar.torch_detection import native_batch
50
+
51
+ logger = get_logger(__name__)
52
+
53
+ #: Which entry point :meth:`FastaiDetector.run` dispatches to (the standard four).
54
+ DetectorTask = RunnableTask
55
+
56
+ __all__ = ["DetectorTask", "FastaiDetector", "MetricsSpec", "NativeDetectionAdapter", "passthrough_loss"]
57
+
58
+
59
+ def fastai_detection_collate(
60
+ records: Sequence[Any], input_key: str = "image", target_key: str = "target"
61
+ ) -> Tuple[Any, torch.Tensor]:
62
+ """The fastai twin of the shared detection collate — ``((images, targets), dummy_y)``.
63
+
64
+ fastai unpacks a batch positionally into ``(xb, yb)`` and calls ``model(*xb)``, but the
65
+ native train-mode forward needs the targets IN the call — so BOTH ride in ``xb`` and ``yb``
66
+ is a dummy the pass-through loss ignores. Built ON the shared collate, so the record keys and
67
+ the never-pad-never-drop target rule stay one implementation.
68
+ """
69
+ batch = collate_list(list(records))
70
+ images, targets = native_batch(batch, input_key, target_key)
71
+ return (images, targets), torch.zeros(len(images))
72
+
73
+
74
+ class NativeDetectionAdapter(nn.Module):
75
+ """The no-op-loss bridge: training forward returns the SUMMED loss dict as the "prediction".
76
+
77
+ In eval mode it returns the model's per-image prediction list — the same objects the fleet's
78
+ torchmetrics consume — and the pass-through loss then reports a zero ``valid_loss``.
79
+ """
80
+
81
+ def __init__(self, model: nn.Module) -> None:
82
+ super().__init__()
83
+ self.model = model
84
+
85
+ def forward(self, payload: Tuple[Any, Any]) -> Any:
86
+ images, targets = payload
87
+ if self.training:
88
+ if targets is None:
89
+ raise ValueError("FastaiDetector training requires targets on the batch.")
90
+ loss_dict = self.model(images, targets)
91
+ if not isinstance(loss_dict, dict):
92
+ raise TypeError(
93
+ f"Detection model in train mode must return Dict[str, Tensor] (a loss dict); "
94
+ f"got {type(loss_dict).__name__}."
95
+ )
96
+ return cast(torch.Tensor, sum(loss_dict.values()))
97
+ return self.model(images)
98
+
99
+
100
+ def passthrough_loss(prediction: Any, *_: Any) -> torch.Tensor:
101
+ """The no-op loss: the model already computed it — pass the scalar through unchanged.
102
+
103
+ On the validation pass the "prediction" is the per-image list, for which no loss exists
104
+ under this contract — a ZERO scalar keeps fastai's bookkeeping running, and the recorded
105
+ ``valid_loss`` of 0 is documented as meaningless rather than smoothed over.
106
+ """
107
+ if isinstance(prediction, torch.Tensor) and prediction.ndim == 0:
108
+ return prediction
109
+ return torch.zeros((), requires_grad=False)
110
+
111
+
112
+ class DetectionMetricsCallback(FastaiCallback):
113
+ """Feed the validation pass's predictions to the fleet's torchmetrics collection.
114
+
115
+ ``Learner.metrics`` cannot serve here (no fastai metric consumes a per-image prediction
116
+ list), so the SAME ``MetricCollection`` every other backend builds is updated from a
117
+ callback: on each non-training batch the adapter's prediction list and the targets packed in
118
+ ``xb`` are handed to ``update()``. The runnable computes/reports at the end.
119
+ """
120
+
121
+ def __init__(self, collection: Optional[MetricCollection]) -> None:
122
+ self.collection = collection
123
+
124
+ def after_pred(self) -> None:
125
+ if self.training or self.collection is None:
126
+ return
127
+ predictions = self.learn.pred
128
+ targets = self.learn.xb[0][1]
129
+ if isinstance(predictions, list) and targets is not None:
130
+ self.collection.update(predictions, targets)
131
+
132
+
133
+ @configurable(task="detection", role="trainer", framework="torch")
134
+ class FastaiDetector(DetectionTorchHooks, FastaiRunnable):
135
+ """Train, evaluate or predict an object detector with a fastai ``Learner``.
136
+
137
+ Args:
138
+ model: Torchvision-native detection model — wire ``!lazy:`` so :meth:`initialize` can
139
+ inject the resolved ``num_classes``. Wrapped in :class:`NativeDetectionAdapter` for
140
+ the Learner (the no-op-loss design; see the module docstring).
141
+ train_set: Training source (``task="fit"``).
142
+ test_set: Held-out source (``task="test"`` / ``"predict"``).
143
+ num_classes: Class count (torchvision-style incl. background). Omitted, derived from the
144
+ model head or the train targets.
145
+ task: Which entry point ``run()`` dispatches to.
146
+ max_epochs / batch_size / num_workers: the shared knobs.
147
+ persistent_workers: Override the pairing derived from ``num_workers`` (``None`` derives
148
+ ``num_workers != 0``). An explicit value is for a HOST fact no derivation can see —
149
+ macOS terminates persistent workers slowly, so a config there sets ``false`` while
150
+ keeping its workers. ``True`` with ``num_workers=0`` is refused.
151
+ learning_rate: Peak LR — ``lr_max`` for one-cycle, ``lr`` otherwise.
152
+ weight_decay: fastai's ``wd``. ``None`` is fastai's own default.
153
+ one_cycle: Use ``fit_one_cycle`` (fastai's headline scheduler) instead of plain ``fit``.
154
+ opt_func: A ``fastai.optimizer`` function or its name (``"Adam"``, ``"SGD"``, …).
155
+ metrics: torchmetrics templates for the EVAL splits — the fleet vocabulary, fed through
156
+ :class:`DetectionMetricsCallback`. ``val_metrics`` / ``test_metrics`` merge over it.
157
+ No ``train_metrics``: the training pass computes the loss dict and nothing else
158
+ (wiring one raises loudly, via the task base's guarding property).
159
+ device: Where to run — see :data:`Device`. Carried onto the ``DataLoaders`` so fastai's
160
+ own placement callback honours it (see :meth:`_place`).
161
+ class_names: Labels for the per-class metric report, in class-id order.
162
+ plot_metrics: ALSO send each per-class metric to the trackers as a bar chart.
163
+ seed: Seed for torch's global RNG, applied when `initialize()` builds the model —
164
+ the torchvision builders randomly reinitialize their `num_classes` head, and no
165
+ framework covers that draw. Applied without restoring the RNG state (the
166
+ workspace wrapper-seeding idiom), so the loader shuffle is seeded too.
167
+ metric_names: How recorded metrics are named. This backend reports through its OWN
168
+ torchmetrics pass under canonical names; the Recorder's ``train_loss`` is translated
169
+ from fastai's vocabulary.
170
+ callbacks: fastai callbacks.
171
+ trackers: matrainer trackers — one or a list.
172
+ experiment_name: Run identity, recorded in artifacts and tracking.
173
+ run_name: Run identity; a random ``adjective_noun`` when omitted.
174
+ input_key: Record key holding the image.
175
+ target_key: Record key holding the detection target ``Boxes``.
176
+
177
+ Optional OVERRIDE slots — every one is already constructed with a sensible default in
178
+ ``__init__``, so nothing here NEEDS wiring; a same-named top-level YAML key replaces one
179
+ via broadcasting when you want to: ``val_set``, ``train/val/test_loader``, ``dataloaders``,
180
+ ``learner``, ``predictions_sink``, ``metrics_sidecar_path``.
181
+ """
182
+
183
+ def __init__(
184
+ self,
185
+ model: Optional[Mandatory[Partial[nn.Module]]] = None,
186
+ train_set: Optional[Partial[RecordSource]] = None,
187
+ test_set: Optional[Partial[RecordSource]] = None,
188
+ num_classes: Optional[int] = None,
189
+ task: DetectorTask = "fit",
190
+ max_epochs: int = 10,
191
+ batch_size: int = 2,
192
+ num_workers: int = 0,
193
+ persistent_workers: Optional[bool] = None,
194
+ learning_rate: float = 1e-4,
195
+ weight_decay: Optional[float] = None,
196
+ one_cycle: bool = True,
197
+ opt_func: FastaiOptimizer = "Adam",
198
+ metrics: MetricsSpec = None,
199
+ val_metrics: MetricsSpec = None,
200
+ test_metrics: MetricsSpec = None,
201
+ device: Device = "auto",
202
+ class_names: Optional[List[str]] = None,
203
+ plot_metrics: bool = False,
204
+ seed: int = 0,
205
+ metric_names: Optional[Partial[MetricNames]] = None,
206
+ callbacks: Optional[List[Partial[FastaiCallback]]] = None,
207
+ trackers: Optional[Union[Partial[Tracker], Iterable[Partial[Tracker]]]] = None,
208
+ experiment_name: str = "raidar_detection",
209
+ run_name: Optional[str] = None,
210
+ input_key: str = "image",
211
+ target_key: str = "target",
212
+ ) -> None:
213
+ super().__init__(
214
+ model=model,
215
+ train_set=train_set,
216
+ test_set=test_set,
217
+ task=task,
218
+ max_epochs=max_epochs,
219
+ batch_size=batch_size,
220
+ num_workers=num_workers,
221
+ persistent_workers=persistent_workers,
222
+ trackers=trackers,
223
+ experiment_name=experiment_name,
224
+ run_name=run_name,
225
+ input_key=input_key,
226
+ target_key=target_key,
227
+ metrics=metrics,
228
+ val_metrics=val_metrics,
229
+ test_metrics=test_metrics,
230
+ metric_names=metric_names,
231
+ learning_rate=learning_rate,
232
+ weight_decay=weight_decay,
233
+ one_cycle=one_cycle,
234
+ opt_func=opt_func,
235
+ callbacks=callbacks,
236
+ # The batch SHAPE is DECLARED: the no-op-loss packing over the shared list collate.
237
+ collate_fn=partial(fastai_detection_collate, input_key=str(input_key), target_key=str(target_key)),
238
+ )
239
+ self.num_classes = int(num_classes) if num_classes is not None else None
240
+ self.device_choice: Device = device
241
+ self.class_names: Optional[List[str]] = list(class_names) if class_names else None
242
+ self.plot_metrics = plot_metrics
243
+ self.seed = int(seed)
244
+
245
+ # ---- the torchmetrics half the base leaves open ----------------------------------------- #
246
+ def _build_fit_metrics(self, include_train: bool = True) -> None:
247
+ """RESTORED family builders: this contract scores through torchmetrics collections
248
+ (fed by :class:`DetectionMetricsCallback`), not through ``Learner.metrics`` names —
249
+ the case the base's no-op documents."""
250
+ TorchTrainerRunnable._build_fit_metrics(self, include_train=False)
251
+
252
+ def _build_eval_metrics(self) -> None:
253
+ TorchTrainerRunnable._build_eval_metrics(self)
254
+
255
+ def _active_collection(self, split: str) -> Optional[MetricCollection]:
256
+ if split == "val" and self.task == "fit":
257
+ return cast(Optional[MetricCollection], self.val_metrics if self.val_set is not None else None)
258
+ return cast(Optional[MetricCollection], getattr(self, f"{split}_metrics"))
259
+
260
+ def _reduce_collection(self, collection: Optional[MetricCollection]) -> Dict[str, float]:
261
+ """Compute + report + RESET the collection — scalars returned, vectors through the
262
+ task hooks to the text channel (the same reporting every other backend does)."""
263
+ if not isinstance(collection, (Metric, MetricCollection)):
264
+ return {}
265
+ computed = self._reportable(collection.compute())
266
+ self._report_nonscalars(computed, None, self._live_trackers())
267
+ values = scalar_metrics(computed)
268
+ collection.reset()
269
+ return values
270
+
271
+ # ---- the no-op-loss bridge, hung on the base's Learner seams ---------------------------- #
272
+ def _learner_model(self) -> nn.Module:
273
+ inner = super()._learner_model() # the nn.Module validation
274
+ self._device = resolve_device(self.device_choice)
275
+ inner.to(self._device)
276
+ return NativeDetectionAdapter(inner)
277
+
278
+ def _learner_loss(self) -> Any:
279
+ return passthrough_loss
280
+
281
+ def _learner_metric_objects(self, split: str) -> List[Any]:
282
+ # `Learner.metrics` stays EMPTY — no fastai metric consumes a per-image prediction
283
+ # list; the torchmetrics collection is fed from the callback below instead.
284
+ return []
285
+
286
+ def _learner_callbacks(self, split: str) -> List[Any]:
287
+ return [DetectionMetricsCallback(self._active_collection(split))] + self._callbacks()
288
+
289
+ def _place(self, dataloaders: DataLoaders) -> DataLoaders:
290
+ """Carry this run's device onto the ``DataLoaders`` so fastai's own callback honours it.
291
+
292
+ ``TrainEvalCallback.before_fit`` runs ``self.model.to(getattr(dls, 'device',
293
+ default_device()))`` — and over PLAIN torch loaders ``dls.device`` raises (fastcore's
294
+ attribute delegation reaches the first loader, which has no ``device``), so the fallback
295
+ is ``default_device()``: on Apple silicon the cpu model was silently moved to MPS and the
296
+ measured step went 1.0 s → **32.9 s** (torchvision detection's ~30x MPS fallback, hit for
297
+ real on the first cppe-5 run). The PUBLIC setter cannot carry the pin — it recurses
298
+ ``dl.to(d)`` into the plain loaders and raises — so the private ``_device`` field the
299
+ getter reads is the working route (the workspace's known-private-API precedent: used
300
+ knowingly because the public alternative is broken, with the measurement recorded).
301
+ """
302
+ self._device = resolve_device(self.device_choice)
303
+ dataloaders._device = self._device
304
+ return dataloaders
305
+
306
+ # ---- what a run RECORDS (the Recorder holds only train_loss here) ----------------------- #
307
+ def _fit_results(self, learner: Learner, names: MetricNames) -> Dict[str, float]:
308
+ logs = _recorded_train_loss(learner, names)
309
+ logs.update(names(self._reduce_collection(self._active_collection("val"))))
310
+ return logs
311
+
312
+ def _log_epoch_history(self, learner: Learner, trackers: Sequence[Tracker], names: MetricNames) -> None:
313
+ """Every epoch's ``train_loss`` — the only Recorder column that means anything here —
314
+ plus the final torchmetrics scores, which live outside the Recorder entirely."""
315
+ for epoch, row in enumerate(list(getattr(learner.recorder, "values", []) or [])):
316
+ metrics = names({"train_loss": float(row[0])}, source="fastai")
317
+ for tracker in trackers:
318
+ tracker.log_metrics(metrics, step=epoch)
319
+ for tracker in trackers:
320
+ tracker.log_metrics(self._computed_metrics)
321
+
322
+ def _validate_results(self, learner: Learner, values: Sequence[Any], split: str) -> Dict[str, float]:
323
+ """The torchmetrics scores — the Learner's own row is a meaningless zero loss."""
324
+ results = as_metric_names(self.metric_names)(self._reduce_collection(self._active_collection(split)))
325
+ for tracker in self._live_trackers():
326
+ tracker.log_metrics(results)
327
+ return results
328
+
329
+ # ---- predict: a plain forward over the record-shaped batch ------------------------------ #
330
+ def _record_collate(self) -> Callable[[List[Record]], Any]:
331
+ return collate_list
332
+
333
+ @torch.no_grad()
334
+ def _predict_batch(self, batch: Record, device: torch.device) -> Any:
335
+ images, _ = native_batch(batch, self.input_key, self.target_key)
336
+ return cast(nn.Module, self.model)([image.to(device) for image in images])
337
+
338
+
339
+ def _recorded_train_loss(learner: Learner, names: MetricNames) -> Dict[str, float]:
340
+ """The last epoch's ``train_loss`` in canonical spelling. ``valid_loss`` is DROPPED — under
341
+ the no-op-loss contract it is a recorded zero, and a meaningless number under a real-looking
342
+ name is worse than a gap."""
343
+ rows = list(getattr(learner.recorder, "values", []) or [])
344
+ if not rows:
345
+ return {}
346
+ return names({"train_loss": float(rows[-1][0])}, source="fastai")
@@ -0,0 +1,8 @@
1
+ """The shared tiny-FCOS spec and its per-framework implementations.
2
+
3
+ This ``__init__`` imports NOTHING, and that is load-bearing: ``raidar/__init__.py`` resolves
4
+ every backend name lazily so a machine without torch never imports it, and a re-export here
5
+ would drag a framework in the moment anything under the package — including the
6
+ dependency-free ``spec.py`` — is touched. Import the implementation you want by module:
7
+ ``from raidar.fcos.torch_fcos import TorchFcos``.
8
+ """
@@ -0,0 +1,165 @@
1
+ """``FlaxFcos`` — the shared tiny-FCOS spec in ``flax.nnx``, the JAX backend's model.
2
+
3
+ The JAX entry in the comparison :mod:`raidar.fcos.spec` describes, and it wraps no zoo — which
4
+ here is not a design choice but the only option: there is no Flax detection zoo to wrap
5
+ (``transformers`` dropped Flax entirely in v5). So the JAX backend implements the spec natively,
6
+ which is exactly why the spec exists.
7
+
8
+ It IS an ``nnx.Module``, the same decision as its siblings being their framework's own model
9
+ type: the detector drives whatever is wired into its ``model`` slot without asking what it got,
10
+ and ``nnx.state`` / ``nnx.Optimizer`` reach the parameters straight through the wrapper.
11
+
12
+ **Channels-LAST** (``[N, H, W, C]``), like every implementation except the torch one.
13
+
14
+ One Flax fact shapes the lazy build (measured in the segmentation project): an attribute first
15
+ assigned ``None`` in ``__init__`` becomes STATIC in nnx's pytree, and assigning a Module to it
16
+ later raises — ``nnx.data`` is the fix flax itself names, and it is what keeps zero-arg
17
+ construction compatible with building at ``flow()`` time.
18
+ """
19
+
20
+ from typing import Any, Tuple
21
+
22
+ from confluid import configurable
23
+ from flax import nnx
24
+ from loggair import get_logger
25
+
26
+ from raidar.fcos.spec import BACKBONE_WIDTHS, HEAD_WIDTH, INPUT_SHAPE, KERNEL_SIZE, grid_size, stride
27
+
28
+ logger = get_logger(__name__)
29
+
30
+ __all__ = ["FlaxFcos"]
31
+
32
+
33
+ class _ConvBnRelu(nnx.Module):
34
+ """``conv -> BN -> ReLU`` — the spec's repeated unit, in ``flax.nnx``."""
35
+
36
+ def __init__(self, in_channels: int, width: int, rngs: Any, conv_stride: int = 1) -> None:
37
+ self.conv = nnx.Conv(
38
+ in_channels,
39
+ width,
40
+ kernel_size=(KERNEL_SIZE, KERNEL_SIZE),
41
+ strides=(conv_stride, conv_stride),
42
+ rngs=rngs,
43
+ )
44
+ self.norm = nnx.BatchNorm(width, rngs=rngs)
45
+
46
+ def __call__(self, x: Any, training: bool = False) -> Any:
47
+ # `use_running_average` is the INVERSE of "training": in eval we consume the running
48
+ # statistics rather than the batch's, exactly as keras and torch do.
49
+ return nnx.relu(self.norm(self.conv(x), use_running_average=not training))
50
+
51
+
52
+ class _Fcos(nnx.Module):
53
+ """The spec's layer graph: strided backbone → shared trunk → the three 1x1 heads."""
54
+
55
+ def __init__(self, num_classes: int, in_channels: int, widths: Tuple[int, ...], head_width: int, seed: int) -> None:
56
+ rngs = nnx.Rngs(seed)
57
+ self.stages: Any = nnx.List([])
58
+ channels = in_channels
59
+ for width in widths:
60
+ self.stages.append(_ConvBnRelu(channels, width, rngs))
61
+ self.stages.append(_ConvBnRelu(width, width, rngs, conv_stride=2)) # halves H and W
62
+ channels = width
63
+ self.trunk = _ConvBnRelu(channels, head_width, rngs)
64
+ # The three 1x1 heads: raw outputs, NO activation — the spec's decode/loss own the
65
+ # sigmoid/exp transforms.
66
+ self.cls_head = nnx.Conv(head_width, num_classes, kernel_size=(1, 1), rngs=rngs)
67
+ self.box_head = nnx.Conv(head_width, 4, kernel_size=(1, 1), rngs=rngs)
68
+ self.ctr_head = nnx.Conv(head_width, 1, kernel_size=(1, 1), rngs=rngs)
69
+
70
+ def __call__(self, x: Any, training: bool = False) -> Any:
71
+ for stage in self.stages:
72
+ x = stage(x, training=training)
73
+ x = self.trunk(x, training=training)
74
+ return self.cls_head(x), self.box_head(x), self.ctr_head(x)
75
+
76
+
77
+ @configurable(task="detection", role="model", lazy=True, framework="jax")
78
+ class FlaxFcos(nnx.Module):
79
+ """The shared tiny-FCOS spec (:mod:`raidar.fcos.spec`), implemented in ``flax.nnx``.
80
+
81
+ Args:
82
+ num_classes: Width of the per-cell class head. Sentinel ``0`` is invalid but permitted so
83
+ the class is zero-arg constructible; a detector flows the resolved count in at run time.
84
+ input_shape: ``(H, W, C)`` — channels LAST, which is also this engine's tensor layout.
85
+ widths: Channels per backbone stage. Changing it breaks comparability with the other
86
+ implementations — see :mod:`raidar.fcos.spec`.
87
+ head_width: Channels of the shared head trunk.
88
+ score_threshold: Eval-time decode floor — read by the backend's numpy decode.
89
+ iou_threshold: Eval-time per-class NMS overlap threshold.
90
+ max_detections: Eval-time cap on detections per image.
91
+ seed: Seed for the ``nnx.Rngs`` the initializers draw from — explicit randomness is the
92
+ JAX story, and this knob is what makes a config reproduce its weights.
93
+ """
94
+
95
+ def __init__(
96
+ self,
97
+ num_classes: int = 0,
98
+ input_shape: Tuple[int, int, int] = INPUT_SHAPE,
99
+ widths: Tuple[int, ...] = BACKBONE_WIDTHS,
100
+ head_width: int = HEAD_WIDTH,
101
+ score_threshold: float = 0.05,
102
+ iou_threshold: float = 0.5,
103
+ max_detections: int = 100,
104
+ seed: int = 0,
105
+ ) -> None:
106
+ # Partial: store only. No parameter allocation — the workspace zero-arg mandate.
107
+ self.num_classes = num_classes
108
+ self.input_shape = tuple(input_shape)
109
+ self.widths = tuple(widths)
110
+ self.head_width = head_width
111
+ self.score_threshold = float(score_threshold)
112
+ self.iou_threshold = float(iou_threshold)
113
+ self.max_detections = int(max_detections)
114
+ self.seed = seed
115
+ # `nnx.data`: a bare `None` would become a STATIC pytree attribute, and assigning the
116
+ # built network to it later RAISES (measured in the segmentation project).
117
+ self._model: Any = nnx.data(None)
118
+
119
+ def solidify(self) -> Any:
120
+ """Build (once) and return the live network — confluid's ``flow()``-time hook."""
121
+ if self._model is None:
122
+ if not self.num_classes:
123
+ raise ValueError(
124
+ "FlaxFcos.num_classes is not set — a detector flows the resolved count in "
125
+ "at run time, or set it explicitly."
126
+ )
127
+ grid_size(self.input_shape, self.widths) # type: ignore[arg-type] # validate divisibility EARLY
128
+ self._model = nnx.data(
129
+ _Fcos(
130
+ num_classes=self.num_classes,
131
+ in_channels=int(self.input_shape[-1]),
132
+ widths=self.widths,
133
+ head_width=self.head_width,
134
+ seed=self.seed,
135
+ )
136
+ )
137
+ logger.info(f"Built the shared FCOS spec in flax.nnx ({self.num_classes} classes, widths={self.widths}).")
138
+ return self._model
139
+
140
+ @property
141
+ def model(self) -> Any:
142
+ """The live network, built on first access."""
143
+ return self.solidify()
144
+
145
+ @property
146
+ def spec_stride(self) -> int:
147
+ """The raw-to-distance scale the loss/decode need — derived from the configured widths."""
148
+ return stride(self.widths)
149
+
150
+ def __call__(self, x: Any, training: bool = False) -> Any:
151
+ """The three raw head maps from an ``[N, H, W, C]`` batch — channels LAST."""
152
+ return self.model(x, training=training)
153
+
154
+ @property
155
+ def parameter_count(self) -> int:
156
+ """Trainable parameters — the number :mod:`raidar.fcos.spec` predicts.
157
+
158
+ BatchNorm's running statistics are ``nnx.BatchStat`` — a different variable TYPE in the
159
+ same state tree — so counting ``nnx.Param`` only excludes them, the same exclusion the
160
+ spec makes.
161
+ """
162
+ import jax
163
+
164
+ params = nnx.state(self.model, nnx.Param)
165
+ return int(sum(leaf.size for leaf in jax.tree.leaves(params)))