deltaid 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.
- deltaid/__init__.py +60 -0
- deltaid/_keras.py +16 -0
- deltaid/_tensorflow.py +37 -0
- deltaid/cli.py +92 -0
- deltaid/fastai_segmenter.py +229 -0
- deltaid/huggingface_model.py +135 -0
- deltaid/huggingface_segmenter.py +313 -0
- deltaid/jax_segmenter.py +349 -0
- deltaid/keras_segmentation.py +102 -0
- deltaid/keras_segmenter.py +141 -0
- deltaid/lightning_segmenter.py +152 -0
- deltaid/mlx_segmenter.py +312 -0
- deltaid/py.typed +0 -0
- deltaid/segmentation_base.py +106 -0
- deltaid/segmentation_keras.py +120 -0
- deltaid/segmentation_torch.py +88 -0
- deltaid/smp_model.py +256 -0
- deltaid/tensorflow_segmenter.py +149 -0
- deltaid/torch_segmentation.py +126 -0
- deltaid/torch_segmenter.py +148 -0
- deltaid/unet/__init__.py +10 -0
- deltaid/unet/flax_unet.py +223 -0
- deltaid/unet/keras_unet.py +162 -0
- deltaid/unet/mlx_unet.py +263 -0
- deltaid/unet/spec.py +135 -0
- deltaid/unet/tensorflow_unet.py +253 -0
- deltaid/unet/torch_unet.py +219 -0
- deltaid-0.1.0a1.dist-info/METADATA +645 -0
- deltaid-0.1.0a1.dist-info/RECORD +33 -0
- deltaid-0.1.0a1.dist-info/WHEEL +5 -0
- deltaid-0.1.0a1.dist-info/entry_points.txt +24 -0
- deltaid-0.1.0a1.dist-info/licenses/LICENSE +21 -0
- deltaid-0.1.0a1.dist-info/top_level.txt +1 -0
deltaid/__init__.py
ADDED
|
@@ -0,0 +1,60 @@
|
|
|
1
|
+
"""Deltaid: semantic segmentation across training backends, driven by one config.
|
|
2
|
+
|
|
3
|
+
**The core is backend-free.** ``pip install deltaid`` gives you the CLI and the config surface;
|
|
4
|
+
a training framework arrives with the backend you select::
|
|
5
|
+
|
|
6
|
+
pip install 'deltaid[lightning]' # PyTorch Lightning — the reference backend
|
|
7
|
+
|
|
8
|
+
Which is why every backend name below resolves LAZILY (PEP 562): importing ``deltaid`` must not
|
|
9
|
+
require a framework the operator did not choose. Touching a name whose backend is missing raises
|
|
10
|
+
an :class:`ImportError` naming the exact extra, instead of a traceback from three libraries down.
|
|
11
|
+
"""
|
|
12
|
+
|
|
13
|
+
from importlib.metadata import PackageNotFoundError, version
|
|
14
|
+
|
|
15
|
+
from matrainer._exports import lazy_exports
|
|
16
|
+
|
|
17
|
+
try:
|
|
18
|
+
# Single source of truth: the installed distribution's metadata, i.e. pyproject.toml's
|
|
19
|
+
# `version` (the distribution is `deltaid`). Never type the number in here as well.
|
|
20
|
+
__version__ = version("deltaid")
|
|
21
|
+
except PackageNotFoundError: # pragma: no cover - uninstalled source checkout
|
|
22
|
+
__version__ = "0.0.0.dev0"
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
#: Backend-owned name -> (defining module, the extra that installs it). Resolved on first attribute
|
|
26
|
+
#: access. Keep in step with the extras in ``pyproject.toml``: a name here whose extra does not
|
|
27
|
+
#: exist would advertise an install command that fails.
|
|
28
|
+
#
|
|
29
|
+
# The two kinds of model wrap different things, and only the second is the cross-framework
|
|
30
|
+
# comparison — so they live apart. A ZOO WRAPPER (`SegmentationModelPytorch`, reaching somebody
|
|
31
|
+
# else's weights) stays at the TOP LEVEL, one `<backend>_model.py` each; every implementation of
|
|
32
|
+
# the shared architecture spec lives in the `deltaid.unet` package (which imports nothing itself,
|
|
33
|
+
# so these stay lazy).
|
|
34
|
+
_BACKEND_NAMES = {
|
|
35
|
+
"LightningSegmenter": ("deltaid.lightning_segmenter", "lightning"),
|
|
36
|
+
"TorchSegmenter": ("deltaid.torch_segmenter", "torch"),
|
|
37
|
+
"FastaiSegmenter": ("deltaid.fastai_segmenter", "fastai"),
|
|
38
|
+
"KerasSegmenter": ("deltaid.keras_segmenter", "keras"),
|
|
39
|
+
"TensorFlowSegmenter": ("deltaid.tensorflow_segmenter", "tensorflow"),
|
|
40
|
+
"HuggingFaceSegmenter": ("deltaid.huggingface_segmenter", "huggingface"),
|
|
41
|
+
"JaxSegmenter": ("deltaid.jax_segmenter", "jax"),
|
|
42
|
+
"MlxSegmenter": ("deltaid.mlx_segmenter", "mlx"),
|
|
43
|
+
"SegmentationModelPytorch": ("deltaid.smp_model", "torch"),
|
|
44
|
+
"HuggingFaceSegmentationModel": ("deltaid.huggingface_model", "huggingface"),
|
|
45
|
+
# The shared spec's implementations. `TorchUNet` serves EVERY torch backend (lightning, torch,
|
|
46
|
+
# fastai — they differ in the loop, not in what a model is), which is why there is no separate
|
|
47
|
+
# name per backend. Its extra is the SMALLEST one that supplies what it needs — plain `torch`,
|
|
48
|
+
# not `lightning`, so the ImportError advises the smaller install.
|
|
49
|
+
"TorchUNet": ("deltaid.unet.torch_unet", "torch"),
|
|
50
|
+
"KerasUNet": ("deltaid.unet.keras_unet", "keras"),
|
|
51
|
+
"TensorFlowUNet": ("deltaid.unet.tensorflow_unet", "tensorflow"),
|
|
52
|
+
"FlaxUNet": ("deltaid.unet.flax_unet", "jax"),
|
|
53
|
+
"MlxUNet": ("deltaid.unet.mlx_unet", "mlx"),
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
__all__ = [*_BACKEND_NAMES]
|
|
57
|
+
|
|
58
|
+
# The resolver is matrainer's `lazy_exports` (the machinery was identical in every training
|
|
59
|
+
# project's root); the `_BACKEND_NAMES` table above is the project DATA it runs on.
|
|
60
|
+
__getattr__, __dir__ = lazy_exports(__name__, _BACKEND_NAMES)
|
deltaid/_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 deltaid module writes
|
|
11
|
+
``from deltaid._keras import keras`` and never ``import keras`` directly.
|
|
12
|
+
"""
|
|
13
|
+
|
|
14
|
+
from recordstream.keras import keras, keras_backend
|
|
15
|
+
|
|
16
|
+
__all__ = ["keras", "keras_backend"]
|
deltaid/_tensorflow.py
ADDED
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
"""The ONE place deltaid imports TensorFlow — and the ``KERAS_BACKEND`` ordering that must precede it.
|
|
2
|
+
|
|
3
|
+
The twin of :mod:`deltaid._keras`, and it exists 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``. That is the right answer for a Keras run — Keras
|
|
6
|
+
3 is an API and any engine underneath will do — but it is the WRONG one here: on a machine
|
|
7
|
+
carrying both ``deltaid[lightning]`` and ``deltaid[tensorflow]`` (the workspace's own setup),
|
|
8
|
+
torch wins, and :class:`~deltaid.tensorflow_segmenter.TensorFlowSegmenter` would then drive a
|
|
9
|
+
torch-backed ``keras.Model`` with ``tf.GradientTape``, which cannot work.
|
|
10
|
+
|
|
11
|
+
Keras reads the variable ONCE, at import time, so the default has to be in place before ANY
|
|
12
|
+
module imports keras. Which is why this module hands over the ``keras`` handle **as well as**
|
|
13
|
+
``tf``: a consumer importing both from their "natural" homes would write
|
|
14
|
+
``from deltaid._keras import keras`` beside ``from deltaid._tensorflow import tf``, and isort
|
|
15
|
+
sorts ``_keras`` ahead of ``_tensorflow`` — importing keras one line before the default that was
|
|
16
|
+
supposed to steer it. Re-exporting here removes the ordering hazard instead of documenting it.
|
|
17
|
+
|
|
18
|
+
``setdefault``, not an assignment: an explicit ``KERAS_BACKEND=jax`` still wins, and
|
|
19
|
+
``TensorFlowSegmenter.initialize()`` then fails with a message naming the mismatch instead of
|
|
20
|
+
running on an engine its training loop cannot drive.
|
|
21
|
+
|
|
22
|
+
:class:`~recordstream.keras.RecordSequence` is re-exported for the SAME reason as ``keras``, and
|
|
23
|
+
it is not decoration: the default above lives in ``recordstream.keras``, so importing the batching
|
|
24
|
+
adapter from its own module is what pins the variable — and isort sorts a ``recordstream`` line
|
|
25
|
+
into the third-party group, ABOVE every ``deltaid`` line.
|
|
26
|
+
"""
|
|
27
|
+
|
|
28
|
+
import os
|
|
29
|
+
|
|
30
|
+
# BEFORE the imports below, and before anything else imports keras — see the module docstring
|
|
31
|
+
# for why this cannot live at the bottom of an import block.
|
|
32
|
+
os.environ.setdefault("KERAS_BACKEND", "tensorflow")
|
|
33
|
+
|
|
34
|
+
import tensorflow as tf # noqa: E402 - deliberately after the environment default above
|
|
35
|
+
from recordstream.keras import RecordSequence, keras, keras_backend # noqa: E402
|
|
36
|
+
|
|
37
|
+
__all__ = ["RecordSequence", "keras", "keras_backend", "tf"]
|
deltaid/cli.py
ADDED
|
@@ -0,0 +1,92 @@
|
|
|
1
|
+
"""Deltaid CLI — semantic segmentation across training backends.
|
|
2
|
+
|
|
3
|
+
Three verbs, and the training backend is a *config* dimension the CLI passes through::
|
|
4
|
+
|
|
5
|
+
deltaid train cfg.yaml # the config's default backend
|
|
6
|
+
deltaid train cfg.yaml --framework lightning # a `!scope:framework=lightning` block
|
|
7
|
+
deltaid evaluate cfg.yaml
|
|
8
|
+
deltaid predict cfg.yaml
|
|
9
|
+
deltaid 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. What
|
|
19
|
+
this module owns is deltaid's DATA: the FRAMEWORKS table and the verb help texts.
|
|
20
|
+
|
|
21
|
+
Adding a backend: write ``deltaid/<name>_segmenter.py``, then add a row to ``FRAMEWORKS`` below.
|
|
22
|
+
"""
|
|
23
|
+
|
|
24
|
+
from typing import Dict
|
|
25
|
+
|
|
26
|
+
from matrainer.cli import Framework, make_trainer_app, trainer_main
|
|
27
|
+
|
|
28
|
+
FRAMEWORKS: Dict[str, Framework] = {
|
|
29
|
+
"lightning": Framework(
|
|
30
|
+
"PyTorch Lightning — the reference backend (smp models, per-split torchmetrics).",
|
|
31
|
+
"deltaid.torch_segmentation",
|
|
32
|
+
),
|
|
33
|
+
# Shares `lightning`'s loss/metric set, and that is the point rather than an economy: a
|
|
34
|
+
# `torch.nn` loss does not care whether a Trainer or a hand-written loop calls it, so the two
|
|
35
|
+
# backends differ ONLY in the loop.
|
|
36
|
+
"torch": Framework(
|
|
37
|
+
"PyTorch — a hand-written loop, no training framework at all (the control experiment).",
|
|
38
|
+
"deltaid.torch_segmentation",
|
|
39
|
+
),
|
|
40
|
+
"fastai": Framework(
|
|
41
|
+
"fastai — a Learner with one-cycle scheduling, over the same torch stack.",
|
|
42
|
+
# The same torch losses reach it (a `BaseLoss` is a callable over torch tensors), and its
|
|
43
|
+
# METRICS are names in `fastai.metrics` rather than registered classes — so there is
|
|
44
|
+
# nothing extra to import for it.
|
|
45
|
+
"deltaid.torch_segmentation",
|
|
46
|
+
),
|
|
47
|
+
"keras": Framework(
|
|
48
|
+
"Keras 3 — one API over PyTorch / TensorFlow / JAX (set KERAS_BACKEND to pick).",
|
|
49
|
+
"deltaid.keras_segmentation",
|
|
50
|
+
),
|
|
51
|
+
# Shares the Keras loss/metric set on purpose: in TF >= 2.16 `tf.keras` IS Keras 3, so a
|
|
52
|
+
# separate `tensorflow_segmentation.py` would register the same classes under a second tag
|
|
53
|
+
# and make every bare `!class:SparseCategoricalCrossentropy` ambiguous for no gain.
|
|
54
|
+
"tensorflow": Framework(
|
|
55
|
+
"TensorFlow — a native tf.data + tf.GradientTape loop, with SavedModel export.",
|
|
56
|
+
"deltaid.keras_segmentation",
|
|
57
|
+
),
|
|
58
|
+
"huggingface": Framework(
|
|
59
|
+
"Transformers `Trainer` + Accelerate — fine-tuning a Hub checkpoint (SegFormer).",
|
|
60
|
+
# No registrations: an `AutoModelForSemanticSegmentation` computes its own loss from
|
|
61
|
+
# `labels=`, so there is nothing a config could wire.
|
|
62
|
+
),
|
|
63
|
+
"jax": Framework(
|
|
64
|
+
"JAX — a jitted optax loop over a Flax model, the loop written out in full.",
|
|
65
|
+
# No registrations either, for a DIFFERENT reason than huggingface's: optax ships plain
|
|
66
|
+
# FUNCTIONS, so a loss is resolved by NAME and there is no class for the registry to tag.
|
|
67
|
+
),
|
|
68
|
+
"mlx": Framework(
|
|
69
|
+
"MLX — Apple silicon, unified memory, lazy arrays (`mlx.nn` losses by NAME).",
|
|
70
|
+
# `mlx.nn.losses` are functions like optax's; `mlx.optimizers` ships classes, but a
|
|
71
|
+
# config names those too. Nothing to register.
|
|
72
|
+
),
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
app = make_trainer_app(
|
|
76
|
+
name="deltaid",
|
|
77
|
+
description="Semantic segmentation across training backends",
|
|
78
|
+
frameworks=FRAMEWORKS,
|
|
79
|
+
verb_docs={
|
|
80
|
+
"train": "Train a semantic-segmentation model",
|
|
81
|
+
"evaluate": "Evaluate a trained segmenter over the test set",
|
|
82
|
+
"predict": "Stream segmentation predictions from a trained segmenter to its sink",
|
|
83
|
+
},
|
|
84
|
+
)
|
|
85
|
+
|
|
86
|
+
|
|
87
|
+
def main() -> None:
|
|
88
|
+
trainer_main(app, FRAMEWORKS)
|
|
89
|
+
|
|
90
|
+
|
|
91
|
+
if __name__ == "__main__":
|
|
92
|
+
main()
|
|
@@ -0,0 +1,229 @@
|
|
|
1
|
+
"""``FastaiSegmenter`` — the same segmentation run with a fastai ``Learner``.
|
|
2
|
+
|
|
3
|
+
The fastai member of the segmentation fleet, assembled from the workspace trainer bases
|
|
4
|
+
(2026-08-07): the Learner machinery — the ``DataLoaders``/``Learner`` assembly, the positional
|
|
5
|
+
``_to_tuple`` collate (built on the task's own int64-mask ``_targets`` hook), the Recorder
|
|
6
|
+
read-back into canonical names, the plain-function tracking hookup — is
|
|
7
|
+
``matrainer.fastai.FastaiRunnable``, and the segmentation task — ``num_classes`` resolution,
|
|
8
|
+
the ``ignore_index`` semantics — is the SAME :mod:`deltaid.segmentation_base` +
|
|
9
|
+
:mod:`deltaid.segmentation_torch` pair every torch-family backend runs on. What remains HERE is
|
|
10
|
+
the config surface (the full flat constructor — the confluid introspection reads THIS
|
|
11
|
+
signature) and the task's fastai VOCABULARY, which carries the two measured fastai facts:
|
|
12
|
+
|
|
13
|
+
1. **The loss needs ``axis=1``, and fastai's default is WRONG for segmentation.**
|
|
14
|
+
``CrossEntropyLossFlat`` defaults to ``axis=-1``, which flattens the CHANNEL dimension into
|
|
15
|
+
the batch and dies with *"Expected input batch_size (48) to match target batch_size (128)"*
|
|
16
|
+
(measured). With ``axis=1`` it agrees with ``torch.nn.CrossEntropyLoss`` to seven decimals.
|
|
17
|
+
The DEFAULT states it because nothing else in a config hints at it.
|
|
18
|
+
2. **The metrics need no such fix** — ``DiceMulti`` and ``JaccardCoeffMulti`` already default
|
|
19
|
+
to ``axis=1`` because they exist FOR segmentation; only the loss, shared with
|
|
20
|
+
classification, carries the wrong default.
|
|
21
|
+
|
|
22
|
+
**One name is CONFIGURED rather than resolved — ``pixel_accuracy``** (:class:`PixelAccuracy`):
|
|
23
|
+
fastai's ``accuracy`` argmaxes over ``axis=-1`` (the WIDTH of an ``[N, C, H, W]`` prediction)
|
|
24
|
+
and ``foreground_acc`` scores one class, so the quantity every other engine reports was
|
|
25
|
+
unreachable by name. It wraps nothing — it is the ACCUMULATOR fastai does not ship.
|
|
26
|
+
|
|
27
|
+
Run it with ``deltaid train cfg.yaml --framework fastai``.
|
|
28
|
+
"""
|
|
29
|
+
|
|
30
|
+
from typing import Any, Callable, Dict, Iterable, List, Optional, Union
|
|
31
|
+
|
|
32
|
+
import torch
|
|
33
|
+
from confluid import Mandatory, Partial, configurable
|
|
34
|
+
from fastai.callback.core import Callback as FastaiCallback
|
|
35
|
+
from fastai.losses import CrossEntropyLossFlat
|
|
36
|
+
from fastai.metrics import Metric
|
|
37
|
+
from fastai.torch_core import flatten_check
|
|
38
|
+
from loggair import get_logger
|
|
39
|
+
from matrainer.fastai import FastaiLoss, FastaiMetric, FastaiOptimizer, FastaiRunnable
|
|
40
|
+
from matrainer.metric_names import MetricNames
|
|
41
|
+
from matrainer.tracking.base import Tracker
|
|
42
|
+
from recordstream import RecordSource
|
|
43
|
+
from recordstream.runnable import RunnableTask
|
|
44
|
+
|
|
45
|
+
from deltaid.segmentation_torch import SegmentationTorchHooks
|
|
46
|
+
|
|
47
|
+
logger = get_logger(__name__)
|
|
48
|
+
|
|
49
|
+
#: Which entry point :meth:`FastaiSegmenter.run` dispatches to (the standard four).
|
|
50
|
+
SegmenterTask = RunnableTask
|
|
51
|
+
|
|
52
|
+
#: The per-pixel default set — both already default to ``axis=1``, unlike the loss.
|
|
53
|
+
DEFAULT_METRICS = ("DiceMulti", "JaccardCoeffMulti")
|
|
54
|
+
|
|
55
|
+
__all__ = ["DEFAULT_METRICS", "FastaiMetric", "FastaiOptimizer", "FastaiSegmenter", "PixelAccuracy", "SegmenterTask"]
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
@configurable(task="segmentation", role="trainer", framework="torch")
|
|
59
|
+
class FastaiSegmenter(SegmentationTorchHooks, FastaiRunnable):
|
|
60
|
+
"""Train, evaluate or predict a semantic segmenter with a fastai ``Learner``.
|
|
61
|
+
|
|
62
|
+
Args:
|
|
63
|
+
model: Segmentation model emitting ``[N, num_classes, H, W]`` logits — wire ``!lazy:``
|
|
64
|
+
so :meth:`initialize` can inject the resolved ``num_classes`` at run time.
|
|
65
|
+
train_set: Training source (``task="fit"``).
|
|
66
|
+
test_set: Held-out source (``task="test"`` / ``"predict"``).
|
|
67
|
+
num_classes: Class count, background included. Omitted, it is derived from the model or
|
|
68
|
+
the mask column.
|
|
69
|
+
ignore_index: Pixel value skipped by the default loss (and the ``pixel_accuracy``
|
|
70
|
+
alias).
|
|
71
|
+
task: Which entry point ``run()`` dispatches to.
|
|
72
|
+
max_epochs: Training epochs.
|
|
73
|
+
batch_size: Rows per batch.
|
|
74
|
+
num_workers: DataLoader worker processes.
|
|
75
|
+
persistent_workers: Override the pairing derived from ``num_workers`` (``None`` derives
|
|
76
|
+
``num_workers != 0``). An explicit value is for a HOST fact no derivation can see —
|
|
77
|
+
macOS terminates persistent workers slowly, so a config there sets ``false`` while
|
|
78
|
+
keeping its workers. ``True`` with ``num_workers=0`` is refused.
|
|
79
|
+
learning_rate: Peak LR — ``lr_max`` for one-cycle, ``lr`` otherwise.
|
|
80
|
+
weight_decay: fastai's ``wd``. ``None`` is fastai's own default.
|
|
81
|
+
one_cycle: Use ``fit_one_cycle`` (fastai's headline scheduler) instead of plain ``fit``.
|
|
82
|
+
opt_func: A ``fastai.optimizer`` function or its name (``"Adam"``, ``"SGD"``, …).
|
|
83
|
+
loss: The loss. ``None`` picks ``CrossEntropyLossFlat(axis=1)`` — see the module
|
|
84
|
+
docstring for why the axis is not fastai's default.
|
|
85
|
+
metrics: fastai metrics (callables or names), computed on both passes of a fit.
|
|
86
|
+
train_metrics / val_metrics / test_metrics: That split's OWN metrics. ``test_metrics``
|
|
87
|
+
merges over ``metrics`` and NARROWS; ``train_metrics`` and ``val_metrics`` are
|
|
88
|
+
UNIONED, because a fitting ``Learner`` holds ONE list and reports it on both passes.
|
|
89
|
+
metric_names: How recorded metrics are named — see
|
|
90
|
+
:class:`~matrainer.metric_names.MetricNames`. The ``Recorder``'s columns are
|
|
91
|
+
``train_loss`` / ``valid_loss`` / the metrics; the default translates them to the
|
|
92
|
+
canonical ``train/loss`` / ``val/loss`` / ``val/<metric>``, an unprefixed column
|
|
93
|
+
landing under ``val`` because that is the split a ``Learner`` measures.
|
|
94
|
+
callbacks: fastai callbacks.
|
|
95
|
+
trackers: matrainer trackers — one or a list.
|
|
96
|
+
experiment_name: Run identity, recorded in artifacts and tracking.
|
|
97
|
+
run_name: Run identity; a random ``adjective_noun`` when omitted.
|
|
98
|
+
input_key: Record key holding the image.
|
|
99
|
+
target_key: Record key holding the per-pixel mask.
|
|
100
|
+
|
|
101
|
+
Optional OVERRIDE slots — every one is already constructed with a sensible default in
|
|
102
|
+
``__init__``, so nothing here NEEDS wiring; a same-named top-level YAML key replaces one
|
|
103
|
+
via broadcasting when you want to: ``val_set``, ``train/val/test_loader``, ``dataloaders``,
|
|
104
|
+
``learner``, ``predictions_sink``, ``metrics_sidecar_path``.
|
|
105
|
+
"""
|
|
106
|
+
|
|
107
|
+
def __init__(
|
|
108
|
+
self,
|
|
109
|
+
model: Mandatory[Partial[torch.nn.Module]],
|
|
110
|
+
train_set: Optional[Partial[RecordSource]] = None,
|
|
111
|
+
test_set: Optional[Partial[RecordSource]] = None,
|
|
112
|
+
num_classes: Optional[int] = None,
|
|
113
|
+
ignore_index: int = -100,
|
|
114
|
+
task: SegmenterTask = "fit",
|
|
115
|
+
max_epochs: int = 10,
|
|
116
|
+
batch_size: int = 8,
|
|
117
|
+
num_workers: int = 0,
|
|
118
|
+
persistent_workers: Optional[bool] = None,
|
|
119
|
+
learning_rate: float = 1e-3,
|
|
120
|
+
weight_decay: Optional[float] = None,
|
|
121
|
+
one_cycle: bool = True,
|
|
122
|
+
opt_func: FastaiOptimizer = "Adam",
|
|
123
|
+
loss: Optional[Partial[FastaiLoss]] = None,
|
|
124
|
+
metrics: Optional[List[FastaiMetric]] = None,
|
|
125
|
+
train_metrics: Optional[List[FastaiMetric]] = None,
|
|
126
|
+
val_metrics: Optional[List[FastaiMetric]] = None,
|
|
127
|
+
test_metrics: Optional[List[FastaiMetric]] = None,
|
|
128
|
+
metric_names: Optional[Partial[MetricNames]] = None,
|
|
129
|
+
callbacks: Optional[List[Partial[FastaiCallback]]] = None,
|
|
130
|
+
trackers: Optional[Union[Partial[Tracker], Iterable[Partial[Tracker]]]] = None,
|
|
131
|
+
experiment_name: str = "deltaid_segmentation",
|
|
132
|
+
run_name: Optional[str] = None,
|
|
133
|
+
input_key: str = "image",
|
|
134
|
+
target_key: str = "mask",
|
|
135
|
+
) -> None:
|
|
136
|
+
super().__init__(
|
|
137
|
+
model=model,
|
|
138
|
+
train_set=train_set,
|
|
139
|
+
test_set=test_set,
|
|
140
|
+
task=task,
|
|
141
|
+
max_epochs=max_epochs,
|
|
142
|
+
batch_size=batch_size,
|
|
143
|
+
num_workers=num_workers,
|
|
144
|
+
persistent_workers=persistent_workers,
|
|
145
|
+
trackers=trackers,
|
|
146
|
+
experiment_name=experiment_name,
|
|
147
|
+
run_name=run_name,
|
|
148
|
+
input_key=input_key,
|
|
149
|
+
target_key=target_key,
|
|
150
|
+
metrics=metrics,
|
|
151
|
+
train_metrics=train_metrics,
|
|
152
|
+
val_metrics=val_metrics,
|
|
153
|
+
test_metrics=test_metrics,
|
|
154
|
+
metric_names=metric_names,
|
|
155
|
+
learning_rate=learning_rate,
|
|
156
|
+
weight_decay=weight_decay,
|
|
157
|
+
one_cycle=one_cycle,
|
|
158
|
+
opt_func=opt_func,
|
|
159
|
+
loss=loss,
|
|
160
|
+
callbacks=callbacks,
|
|
161
|
+
)
|
|
162
|
+
self.num_classes = int(num_classes) if num_classes is not None else None
|
|
163
|
+
self.ignore_index = int(ignore_index)
|
|
164
|
+
self.class_names: Optional[List[str]] = None
|
|
165
|
+
self.plot_metrics = False
|
|
166
|
+
|
|
167
|
+
# ---- the task's fastai vocabulary ------------------------------------------------------- #
|
|
168
|
+
def _default_fastai_loss(self) -> Any:
|
|
169
|
+
"""``CrossEntropyLossFlat(axis=1)`` — fastai's loss with the axis segmentation needs.
|
|
170
|
+
|
|
171
|
+
The wrapper's own default (``axis=-1``) flattens the CHANNEL dimension of an
|
|
172
|
+
``[N, C, H, W]`` prediction into the batch (measured; the module docstring records the
|
|
173
|
+
failure); with ``axis=1`` it agrees with ``torch.nn.CrossEntropyLoss`` to seven
|
|
174
|
+
decimals. Stated in the DEFAULT because nothing in a config hints at it.
|
|
175
|
+
"""
|
|
176
|
+
return CrossEntropyLossFlat(axis=1, ignore_index=self.ignore_index)
|
|
177
|
+
|
|
178
|
+
def _default_fastai_metrics(self) -> List[FastaiMetric]:
|
|
179
|
+
# Both already default to `axis=1` — they exist for segmentation, so only the loss
|
|
180
|
+
# (shared with classification) carries the wrong default.
|
|
181
|
+
return list(DEFAULT_METRICS)
|
|
182
|
+
|
|
183
|
+
def _metric_aliases(self) -> Dict[str, Callable[[], Any]]:
|
|
184
|
+
return {"pixel_accuracy": lambda: PixelAccuracy(ignore_index=self.ignore_index)}
|
|
185
|
+
|
|
186
|
+
def _metric_vocabulary_hint(self) -> str:
|
|
187
|
+
return "For segmentation: DiceMulti, JaccardCoeffMulti, foreground_acc, Dice, JaccardCoeff."
|
|
188
|
+
|
|
189
|
+
|
|
190
|
+
class PixelAccuracy(Metric):
|
|
191
|
+
"""Per-pixel accuracy over the NON-IGNORED pixels — the one metric fastai has no name for.
|
|
192
|
+
|
|
193
|
+
``fastai.metrics.accuracy`` argmaxes over ``axis=-1``, which on an ``[N, C, H, W]`` prediction
|
|
194
|
+
is the WIDTH, and ``foreground_acc`` scores one class rather than all pixels. So the quantity
|
|
195
|
+
every other engine here reports as ``pixel_accuracy`` was simply unreachable by NAME — the one
|
|
196
|
+
blank column in the backend sweep's table.
|
|
197
|
+
|
|
198
|
+
**Why a CLASS when the module docstring says metrics are names.** That rule is about not
|
|
199
|
+
wrapping an upstream metric to make it registrable, and this wraps nothing: it is the
|
|
200
|
+
ACCUMULATOR fastai does not ship for this quantity. `AvgMetric(partial(accuracy, axis=1))`
|
|
201
|
+
would have been one line and averages per batch WEIGHTED BY BATCH SIZE, which is the right
|
|
202
|
+
answer only while every image contributes the same number of counted pixels — untrue the
|
|
203
|
+
moment ``ignore_index`` drops a varying number of them. Accumulating counts and dividing once
|
|
204
|
+
is exact, and it is precisely the shape fastai's own ``DiceMulti`` uses for the same reason.
|
|
205
|
+
|
|
206
|
+
The name is ``pixel_accuracy`` because that is what the other seven engines call it; a metric
|
|
207
|
+
reported under its own class name would open a column no other row fills.
|
|
208
|
+
"""
|
|
209
|
+
|
|
210
|
+
def __init__(self, axis: int = 1, ignore_index: int = -100) -> None:
|
|
211
|
+
self.axis = axis
|
|
212
|
+
self.ignore_index = ignore_index
|
|
213
|
+
|
|
214
|
+
def reset(self) -> None:
|
|
215
|
+
self.correct, self.total = 0, 0
|
|
216
|
+
|
|
217
|
+
def accumulate(self, learn: Any) -> None:
|
|
218
|
+
predicted, targets = flatten_check(learn.pred.argmax(dim=self.axis), learn.y)
|
|
219
|
+
valid = targets != self.ignore_index
|
|
220
|
+
self.correct += int(((predicted == targets) & valid).sum().item())
|
|
221
|
+
self.total += int(valid.sum().item())
|
|
222
|
+
|
|
223
|
+
@property
|
|
224
|
+
def value(self) -> float:
|
|
225
|
+
return self.correct / self.total if self.total else 0.0
|
|
226
|
+
|
|
227
|
+
@property
|
|
228
|
+
def name(self) -> str:
|
|
229
|
+
return "pixel_accuracy"
|
|
@@ -0,0 +1,135 @@
|
|
|
1
|
+
"""``HuggingFaceSegmentationModel`` — an ``AutoModelForSemanticSegmentation`` behind the model contract.
|
|
2
|
+
|
|
3
|
+
The Hub is the zoo here, so this is the same shape as :class:`deltaid.smp_model.SegmentationModelPytorch`
|
|
4
|
+
with a different builder underneath: ``__init__`` stores only, the network is built on first use by
|
|
5
|
+
:meth:`solidify` (confluid's ``flow()``-time hook), and required configuration is validated at
|
|
6
|
+
build time so zero-arg construction keeps working.
|
|
7
|
+
|
|
8
|
+
Three things are specific to the Hub and are why this class exists rather than a config wiring
|
|
9
|
+
``transformers`` directly:
|
|
10
|
+
|
|
11
|
+
* **``num_classes`` arrives at run time.** A pretrained checkpoint carries its own head — 150
|
|
12
|
+
ADE20K classes for the default SegFormer — so pointing it at a 3-class dataset is a shape
|
|
13
|
+
mismatch. The build passes ``num_labels`` plus ``ignore_mismatched_sizes=True``, which tells
|
|
14
|
+
transformers to DISCARD the pretrained head and start a fresh one at the requested width.
|
|
15
|
+
Without it the load raises; with it, fine-tuning works the way the Hub intends (measured: the
|
|
16
|
+
load report shows ``decode_head.classifier`` reinitialised 150 -> 3).
|
|
17
|
+
* **The model computes its own loss**, from ``labels=``, using ``config.semantic_loss_ignore_index``
|
|
18
|
+
— which defaults to **255**, NOT torch's ``-100``. So the segmenter writes its own
|
|
19
|
+
``ignore_index`` onto the config; see :mod:`deltaid.huggingface_segmenter`.
|
|
20
|
+
* **The logits come back at a REDUCED resolution.** SegFormer emits ``[N, C, H/4, W/4]``
|
|
21
|
+
(measured: a 224x224 input gives 56x56), and it upsamples internally only for its own loss.
|
|
22
|
+
Anything else that compares logits to the mask — a metric, a predictions sink — has to
|
|
23
|
+
upsample first, which the segmenter does.
|
|
24
|
+
|
|
25
|
+
``model_name`` is a Hub id (``"nvidia/segformer-b0-finetuned-ade-512-512"``), the same string you
|
|
26
|
+
would pass to ``from_pretrained``.
|
|
27
|
+
"""
|
|
28
|
+
|
|
29
|
+
from typing import Any, List, Optional
|
|
30
|
+
|
|
31
|
+
from confluid import configurable
|
|
32
|
+
from loggair import get_logger
|
|
33
|
+
from matrainer.uri import ModelRef, hf_model_ref
|
|
34
|
+
|
|
35
|
+
logger = get_logger(__name__)
|
|
36
|
+
|
|
37
|
+
__all__ = ["HuggingFaceSegmentationModel"]
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
@configurable(task="segmentation", role="model", lazy=True, framework="huggingface")
|
|
41
|
+
class HuggingFaceSegmentationModel:
|
|
42
|
+
"""A Hub semantic-segmentation checkpoint with a head sized to your dataset.
|
|
43
|
+
|
|
44
|
+
Args:
|
|
45
|
+
model_name: A Hub model id, e.g. ``"nvidia/segformer-b0-finetuned-ade-512-512"`` or
|
|
46
|
+
``"nvidia/mit-b0"``. Sentinel ``""`` is invalid but permitted so the class is
|
|
47
|
+
zero-arg constructible; it is rejected at build time with a clear error.
|
|
48
|
+
num_classes: Width of the per-pixel head. Sentinel ``0`` likewise — a segmenter injects
|
|
49
|
+
the resolved count via ``flow(model, num_classes=N)`` at run time, so it is not
|
|
50
|
+
written in YAML.
|
|
51
|
+
pretrained: Load the checkpoint's weights. ``False`` builds the same architecture from
|
|
52
|
+
its config with fresh weights, which keeps a first run offline and reproducible.
|
|
53
|
+
trust_remote_code: Allow a Hub repo to execute its own modelling code. Off by default
|
|
54
|
+
because it runs code from the internet; turn it on only for a repo you trust.
|
|
55
|
+
seed: Seed for torch's global RNG, set when the model is BUILT — a pretrained load
|
|
56
|
+
still randomly reinitializes the ``num_labels`` head, and ``TrainingArguments.seed``
|
|
57
|
+
applies only when training starts, too late to cover it. Applied WITHOUT restoring
|
|
58
|
+
the RNG state (the workspace wrapper-seeding idiom).
|
|
59
|
+
"""
|
|
60
|
+
|
|
61
|
+
def __init__(
|
|
62
|
+
self,
|
|
63
|
+
model_name: str = "",
|
|
64
|
+
num_classes: int = 0,
|
|
65
|
+
pretrained: bool = True,
|
|
66
|
+
trust_remote_code: bool = False,
|
|
67
|
+
seed: int = 0,
|
|
68
|
+
) -> None:
|
|
69
|
+
# Partial: store only. No Hub call, no download — the workspace zero-arg mandate.
|
|
70
|
+
self.model_name = model_name
|
|
71
|
+
self.num_classes = int(num_classes)
|
|
72
|
+
self.pretrained = pretrained
|
|
73
|
+
self.trust_remote_code = trust_remote_code
|
|
74
|
+
self.seed = int(seed)
|
|
75
|
+
self._model: Optional[Any] = None
|
|
76
|
+
|
|
77
|
+
def solidify(self) -> Any:
|
|
78
|
+
"""Build (once) and return the live ``transformers`` model."""
|
|
79
|
+
if self._model is not None:
|
|
80
|
+
return self._model
|
|
81
|
+
if not self.model_name:
|
|
82
|
+
raise ValueError("HuggingFaceSegmentationModel.model_name is required (got empty).")
|
|
83
|
+
if self.num_classes < 1:
|
|
84
|
+
raise ValueError(
|
|
85
|
+
f"HuggingFaceSegmentationModel.num_classes must be >= 1 to build (got {self.num_classes}) — "
|
|
86
|
+
"set it explicitly, or let the segmenter derive it."
|
|
87
|
+
)
|
|
88
|
+
import torch
|
|
89
|
+
from transformers import AutoConfig, AutoModelForSemanticSegmentation
|
|
90
|
+
|
|
91
|
+
# Seeded BEFORE the build (the restoration project's 2026-08-06 idiom): a pretrained
|
|
92
|
+
# load still randomly reinitializes the `num_labels` head (`ignore_mismatched_sizes`),
|
|
93
|
+
# and `TrainingArguments.seed` applies only when TRAINING starts — too late to cover
|
|
94
|
+
# it (the detection project measured a 3.4x metric spread from exactly this ordering).
|
|
95
|
+
torch.manual_seed(self.seed)
|
|
96
|
+
|
|
97
|
+
if self.pretrained:
|
|
98
|
+
# `ignore_mismatched_sizes` is what makes fine-tuning possible at all: the checkpoint's
|
|
99
|
+
# head is sized for ITS dataset, and without this the load raises on the mismatch
|
|
100
|
+
# instead of reinitialising the head.
|
|
101
|
+
self._model = AutoModelForSemanticSegmentation.from_pretrained(
|
|
102
|
+
self.model_name,
|
|
103
|
+
num_labels=self.num_classes,
|
|
104
|
+
ignore_mismatched_sizes=True,
|
|
105
|
+
trust_remote_code=self.trust_remote_code,
|
|
106
|
+
)
|
|
107
|
+
else:
|
|
108
|
+
config = AutoConfig.from_pretrained(
|
|
109
|
+
self.model_name, num_labels=self.num_classes, trust_remote_code=self.trust_remote_code
|
|
110
|
+
)
|
|
111
|
+
self._model = AutoModelForSemanticSegmentation.from_config(config)
|
|
112
|
+
logger.info(f"Built {self.model_name} with a {self.num_classes}-class head (pretrained={self.pretrained}).")
|
|
113
|
+
return self._model
|
|
114
|
+
|
|
115
|
+
@property
|
|
116
|
+
def model(self) -> Any:
|
|
117
|
+
"""The live ``transformers`` model, built on first access."""
|
|
118
|
+
return self.solidify()
|
|
119
|
+
|
|
120
|
+
def __call__(self, *args: Any, **kwargs: Any) -> Any:
|
|
121
|
+
"""Delegate to the live model, so the wrapper is callable wherever the model is."""
|
|
122
|
+
return self.model(*args, **kwargs)
|
|
123
|
+
|
|
124
|
+
@property
|
|
125
|
+
def model_refs(self) -> List[ModelRef]:
|
|
126
|
+
"""The weights this wrapper loads, for the run manifest's ``models`` section.
|
|
127
|
+
|
|
128
|
+
Reads STORED CONFIG ONLY — never builds, downloads or opens anything, because the
|
|
129
|
+
property is asked of a wrapper that may never run. An EMPTY list when
|
|
130
|
+
``pretrained=False``: random weights referenced no artifact, and the architecture is
|
|
131
|
+
already recorded in the run's params, so naming one would name something nobody loaded.
|
|
132
|
+
"""
|
|
133
|
+
if not self.model_name or not self.pretrained:
|
|
134
|
+
return []
|
|
135
|
+
return [hf_model_ref(self.model_name, role="pretrained")]
|