Coverage for src/bioimageio/spec/model/v0_5.py: 73%
1844 statements
« prev ^ index » next coverage.py v7.17.3, created at 2026-11-17 16:20 +0000
« prev ^ index » next coverage.py v7.17.3, created at 2026-11-17 16:20 +0000
1from __future__ import annotations
3import collections.abc
4import re
5import string
6import warnings
7from abc import ABC
8from collections.abc import Callable, Mapping, Sequence
9from copy import deepcopy
10from fractions import Fraction
11from functools import partial
12from itertools import chain
13from math import ceil
14from pathlib import Path, PurePosixPath
15from tempfile import mkdtemp
16from textwrap import dedent
17from typing import (
18 TYPE_CHECKING,
19 Annotated,
20 Any,
21 ClassVar,
22 Generic,
23 Literal,
24 NamedTuple,
25 TypeAlias,
26 TypeVar,
27 cast,
28 get_args,
29 overload,
30)
32import numpy as np
33from annotated_types import Ge, Gt, Interval, MaxLen, MinLen, Predicate
34from imageio.v3 import imread, imwrite # pyright: ignore[reportUnknownVariableType]
35from loguru import logger
36from numpy.typing import NDArray
37from pydantic import (
38 AfterValidator,
39 Discriminator,
40 Field,
41 RootModel,
42 SerializationInfo,
43 SerializerFunctionWrapHandler,
44 StrictInt,
45 Tag,
46 ValidationInfo,
47 WrapSerializer,
48 field_validator,
49 model_serializer,
50 model_validator,
51)
52from typing_extensions import Self, assert_never
54from .._internal.common_nodes import (
55 InvalidDescr,
56 KwargsNode,
57 NodeWithExplicitlySetFields,
58)
59from .._internal.constants import DTYPE_LIMITS
60from .._internal.field_warning import issue_warning, warn
61from .._internal.io import BioimageioYamlContent as BioimageioYamlContent
62from .._internal.io import FileDescr as FileDescr
63from .._internal.io import (
64 FileSource,
65 WithSuffix,
66 YamlValue,
67 extract_file_name,
68 get_reader,
69 wo_special_file_name,
70)
71from .._internal.io_basics import Sha256 as Sha256
72from .._internal.io_packaging import (
73 FileDescr_package,
74 package_file_descr_serializer,
75)
76from .._internal.io_utils import load_array, open_bioimageio_yaml
77from .._internal.node import Node
78from .._internal.node_converter import Converter
79from .._internal.type_guards import is_dict, is_sequence
80from .._internal.types import (
81 FAIR,
82 LowerCaseIdentifier,
83 LowerCaseIdentifierAnno,
84 validate_identifier,
85 validate_is_not_keyword,
86)
87from .._internal.types import (
88 AbsoluteTolerance as AbsoluteTolerance,
89)
90from .._internal.types import Datetime as Datetime
91from .._internal.types import Identifier as Identifier
92from .._internal.types import (
93 MismatchedElementsPerMillion as MismatchedElementsPerMillion,
94)
95from .._internal.types import NotEmpty as NotEmpty
96from .._internal.types import (
97 RelativeTolerance as RelativeTolerance,
98)
99from .._internal.types import SiUnit as SiUnit
100from .._internal.url import HttpUrl as HttpUrl
101from .._internal.utils import try_all_raise_last
102from .._internal.validation_context import get_validation_context
103from .._internal.validator_annotations import RestrictCharacters
104from .._internal.version_type import Version as Version
105from .._internal.warning_levels import INFO
106from ..dataset.v0_2 import DatasetDescr as DatasetDescr02
107from ..dataset.v0_2 import LinkedDataset as LinkedDataset02
108from ..dataset.v0_3 import DatasetDescr as DatasetDescr
109from ..dataset.v0_3 import DatasetId as DatasetId
110from ..dataset.v0_3 import LinkedDataset as LinkedDataset
111from ..dataset.v0_3 import Uploader as Uploader
112from ..generic._v0_3_converter import convert_plain_covers_and_docs_and_icon
113from ..generic.v0_3 import (
114 VALID_COVER_IMAGE_EXTENSIONS as VALID_COVER_IMAGE_EXTENSIONS,
115)
116from ..generic.v0_3 import Author as Author
117from ..generic.v0_3 import BadgeDescr as BadgeDescr
118from ..generic.v0_3 import CiteEntry as CiteEntry
119from ..generic.v0_3 import DeprecatedLicenseId as DeprecatedLicenseId
120from ..generic.v0_3 import Doi as Doi
121from ..generic.v0_3 import (
122 FileDescr_documentation,
123 GenericModelDescrBase,
124 LinkedResourceBase,
125 _author_conv, # pyright: ignore[reportPrivateUsage]
126 _maintainer_conv, # pyright: ignore[reportPrivateUsage]
127)
128from ..generic.v0_3 import LicenseId as LicenseId
129from ..generic.v0_3 import LinkedResource as LinkedResource
130from ..generic.v0_3 import Maintainer as Maintainer
131from ..generic.v0_3 import OrcidId as OrcidId
132from ..generic.v0_3 import RelativeFilePath as RelativeFilePath
133from ..generic.v0_3 import ResourceId as ResourceId
134from .v0_4 import Author as _Author_v0_4
135from .v0_4 import BinarizeDescr as _BinarizeDescr_v0_4
136from .v0_4 import CallableFromDepencency as CallableFromDepencency
137from .v0_4 import CallableFromDepencency as _CallableFromDepencency_v0_4
138from .v0_4 import CallableFromFile as _CallableFromFile_v0_4
139from .v0_4 import ClipDescr as _ClipDescr_v0_4
140from .v0_4 import ImplicitOutputShape as _ImplicitOutputShape_v0_4
141from .v0_4 import InputTensorDescr as _InputTensorDescr_v0_4
142from .v0_4 import KnownRunMode as KnownRunMode
143from .v0_4 import ModelDescr as _ModelDescr04
144from .v0_4 import ModelDescr as _ModelDescr_v0_4
145from .v0_4 import OutputTensorDescr as _OutputTensorDescr_v0_4
146from .v0_4 import ParameterizedInputShape as _ParameterizedInputShape_v0_4
147from .v0_4 import PostprocessingDescr as _PostprocessingDescr_v0_4
148from .v0_4 import PreprocessingDescr as _PreprocessingDescr_v0_4
149from .v0_4 import RunMode as RunMode
150from .v0_4 import ScaleLinearDescr as _ScaleLinearDescr_v0_4
151from .v0_4 import ScaleMeanVarianceDescr as _ScaleMeanVarianceDescr_v0_4
152from .v0_4 import ScaleRangeDescr as _ScaleRangeDescr_v0_4
153from .v0_4 import SigmoidDescr as _SigmoidDescr_v0_4
154from .v0_4 import TensorName as _TensorName_v0_4
155from .v0_4 import ZeroMeanUnitVarianceDescr as _ZeroMeanUnitVarianceDescr_v0_4
156from .v0_4 import package_weights
158SpaceUnit = Literal[
159 "attometer",
160 "angstrom",
161 "centimeter",
162 "decimeter",
163 "exameter",
164 "femtometer",
165 "foot",
166 "gigameter",
167 "hectometer",
168 "inch",
169 "kilometer",
170 "megameter",
171 "meter",
172 "micrometer",
173 "mile",
174 "millimeter",
175 "nanometer",
176 "parsec",
177 "petameter",
178 "picometer",
179 "terameter",
180 "yard",
181 "yoctometer",
182 "yottameter",
183 "zeptometer",
184 "zettameter",
185]
186"""Space unit compatible to the [OME-Zarr axes specification 0.5](https://ngff.openmicroscopy.org/0.5/#axes-md)"""
188TimeUnit = Literal[
189 "attosecond",
190 "centisecond",
191 "day",
192 "decisecond",
193 "exasecond",
194 "femtosecond",
195 "gigasecond",
196 "hectosecond",
197 "hour",
198 "kilosecond",
199 "megasecond",
200 "microsecond",
201 "millisecond",
202 "minute",
203 "nanosecond",
204 "petasecond",
205 "picosecond",
206 "second",
207 "terasecond",
208 "yoctosecond",
209 "yottasecond",
210 "zeptosecond",
211 "zettasecond",
212]
213"""Time unit compatible to the [OME-Zarr axes specification 0.5](https://ngff.openmicroscopy.org/0.5/#axes-md)"""
215AxisType = Literal["batch", "channel", "index", "time", "space"]
217_AXIS_TYPE_MAP: Mapping[str, AxisType] = {
218 "b": "batch",
219 "t": "time",
220 "i": "index",
221 "c": "channel",
222 "x": "space",
223 "y": "space",
224 "z": "space",
225}
227_AXIS_ID_MAP = {
228 "b": "batch",
229 "t": "time",
230 "i": "index",
231 "c": "channel",
232 "s": "channel",
233}
235WeightsFormat = Literal[
236 "keras_hdf5",
237 "keras_v3",
238 "onnx",
239 "pytorch_state_dict",
240 "tensorflow_js",
241 "tensorflow_saved_model_bundle",
242 "torchscript",
243]
246class TensorId(LowerCaseIdentifier):
247 root_model: ClassVar[type[RootModel[Any]]] = RootModel[
248 Annotated[LowerCaseIdentifierAnno, MaxLen(32)]
249 ]
252def _normalize_axis_id(a: str):
253 b = str(a).lower()
254 normalized = _AXIS_ID_MAP.get(b, b)
255 if a != normalized:
256 logger.opt(depth=3).debug(
257 "Normalized axis id from '{}' to '{}'.", a, normalized
258 )
259 return normalized
262class AxisId(LowerCaseIdentifier):
263 root_model: ClassVar[type[RootModel[Any]]] = RootModel[
264 Annotated[
265 NotEmpty[str],
266 AfterValidator(_normalize_axis_id),
267 MaxLen(16),
268 AfterValidator(validate_identifier),
269 AfterValidator(validate_is_not_keyword),
270 ]
271 ]
274def _is_batch(a: str) -> bool:
275 return str(a) == "batch"
278def _is_not_batch(a: str) -> bool:
279 return not _is_batch(a)
282NonBatchAxisId = Annotated[AxisId, Predicate(_is_not_batch)]
284PreprocessingId = Literal[
285 "binarize",
286 "clip",
287 "ensure_dtype",
288 "fixed_zero_mean_unit_variance",
289 "scale_linear",
290 "scale_range",
291 "sigmoid",
292 "softmax",
293]
294PostprocessingId = Literal[
295 "binarize",
296 "clip",
297 "custom",
298 "ensure_dtype",
299 "fixed_zero_mean_unit_variance",
300 "scale_linear",
301 "scale_mean_variance",
302 "scale_range",
303 "sigmoid",
304 "softmax",
305 "zero_mean_unit_variance",
306]
309SAME_AS_TYPE = "<same as type>"
312ParameterizedSize_N: TypeAlias = int
313"""
314Annotates an integer to calculate a concrete axis size from a `ParameterizedSize`.
315"""
318class ParameterizedSize(Node):
319 """Describes a range of valid tensor axis sizes as `size = min + n*step`.
321 - **min** and **step** are given by the model description.
322 - All blocksize paramters n = 0,1,2,... yield a valid `size`.
323 - A greater blocksize paramter n = 0,1,2,... results in a greater **size**.
324 This allows to adjust the axis size more generically.
325 """
327 N: ClassVar[type[int]] = ParameterizedSize_N
328 """Positive integer to parameterize this axis"""
330 min: Annotated[int, Gt(0)]
331 step: Annotated[int, Gt(0)]
333 def validate_size(self, size: int, msg_prefix: str = "") -> int:
334 if size < self.min:
335 raise ValueError(
336 f"{msg_prefix}size {size} < {self.min} (minimum axis size)"
337 )
338 if (size - self.min) % self.step != 0:
339 raise ValueError(
340 f"{msg_prefix}size {size} is not parameterized by `min + n*step` ="
341 + f" `{self.min} + n*{self.step}`"
342 )
344 return size
346 def get_size(self, n: ParameterizedSize_N) -> int:
347 return self.min + self.step * n
349 def get_n(self, s: int) -> ParameterizedSize_N:
350 """return smallest n parameterizing a size greater or equal than `s`"""
351 return ceil((s - self.min) / self.step)
354class DataDependentSize(Node):
355 min: Annotated[int, Gt(0)] = 1
356 max: Annotated[int | None, Gt(1)] = None
358 @model_validator(mode="after")
359 def _validate_max_gt_min(self):
360 if self.max is not None and self.min >= self.max:
361 raise ValueError(f"expected `min` < `max`, but got {self.min}, {self.max}")
363 return self
365 def validate_size(self, size: int, msg_prefix: str = "") -> int:
366 if size < self.min:
367 raise ValueError(f"{msg_prefix}size {size} < {self.min}")
369 if self.max is not None and size > self.max:
370 raise ValueError(f"{msg_prefix}size {size} > {self.max}")
372 return size
375class SizeReference(Node):
376 """A tensor axis size (extent in pixels/frames) defined in relation to a reference axis.
378 `axis.size = reference.size * reference.scale / axis.scale + offset`
380 Note:
381 1. The axis and the referenced axis need to have the same unit (or no unit).
382 2. Batch axes may not be referenced.
383 3. Fractions are rounded down.
384 4. If the reference axis is `concatenable` the referencing axis is assumed to be
385 `concatenable` as well with the same block order.
387 Example:
388 An unisotropic input image of w*h=100*49 pixels depicts a phsical space of 200*196mm².
389 Let's assume that we want to express the image height h in relation to its width w
390 instead of only accepting input images of exactly 100*49 pixels
391 (for example to express a range of valid image shapes by parametrizing w, see `ParameterizedSize`).
393 >>> w = SpaceInputAxis(id=AxisId("w"), size=100, unit="millimeter", scale=2)
394 >>> h = SpaceInputAxis(
395 ... id=AxisId("h"),
396 ... size=SizeReference(tensor_id=TensorId("input"), axis_id=AxisId("w"), offset=-1),
397 ... unit="millimeter",
398 ... scale=4,
399 ... )
400 >>> print(h.size.get_size(h, w))
401 49
403 ⇒ h = w * w.scale / h.scale + offset = 100 * 2mm / 4mm - 1 = 49
404 """
406 tensor_id: TensorId
407 """tensor id of the reference axis"""
409 axis_id: AxisId
410 """axis id of the reference axis"""
412 offset: StrictInt = 0
414 def get_size(
415 self,
416 axis: ChannelAxis
417 | IndexInputAxis
418 | IndexOutputAxis
419 | TimeInputAxis
420 | SpaceInputAxis
421 | TimeOutputAxis
422 | TimeOutputAxisWithHalo
423 | SpaceOutputAxis
424 | SpaceOutputAxisWithHalo,
425 ref_axis: ChannelAxis
426 | IndexInputAxis
427 | IndexOutputAxis
428 | TimeInputAxis
429 | SpaceInputAxis
430 | TimeOutputAxis
431 | TimeOutputAxisWithHalo
432 | SpaceOutputAxis
433 | SpaceOutputAxisWithHalo,
434 n: ParameterizedSize_N = 0,
435 ref_size: int | None = None,
436 ):
437 """Compute the concrete size for a given axis and its reference axis.
439 Args:
440 axis: The axis this [SizeReference][] is the size of.
441 ref_axis: The reference axis to compute the size from.
442 n: If the **ref_axis** is parameterized (of type `ParameterizedSize`)
443 and no fixed **ref_size** is given,
444 **n** is used to compute the size of the parameterized **ref_axis**.
445 ref_size: Overwrite the reference size instead of deriving it from
446 **ref_axis**
447 (**ref_axis.scale** is still used; any given **n** is ignored).
448 """
449 assert axis.size == self, (
450 "Given `axis.size` is not defined by this `SizeReference`"
451 )
453 assert ref_axis.id == self.axis_id, (
454 f"Expected `ref_axis.id` to be {self.axis_id}, but got {ref_axis.id}."
455 )
457 assert axis.unit == ref_axis.unit, (
458 "`SizeReference` requires `axis` and `ref_axis` to have the same `unit`,"
459 f" but {axis.unit}!={ref_axis.unit}"
460 )
461 if ref_size is None:
462 if isinstance(ref_axis.size, (int, float)):
463 ref_size = ref_axis.size
464 elif isinstance(ref_axis.size, ParameterizedSize):
465 ref_size = ref_axis.size.get_size(n)
466 elif isinstance(ref_axis.size, DataDependentSize):
467 raise ValueError(
468 "Reference axis referenced in `SizeReference` may not be a `DataDependentSize`."
469 )
470 elif isinstance(ref_axis.size, SizeReference):
471 raise ValueError(
472 "Reference axis referenced in `SizeReference` may not be sized by a"
473 + " `SizeReference` itself."
474 )
475 else:
476 assert_never(ref_axis.size)
478 ratio = Fraction(ref_axis.scale) / Fraction(axis.scale)
479 return int(Fraction(ref_size) * ratio + self.offset)
481 @staticmethod
482 def _get_unit(
483 axis: ChannelAxis
484 | IndexInputAxis
485 | IndexOutputAxis
486 | TimeInputAxis
487 | SpaceInputAxis
488 | TimeOutputAxis
489 | TimeOutputAxisWithHalo
490 | SpaceOutputAxis
491 | SpaceOutputAxisWithHalo,
492 ):
493 return axis.unit
496class AxisBase(NodeWithExplicitlySetFields):
497 id: AxisId
498 """An axis id unique across all axes of one tensor."""
500 description: Annotated[str, MaxLen(128)] = ""
501 """A short description of this axis beyond its type and id."""
504class WithHalo(Node):
505 halo: Annotated[int, Ge(1)]
506 """The halo should be cropped from the output tensor to avoid boundary effects.
507 It is to be cropped from both sides, i.e. `size_after_crop = size - 2 * halo`.
508 To document a halo that is already cropped by the model use `size.offset` instead."""
510 size: Annotated[
511 SizeReference,
512 Field(examples=[{"tensor_id": "t", "axis_id": "a", "offset": 5}]),
513 ]
514 """reference to another axis with an optional offset (see [SizeReference][])"""
517BATCH_AXIS_ID = AxisId("batch")
518CHANNEL_AXIS_ID = AxisId("channel")
519DEFAULT_SPACE_AXIS_ID = AxisId("x")
520DEFAULT_INDEX_AXIS_ID = AxisId("index")
521DEFAULT_TIME_AXIS_ID = AxisId("time")
524class BatchAxis(AxisBase):
525 """A concatenable batch axis shared implicitly by input and output tensors."""
527 implemented_type: ClassVar[Literal["batch"]] = "batch"
528 if TYPE_CHECKING:
529 type: Literal["batch"] = "batch"
530 else:
531 type: Literal["batch"]
533 id: Annotated[AxisId, Predicate(_is_batch)] = BATCH_AXIS_ID
534 size: Literal[1] | None = None
535 """The batch size may be fixed to 1,
536 otherwise (the default) it may be chosen arbitrarily depending on available memory"""
538 @property
539 def scale(self):
540 return 1.0
542 @property
543 def concatenable(self):
544 return "reproducible"
546 @property
547 def unit(self):
548 return None
551class ChannelAxis(AxisBase):
552 implemented_type: ClassVar[Literal["channel"]] = "channel"
553 if TYPE_CHECKING:
554 type: Literal["channel"] = "channel"
555 else:
556 type: Literal["channel"]
558 id: NonBatchAxisId = CHANNEL_AXIS_ID
560 channel_names: NotEmpty[list[str]]
561 """Name/label for each channel. The number of channels is given by `len(channel_names)`."""
563 @property
564 def size(self) -> int:
565 return len(self.channel_names)
567 @property
568 def concatenable(self):
569 return False
571 @property
572 def scale(self) -> float:
573 return 1.0
575 @property
576 def unit(self):
577 return None
580class _WithInputAxisSize(Node):
581 size: Annotated[
582 Annotated[int, Gt(0)] | ParameterizedSize | SizeReference,
583 Field(
584 examples=[
585 10,
586 ParameterizedSize(min=32, step=16).model_dump(mode="json"),
587 {"tensor_id": "t", "axis_id": "a", "offset": 5},
588 ]
589 ),
590 ]
591 """The size/length of this axis can be specified as
592 - fixed integer
593 - parameterized series of valid sizes ([ParameterizedSize][])
594 - reference to another axis with an optional offset ([SizeReference][])
595 """
598class IndexAxisBase(AxisBase):
599 implemented_type: ClassVar[Literal["index"]] = "index"
600 if TYPE_CHECKING:
601 type: Literal["index"] = "index"
602 else:
603 type: Literal["index"]
605 id: NonBatchAxisId = DEFAULT_INDEX_AXIS_ID
607 @property
608 def scale(self) -> float:
609 return 1.0
611 @property
612 def unit(self):
613 return None
616class IndexInputAxis(IndexAxisBase, _WithInputAxisSize):
617 concatenable: bool | Literal["applicable", "reproducible"] = "reproducible"
618 """If a model has a `concatenable` input axis, it can be processed blockwise,
619 splitting a longer sample axis into blocks matching its input tensor description.
621 Output axes are concatenable if they have a [SizeReference][] to a concatenable
622 input axis. Each concatenable input axis must be referenced by an output axis.
624 Set `concatenable` to `applicable` if the model can be meaningfully applied blockwise,
625 but its outputs may change beyond the specified numerical tolerance for reproducibility,
626 for example due to the use of instance norm within the model.
627 `True` is an alias for `applicable` and is provided for backwards compatibility.
628 """
631class IndexOutputAxis(IndexAxisBase):
632 size: Annotated[
633 Annotated[int, Gt(0)] | SizeReference | DataDependentSize,
634 Field(examples=[10, {"tensor_id": "t", "axis_id": "a", "offset": 5}]),
635 ]
636 """The size/length of this axis can be specified as
637 - fixed integer
638 - reference to another axis with an optional offset ([SizeReference][])
639 - data dependent size using [DataDependentSize][] (size is only known after model inference)
640 """
643class TimeAxisBase(AxisBase):
644 implemented_type: ClassVar[Literal["time"]] = "time"
645 if TYPE_CHECKING:
646 type: Literal["time"] = "time"
647 else:
648 type: Literal["time"]
650 id: NonBatchAxisId = DEFAULT_TIME_AXIS_ID
651 unit: TimeUnit | None = None
652 scale: Annotated[float, Gt(0)] = 1.0
655class TimeInputAxis(TimeAxisBase, _WithInputAxisSize):
656 concatenable: bool | Literal["applicable", "reproducible"] = "reproducible"
657 """If a model has a `concatenable` input axis, it can be processed blockwise,
658 splitting a longer sample axis into blocks matching its input tensor description.
660 Output axes are concatenable if they have a [SizeReference][] to a concatenable
661 input axis. Each concatenable input axis must be referenced by an output axis.
663 Set `concatenable` to `applicable` if the model can be meaningfully applied blockwise,
664 but its outputs may change beyond the specified numerical tolerance for reproducibility,
665 for example due to the use of instance norm within the model.
666 `True` is an alias for `applicable` and is provided for backwards compatibility.
667 """
670class SpaceAxisBase(AxisBase):
671 implemented_type: ClassVar[Literal["space"]] = "space"
672 if TYPE_CHECKING:
673 type: Literal["space"] = "space"
674 else:
675 type: Literal["space"]
677 id: Annotated[NonBatchAxisId, Field(examples=["x", "y", "z"])] = (
678 DEFAULT_SPACE_AXIS_ID
679 )
680 unit: SpaceUnit | None = None
681 scale: Annotated[float, Gt(0)] = 1.0
684class SpaceInputAxis(SpaceAxisBase, _WithInputAxisSize):
685 concatenable: bool | Literal["applicable", "reproducible"] = "reproducible"
686 """If a model has a `concatenable` input axis, it can be processed blockwise,
687 splitting a longer sample axis into blocks matching its input tensor description.
689 Output axes are concatenable if they have a [SizeReference][] to a concatenable
690 input axis. Each concatenable input axis must be referenced by an output axis.
692 Set `concatenable` to `applicable` if the model can be meaningfully applied blockwise,
693 but its outputs may change beyond the specified numerical tolerance for reproducibility,
694 for example due to the use of instance norm within the model.
695 `True` is an alias for `applicable` and is provided for backwards compatibility.
696 """
699INPUT_AXIS_TYPES = (
700 BatchAxis,
701 ChannelAxis,
702 IndexInputAxis,
703 TimeInputAxis,
704 SpaceInputAxis,
705)
706"""intended for isinstance comparisons in py<3.10"""
708_InputAxisUnion = (
709 BatchAxis | ChannelAxis | IndexInputAxis | TimeInputAxis | SpaceInputAxis
710)
711InputAxis = Annotated[_InputAxisUnion, Discriminator("type")]
714class _WithOutputAxisSize(Node):
715 size: Annotated[
716 Annotated[int, Gt(0)] | SizeReference,
717 Field(examples=[10, {"tensor_id": "t", "axis_id": "a", "offset": 5}]),
718 ]
719 """The size/length of this axis can be specified as
720 - fixed integer
721 - reference to another axis with an optional offset (see [SizeReference][])
722 """
725class TimeOutputAxis(TimeAxisBase, _WithOutputAxisSize):
726 pass
729class TimeOutputAxisWithHalo(TimeAxisBase, WithHalo):
730 pass
733def _get_halo_axis_discriminator_value(v: Any) -> Literal["with_halo", "wo_halo"]:
734 if isinstance(v, dict):
735 return "with_halo" if "halo" in v else "wo_halo"
736 else:
737 return "with_halo" if hasattr(v, "halo") else "wo_halo"
740_TimeOutputAxisUnion = Annotated[
741 Annotated[TimeOutputAxis, Tag("wo_halo")]
742 | Annotated[TimeOutputAxisWithHalo, Tag("with_halo")],
743 Discriminator(_get_halo_axis_discriminator_value),
744]
747class SpaceOutputAxis(SpaceAxisBase, _WithOutputAxisSize):
748 pass
751class SpaceOutputAxisWithHalo(SpaceAxisBase, WithHalo):
752 pass
755_SpaceOutputAxisUnion = Annotated[
756 Annotated[SpaceOutputAxis, Tag("wo_halo")]
757 | Annotated[SpaceOutputAxisWithHalo, Tag("with_halo")],
758 Discriminator(_get_halo_axis_discriminator_value),
759]
762_OutputAxisUnion = (
763 BatchAxis
764 | ChannelAxis
765 | IndexOutputAxis
766 | _TimeOutputAxisUnion
767 | _SpaceOutputAxisUnion
768)
769OutputAxis = Annotated[_OutputAxisUnion, Discriminator("type")]
771OUTPUT_AXIS_TYPES = (
772 BatchAxis,
773 ChannelAxis,
774 IndexOutputAxis,
775 TimeOutputAxis,
776 TimeOutputAxisWithHalo,
777 SpaceOutputAxis,
778 SpaceOutputAxisWithHalo,
779)
780"""intended for isinstance comparisons in py<3.10"""
783AnyAxis = InputAxis | OutputAxis
785ANY_AXIS_TYPES = INPUT_AXIS_TYPES + OUTPUT_AXIS_TYPES
786"""intended for isinstance comparisons in py<3.10"""
788TVs = (
789 NotEmpty[list[int]]
790 | NotEmpty[list[float]]
791 | NotEmpty[list[bool]]
792 | NotEmpty[list[str]]
793)
796NominalOrOrdinalDType = Literal[
797 "float32",
798 "float64",
799 "uint8",
800 "int8",
801 "uint16",
802 "int16",
803 "uint32",
804 "int32",
805 "uint64",
806 "int64",
807 "bool",
808]
811class NominalOrOrdinalDataDescr(Node):
812 values: TVs
813 """A fixed set of nominal or an ascending sequence of ordinal values.
814 In this case `data.type` is required to be an unsigend integer type, e.g. 'uint8'.
815 String `values` are interpreted as labels for tensor values 0, ..., N.
816 Note: as YAML 1.2 does not natively support a "set" datatype,
817 nominal values should be given as a sequence (aka list/array) as well.
818 """
820 type: Annotated[
821 NominalOrOrdinalDType,
822 Field(
823 examples=[
824 "float32",
825 "uint8",
826 "uint16",
827 "int64",
828 "bool",
829 ],
830 ),
831 ] = "uint8"
833 @model_validator(mode="after")
834 def _validate_values_match_type(
835 self,
836 ) -> Self:
837 incompatible: list[Any] = []
838 for v in self.values:
839 if self.type == "bool":
840 if not isinstance(v, bool):
841 incompatible.append(v)
842 elif self.type in DTYPE_LIMITS:
843 if (
844 isinstance(v, (int, float))
845 and (
846 v < DTYPE_LIMITS[self.type].min
847 or v > DTYPE_LIMITS[self.type].max
848 )
849 or (isinstance(v, str) and "uint" not in self.type)
850 or (isinstance(v, float) and "int" in self.type)
851 ):
852 incompatible.append(v)
853 else:
854 incompatible.append(v)
856 if len(incompatible) == 5:
857 incompatible.append("...")
858 break
860 if incompatible:
861 raise ValueError(
862 f"data type '{self.type}' incompatible with values {incompatible}"
863 )
865 return self
867 unit: Literal["arbitrary unit"] | SiUnit | None = None
869 @property
870 def range(self):
871 if isinstance(self.values[0], str):
872 return 0, len(self.values) - 1
873 else:
874 return min(self.values), max(self.values)
877IntervalOrRatioDType = Literal[
878 "float32",
879 "float64",
880 "uint8",
881 "int8",
882 "uint16",
883 "int16",
884 "uint32",
885 "int32",
886 "uint64",
887 "int64",
888]
891class IntervalOrRatioDataDescr(Node):
892 type: Annotated[ # TODO: rename to dtype
893 IntervalOrRatioDType,
894 Field(
895 examples=["float32", "float64", "uint8", "uint16"],
896 ),
897 ] = "float32"
898 range: tuple[float | None, float | None] = (
899 None,
900 None,
901 )
902 """Tuple `(minimum, maximum)` specifying the allowed range of the data in this tensor.
903 `None` corresponds to min/max of what can be expressed by **type**."""
904 unit: Literal["arbitrary unit"] | SiUnit = "arbitrary unit"
905 scale: float = 1.0
906 """Scale for data on an interval (or ratio) scale."""
907 offset: float | None = None
908 """Offset for data on a ratio scale."""
910 @model_validator(mode="before")
911 def _replace_inf(cls, data: Any):
912 if is_dict(data) and "range" in data and is_sequence(data["range"]):
913 forbidden = (
914 "inf",
915 "-inf",
916 ".inf",
917 "-.inf",
918 float("inf"),
919 float("-inf"),
920 )
921 if any(v in forbidden for v in data["range"]):
922 issue_warning("replaced 'inf' value", value=data["range"])
924 data["range"] = tuple(
925 (None if v in forbidden else v) for v in data["range"]
926 )
928 return data
931TensorDataDescr = NominalOrOrdinalDataDescr | IntervalOrRatioDataDescr
934class BinarizeKwargs(KwargsNode):
935 """key word arguments for [BinarizeDescr][]"""
937 threshold: float
938 """The fixed threshold"""
941class BinarizeAlongAxisKwargs(KwargsNode):
942 """key word arguments for [BinarizeDescr][]"""
944 threshold: NotEmpty[list[float]]
945 """The fixed threshold values along `axis`"""
947 axis: Annotated[NonBatchAxisId, Field(examples=["channel"])]
948 """The `threshold` axis"""
951class BinarizeDescr(NodeWithExplicitlySetFields):
952 """Binarize the tensor with a fixed threshold.
954 Values above [BinarizeKwargs.threshold][]/[BinarizeAlongAxisKwargs.threshold][]
955 will be set to one, values below the threshold to zero.
957 Examples:
958 - in YAML
959 ```yaml
960 postprocessing:
961 - id: binarize
962 kwargs:
963 axis: 'channel'
964 threshold: [0.25, 0.5, 0.75]
965 ```
966 - in Python:
968 >>> postprocessing = [BinarizeDescr(
969 ... kwargs=BinarizeAlongAxisKwargs(
970 ... axis=AxisId('channel'),
971 ... threshold=[0.25, 0.5, 0.75],
972 ... )
973 ... )]
974 """
976 implemented_id: ClassVar[Literal["binarize"]] = "binarize"
977 if TYPE_CHECKING:
978 id: Literal["binarize"] = "binarize"
979 else:
980 id: Literal["binarize"]
981 kwargs: BinarizeKwargs | BinarizeAlongAxisKwargs
984class ClipKwargs(KwargsNode):
985 """key word arguments for [ClipDescr][]"""
987 min: float | None = None
988 """Minimum value for clipping.
990 Exclusive with [min_percentile][]
991 """
992 min_percentile: Annotated[float, Interval(ge=0, lt=100)] | None = None
993 """Minimum percentile for clipping.
995 Exclusive with [min][].
997 In range [0, 100).
998 """
1000 max: float | None = None
1001 """Maximum value for clipping.
1003 Exclusive with `max_percentile`.
1004 """
1005 max_percentile: Annotated[float, Interval(gt=1, le=100)] | None = None
1006 """Maximum percentile for clipping.
1008 Exclusive with `max`.
1010 In range (1, 100].
1011 """
1013 axes: Annotated[Sequence[AxisId] | None, Field(examples=[("batch", "x", "y")])] = (
1014 None
1015 )
1016 """The subset of axes to determine percentiles jointly,
1018 i.e. axes to reduce to compute min/max from `min_percentile`/`max_percentile`.
1019 For example to clip 'batch', 'x' and 'y' jointly in a tensor ('batch', 'channel', 'y', 'x')
1020 resulting in a tensor of equal shape with clipped values per channel, specify `axes=('batch', 'x', 'y')`.
1021 To clip samples independently, leave out the 'batch' axis.
1023 Only valid if `min_percentile` and/or `max_percentile` are set.
1025 Default: Compute percentiles over all axes jointly."""
1027 @model_validator(mode="after")
1028 def _validate(self) -> Self:
1029 if (self.min is not None) and (self.min_percentile is not None):
1030 raise ValueError(
1031 "Only one of `min` and `min_percentile` may be set, not both."
1032 )
1033 if (self.max is not None) and (self.max_percentile is not None):
1034 raise ValueError(
1035 "Only one of `max` and `max_percentile` may be set, not both."
1036 )
1037 if (
1038 self.min is None
1039 and self.min_percentile is None
1040 and self.max is None
1041 and self.max_percentile is None
1042 ):
1043 raise ValueError(
1044 "At least one of `min`, `min_percentile`, `max`, or `max_percentile` must be set."
1045 )
1047 if (
1048 self.axes is not None
1049 and self.min_percentile is None
1050 and self.max_percentile is None
1051 ):
1052 raise ValueError(
1053 "If `axes` is set, at least one of `min_percentile` or `max_percentile` must be set."
1054 )
1056 return self
1059class ClipDescr(NodeWithExplicitlySetFields):
1060 """Set tensor values below min to min and above max to max.
1062 See `ScaleRangeDescr` for examples.
1063 """
1065 implemented_id: ClassVar[Literal["clip"]] = "clip"
1066 if TYPE_CHECKING:
1067 id: Literal["clip"] = "clip"
1068 else:
1069 id: Literal["clip"]
1071 kwargs: ClipKwargs
1074class EnsureDtypeKwargs(KwargsNode):
1075 """key word arguments for [EnsureDtypeDescr][]"""
1077 dtype: Literal[
1078 "float32",
1079 "float64",
1080 "uint8",
1081 "int8",
1082 "uint16",
1083 "int16",
1084 "uint32",
1085 "int32",
1086 "uint64",
1087 "int64",
1088 "bool",
1089 ]
1092class EnsureDtypeDescr(NodeWithExplicitlySetFields):
1093 """Cast the tensor data type to `EnsureDtypeKwargs.dtype` (if not matching).
1095 This can for example be used to ensure the inner neural network model gets a
1096 different input tensor data type than the fully described bioimage.io model does.
1098 Examples:
1099 The described bioimage.io model (incl. preprocessing) accepts any
1100 float32-compatible tensor, normalizes it with percentiles and clipping and then
1101 casts it to uint8, which is what the neural network in this example expects.
1102 - in YAML
1103 ```yaml
1104 inputs:
1105 - data:
1106 type: float32 # described bioimage.io model is compatible with any float32 input tensor
1107 preprocessing:
1108 - id: scale_range
1109 kwargs:
1110 axes: ['y', 'x']
1111 max_percentile: 99.8
1112 min_percentile: 5.0
1113 - id: clip
1114 kwargs:
1115 min: 0.0
1116 max: 1.0
1117 - id: ensure_dtype # the neural network of the model requires uint8
1118 kwargs:
1119 dtype: uint8
1120 ```
1121 - in Python:
1122 >>> preprocessing = [
1123 ... ScaleRangeDescr(
1124 ... kwargs=ScaleRangeKwargs(
1125 ... axes= (AxisId('y'), AxisId('x')),
1126 ... max_percentile= 99.8,
1127 ... min_percentile= 5.0,
1128 ... )
1129 ... ),
1130 ... ClipDescr(kwargs=ClipKwargs(min=0.0, max=1.0)),
1131 ... EnsureDtypeDescr(kwargs=EnsureDtypeKwargs(dtype="uint8")),
1132 ... ]
1133 """
1135 implemented_id: ClassVar[Literal["ensure_dtype"]] = "ensure_dtype"
1136 if TYPE_CHECKING:
1137 id: Literal["ensure_dtype"] = "ensure_dtype"
1138 else:
1139 id: Literal["ensure_dtype"]
1141 kwargs: EnsureDtypeKwargs
1144class ScaleLinearKwargs(KwargsNode):
1145 """Key word arguments for [ScaleLinearDescr][]"""
1147 gain: float = 1.0
1148 """multiplicative factor"""
1150 offset: float = 0.0
1151 """additive term"""
1153 @model_validator(mode="after")
1154 def _validate(self) -> Self:
1155 if self.gain == 1.0 and self.offset == 0.0:
1156 raise ValueError(
1157 "Redundant linear scaling not allowd. Set `gain` != 1.0 and/or `offset`"
1158 + " != 0.0."
1159 )
1161 return self
1164class ScaleLinearAlongAxisKwargs(KwargsNode):
1165 """Key word arguments for [ScaleLinearDescr][]"""
1167 axis: Annotated[NonBatchAxisId, Field(examples=["channel"])]
1168 """The axis of gain and offset values."""
1170 gain: float | NotEmpty[list[float]] = 1.0
1171 """multiplicative factor"""
1173 offset: float | NotEmpty[list[float]] = 0.0
1174 """additive term"""
1176 @model_validator(mode="after")
1177 def _validate(self) -> Self:
1178 if isinstance(self.gain, list):
1179 if isinstance(self.offset, list):
1180 if len(self.gain) != len(self.offset):
1181 raise ValueError(
1182 f"Size of `gain` ({len(self.gain)}) and `offset` ({len(self.offset)}) must match."
1183 )
1184 else:
1185 self.offset = [float(self.offset)] * len(self.gain)
1186 elif isinstance(self.offset, list):
1187 self.gain = [float(self.gain)] * len(self.offset)
1188 else:
1189 raise ValueError(
1190 "Do not specify an `axis` for scalar gain and offset values."
1191 )
1193 if all(g == 1.0 for g in self.gain) and all(off == 0.0 for off in self.offset):
1194 raise ValueError(
1195 "Redundant linear scaling not allowd. Set `gain` != 1.0 and/or `offset`"
1196 + " != 0.0."
1197 )
1199 return self
1202class ScaleLinearDescr(NodeWithExplicitlySetFields):
1203 """Fixed linear scaling.
1205 Examples:
1206 1. Scale with scalar gain and offset
1207 - in YAML
1208 ```yaml
1209 preprocessing:
1210 - id: scale_linear
1211 kwargs:
1212 gain: 2.0
1213 offset: 3.0
1214 ```
1215 - in Python:
1217 >>> preprocessing = [
1218 ... ScaleLinearDescr(kwargs=ScaleLinearKwargs(gain= 2.0, offset=3.0))
1219 ... ]
1221 2. Independent scaling along an axis
1222 - in YAML
1223 ```yaml
1224 preprocessing:
1225 - id: scale_linear
1226 kwargs:
1227 axis: 'channel'
1228 gain: [1.0, 2.0, 3.0]
1229 ```
1230 - in Python:
1232 >>> preprocessing = [
1233 ... ScaleLinearDescr(
1234 ... kwargs=ScaleLinearAlongAxisKwargs(
1235 ... axis=AxisId("channel"),
1236 ... gain=[1.0, 2.0, 3.0],
1237 ... )
1238 ... )
1239 ... ]
1241 """
1243 implemented_id: ClassVar[Literal["scale_linear"]] = "scale_linear"
1244 if TYPE_CHECKING:
1245 id: Literal["scale_linear"] = "scale_linear"
1246 else:
1247 id: Literal["scale_linear"]
1248 kwargs: ScaleLinearKwargs | ScaleLinearAlongAxisKwargs
1251class SigmoidDescr(NodeWithExplicitlySetFields):
1252 """The logistic sigmoid function, a.k.a. expit function.
1254 Examples:
1255 - in YAML
1256 ```yaml
1257 postprocessing:
1258 - id: sigmoid
1259 ```
1260 - in Python:
1262 >>> postprocessing = [SigmoidDescr()]
1263 """
1265 implemented_id: ClassVar[Literal["sigmoid"]] = "sigmoid"
1266 if TYPE_CHECKING:
1267 id: Literal["sigmoid"] = "sigmoid"
1268 else:
1269 id: Literal["sigmoid"]
1271 @property
1272 def kwargs(self) -> KwargsNode:
1273 """empty kwargs"""
1274 return KwargsNode()
1277class SoftmaxKwargs(KwargsNode):
1278 """key word arguments for [SoftmaxDescr][]"""
1280 axis: Annotated[NonBatchAxisId, Field(examples=["channel"])] = CHANNEL_AXIS_ID
1281 """The axis to apply the softmax function along.
1282 Note:
1283 Defaults to 'channel' axis
1284 (which may not exist, in which case
1285 a different axis id has to be specified).
1286 """
1289class SoftmaxDescr(NodeWithExplicitlySetFields):
1290 """The softmax function.
1292 Examples:
1293 - in YAML
1294 ```yaml
1295 postprocessing:
1296 - id: softmax
1297 kwargs:
1298 axis: channel
1299 ```
1300 - in Python:
1302 >>> postprocessing = [SoftmaxDescr(kwargs=SoftmaxKwargs(axis=AxisId("channel")))]
1303 """
1305 implemented_id: ClassVar[Literal["softmax"]] = "softmax"
1306 if TYPE_CHECKING:
1307 id: Literal["softmax"] = "softmax"
1308 else:
1309 id: Literal["softmax"]
1311 kwargs: SoftmaxKwargs = Field(default_factory=SoftmaxKwargs.model_construct)
1314class _StardistPostprocessingKwargsBase(KwargsNode):
1315 """key word arguments for [StardistPostprocessingDescr][]"""
1317 prob_threshold: float
1318 """The probability threshold for object candidate selection."""
1320 nms_threshold: float
1321 """The IoU threshold for non-maximum suppression."""
1323 n_rays: int
1324 """Number of radial lines (rays) cast from the center of an object to its boundary."""
1327class StardistPostprocessingKwargs2D(_StardistPostprocessingKwargsBase):
1328 grid: tuple[int, int]
1329 """Grid size of network predictions."""
1331 b: int | tuple[tuple[int, int], tuple[int, int]]
1332 """Border region in which object probability is set to zero."""
1335class StardistPostprocessingKwargs3D(_StardistPostprocessingKwargsBase):
1336 grid: tuple[int, int, int]
1337 """Grid size of network predictions."""
1339 b: int | tuple[tuple[int, int], tuple[int, int], tuple[int, int]]
1340 """Border region in which object probability is set to zero."""
1342 anisotropy: tuple[float, float, float]
1343 """Anisotropy factors for 3D star-convex polyhedra, i.e. the physical pixel size along each spatial axis."""
1345 overlap_label: int | None = None
1346 """Optional label to apply to any area of overlapping predicted objects."""
1349class StardistPostprocessingDescr(NodeWithExplicitlySetFields):
1350 """Stardist postprocessing including non-maximum suppression and converting polygon representations to instance labels
1352 as described in:
1353 - Uwe Schmidt, Martin Weigert, Coleman Broaddus, and Gene Myers.
1354 [*Cell Detection with Star-convex Polygons*](https://arxiv.org/abs/1806.03535).
1355 International Conference on Medical Image Computing and Computer-Assisted Intervention (MICCAI), Granada, Spain, September 2018.
1356 - Martin Weigert, Uwe Schmidt, Robert Haase, Ko Sugawara, and Gene Myers.
1357 [*Star-convex Polyhedra for 3D Object Detection and Segmentation in Microscopy*](http://openaccess.thecvf.com/content_WACV_2020/papers/Weigert_Star-convex_Polyhedra_for_3D_Object_Detection_and_Segmentation_in_Microscopy_WACV_2020_paper.pdf).
1358 The IEEE Winter Conference on Applications of Computer Vision (WACV), Snowmass Village, Colorado, March 2020.
1360 Note: Only available if the `stardist` package is installed.
1361 """
1363 implemented_id: ClassVar[Literal["stardist_postprocessing"]] = (
1364 "stardist_postprocessing"
1365 )
1366 if TYPE_CHECKING:
1367 id: Literal["stardist_postprocessing"] = "stardist_postprocessing"
1368 else:
1369 id: Literal["stardist_postprocessing"]
1371 kwargs: StardistPostprocessingKwargs2D | StardistPostprocessingKwargs3D
1374class CellposeFlowDynamicsKwargs(KwargsNode):
1375 """key word arguments for [CellposeFlowDynamicsDescr][]"""
1377 cellprob_threshold: float
1378 flow_threshold: float
1379 do_3D: bool
1380 min_size: int = 15
1381 """Minimum size of objects to keep, in pixels. Default is 15, which is the default in Cellpose. Set to 0 to disable filtering by size."""
1382 output_dtype: Literal["uint16", "uint32"] = "uint16"
1385class CellposeFlowDynamicsDescr(NodeWithExplicitlySetFields):
1386 """Cellpose flow dynamics postprocessing as described in:
1387 - Carsen Stringer and Marius Pachitariu. [*Cellpose: a generalist algorithm for cellular segmentation*](https://www.nature.com/articles/s41592-020-01018-x). Nature Methods, 2021.
1389 Note: Only available if the `cellpose` package is installed.
1390 """
1392 implemented_id: ClassVar[Literal["cellpose_flow_dynamics"]] = (
1393 "cellpose_flow_dynamics"
1394 )
1395 if TYPE_CHECKING:
1396 id: Literal["cellpose_flow_dynamics"] = "cellpose_flow_dynamics"
1397 else:
1398 id: Literal["cellpose_flow_dynamics"]
1400 kwargs: CellposeFlowDynamicsKwargs
1403class CustomProcessingDescr(NodeWithExplicitlySetFields, FileDescr):
1404 """Custom (post)processing op — source file shipped inline with the model.
1406 Supports (post)processing that cannot be expressed by the built-in named
1407 operations (watershed, connected components, etc.)
1408 using a simple Python callable interface.
1410 The op is implemented in a ``.py`` file packaged alongside the model weights.
1411 Two styles are supported:
1413 *Callable class* — kwargs go to ``__init__``, tensors arrive in ``__call__``:
1415 .. code-block:: python
1417 # my_postprocess.py
1418 import numpy as np
1420 class my_postprocess:
1421 def __init__(self, threshold: float = 0.5) -> None:
1422 self.threshold = threshold
1423 def __call__(self, *arrays: np.ndarray) -> np.ndarray:
1424 # arrays = model output tensors in rdf.yaml declaration order
1425 return (arrays[0] > self.threshold).astype(np.uint8)
1427 *Factory function* — alternative closure style, identical runtime behaviour:
1429 .. code-block:: python
1431 # my_postprocess.py
1432 import numpy as np
1434 def my_postprocess(threshold: float = 0.5):
1435 def run(*arrays: np.ndarray) -> np.ndarray:
1436 return (arrays[0] > threshold).astype(np.uint8)
1437 return run
1439 Reference it in ``rdf.yaml`` with the source file included in the package:
1441 .. code-block:: yaml
1443 postprocessing:
1444 - id: custom
1445 callable: my_postprocess # class or function name in source
1446 source: my_postprocess.py # packaged alongside weights
1447 sha256: <hash> # sha256 of the source file
1448 kwargs: # forwarded to __init__ / factory
1449 threshold: 0.5
1451 **Security:** source files are SHA-256 verified before execution.
1452 Execution requires explicit opt-in in bioimageio.core and curator
1453 review before Zoo publication.
1454 """
1456 implemented_id: ClassVar[Literal["custom"]] = "custom"
1457 if TYPE_CHECKING:
1458 id: Literal["custom"] = "custom"
1459 else:
1460 id: Literal["custom"]
1462 callable: Annotated[
1463 str,
1464 Field(examples=["my_postprocess_factory", "MyPostprocessClass"]),
1465 ]
1466 """Name of the callable class or factory function defined in ``source``.
1468 At runtime: ``op = callable(**kwargs)``, then ``result = op(*output_tensors)``
1469 per image. Both a class with ``__call__`` and a factory function returning
1470 a callable satisfy this protocol."""
1472 source: Annotated[FileSource, AfterValidator(wo_special_file_name)]
1473 """Python source file (included when packaging the model)."""
1475 kwargs: dict[str, YamlValue] = Field(
1476 default_factory=cast(Callable[[], dict[str, YamlValue]], dict)
1477 )
1478 """Keyword arguments forwarded to the callable (``__init__`` or factory)."""
1480 @model_serializer(mode="wrap", when_used="unless-none")
1481 def _serialize(
1482 self, nxt: SerializerFunctionWrapHandler, info: SerializationInfo
1483 ) -> dict[str, YamlValue]:
1484 return package_file_descr_serializer(self, nxt, info)
1487class FixedZeroMeanUnitVarianceKwargs(KwargsNode):
1488 """key word arguments for [FixedZeroMeanUnitVarianceDescr][]"""
1490 mean: float
1491 """The mean value to normalize with."""
1493 std: Annotated[float, Ge(1e-6)]
1494 """The standard deviation value to normalize with."""
1497class FixedZeroMeanUnitVarianceAlongAxisKwargs(KwargsNode):
1498 """key word arguments for [FixedZeroMeanUnitVarianceDescr][]"""
1500 mean: NotEmpty[list[float]]
1501 """The mean value(s) to normalize with."""
1503 std: NotEmpty[list[Annotated[float, Ge(1e-6)]]]
1504 """The standard deviation value(s) to normalize with.
1505 Size must match `mean` values."""
1507 axis: Annotated[NonBatchAxisId, Field(examples=["channel", "index"])]
1508 """The axis of the mean/std values to normalize each entry along that dimension
1509 separately."""
1511 @model_validator(mode="after")
1512 def _mean_and_std_match(self) -> Self:
1513 if len(self.mean) != len(self.std):
1514 raise ValueError(
1515 f"Size of `mean` ({len(self.mean)}) and `std` ({len(self.std)})"
1516 + " must match."
1517 )
1519 return self
1522class FixedZeroMeanUnitVarianceDescr(NodeWithExplicitlySetFields):
1523 """Subtract a given mean and divide by the standard deviation.
1525 Normalize with fixed, precomputed values for
1526 `FixedZeroMeanUnitVarianceKwargs.mean` and `FixedZeroMeanUnitVarianceKwargs.std`
1527 Use `FixedZeroMeanUnitVarianceAlongAxisKwargs` for independent scaling along given
1528 axes.
1530 Examples:
1531 1. scalar value for whole tensor
1532 - in YAML
1533 ```yaml
1534 preprocessing:
1535 - id: fixed_zero_mean_unit_variance
1536 kwargs:
1537 mean: 103.5
1538 std: 13.7
1539 ```
1540 - in Python
1541 >>> preprocessing = [FixedZeroMeanUnitVarianceDescr(
1542 ... kwargs=FixedZeroMeanUnitVarianceKwargs(mean=103.5, std=13.7)
1543 ... )]
1545 2. independently along an axis
1546 - in YAML
1547 ```yaml
1548 preprocessing:
1549 - id: fixed_zero_mean_unit_variance
1550 kwargs:
1551 axis: channel
1552 mean: [101.5, 102.5, 103.5]
1553 std: [11.7, 12.7, 13.7]
1554 ```
1555 - in Python
1556 >>> preprocessing = [FixedZeroMeanUnitVarianceDescr(
1557 ... kwargs=FixedZeroMeanUnitVarianceAlongAxisKwargs(
1558 ... axis=AxisId("channel"),
1559 ... mean=[101.5, 102.5, 103.5],
1560 ... std=[11.7, 12.7, 13.7],
1561 ... )
1562 ... )]
1563 """
1565 implemented_id: ClassVar[Literal["fixed_zero_mean_unit_variance"]] = (
1566 "fixed_zero_mean_unit_variance"
1567 )
1568 if TYPE_CHECKING:
1569 id: Literal["fixed_zero_mean_unit_variance"] = "fixed_zero_mean_unit_variance"
1570 else:
1571 id: Literal["fixed_zero_mean_unit_variance"]
1573 kwargs: FixedZeroMeanUnitVarianceKwargs | FixedZeroMeanUnitVarianceAlongAxisKwargs
1576class ZeroMeanUnitVarianceKwargs(KwargsNode):
1577 """key word arguments for [ZeroMeanUnitVarianceDescr][]"""
1579 axes: Annotated[Sequence[AxisId] | None, Field(examples=[("batch", "x", "y")])] = (
1580 None
1581 )
1582 """The subset of axes to normalize jointly, i.e. axes to reduce to compute mean/std.
1583 For example to normalize 'batch', 'x' and 'y' jointly in a tensor ('batch', 'channel', 'y', 'x')
1584 resulting in a tensor of equal shape normalized per channel, specify `axes=('batch', 'x', 'y')`.
1585 To normalize each sample independently leave out the 'batch' axis.
1586 Default: Scale all axes jointly."""
1588 eps: Annotated[float, Interval(gt=0, le=0.1)] = 1e-6
1589 """epsilon for numeric stability: `out = (tensor - mean) / (std + eps)`."""
1592class ZeroMeanUnitVarianceDescr(NodeWithExplicitlySetFields):
1593 """Subtract mean and divide by variance.
1595 Examples:
1596 Subtract tensor mean and variance
1597 - in YAML
1598 ```yaml
1599 preprocessing:
1600 - id: zero_mean_unit_variance
1601 ```
1602 - in Python
1603 >>> preprocessing = [ZeroMeanUnitVarianceDescr()]
1604 """
1606 implemented_id: ClassVar[Literal["zero_mean_unit_variance"]] = (
1607 "zero_mean_unit_variance"
1608 )
1609 if TYPE_CHECKING:
1610 id: Literal["zero_mean_unit_variance"] = "zero_mean_unit_variance"
1611 else:
1612 id: Literal["zero_mean_unit_variance"]
1614 kwargs: ZeroMeanUnitVarianceKwargs = Field(
1615 default_factory=ZeroMeanUnitVarianceKwargs.model_construct
1616 )
1619class ScaleRangeKwargs(KwargsNode):
1620 """key word arguments for [ScaleRangeDescr][]
1622 For `min_percentile`=0.0 (the default) and `max_percentile`=100 (the default)
1623 this processing step normalizes data to the [0, 1] intervall.
1624 For other percentiles the normalized values will partially be outside the [0, 1]
1625 intervall. Use `ScaleRange` followed by `ClipDescr` if you want to limit the
1626 normalized values to a range.
1627 """
1629 axes: Annotated[Sequence[AxisId] | None, Field(examples=[("batch", "x", "y")])] = (
1630 None
1631 )
1632 """The subset of axes to normalize jointly, i.e. axes to reduce to compute the min/max percentile value.
1633 For example to normalize 'batch', 'x' and 'y' jointly in a tensor ('batch', 'channel', 'y', 'x')
1634 resulting in a tensor of equal shape normalized per channel, specify `axes=('batch', 'x', 'y')`.
1635 To normalize samples independently, leave out the "batch" axis.
1636 Default: Scale all axes jointly."""
1638 min_percentile: Annotated[float, Interval(ge=0, lt=100)] = 0.0
1639 """The lower percentile used to determine the value to align with zero."""
1641 max_percentile: Annotated[float, Interval(gt=1, le=100)] = 100.0
1642 """The upper percentile used to determine the value to align with one.
1643 Has to be bigger than `min_percentile`.
1644 The range is 1 to 100 instead of 0 to 100 to avoid mistakenly
1645 accepting percentiles specified in the range 0.0 to 1.0."""
1647 eps: Annotated[float, Interval(gt=0, le=0.1)] = 1e-6
1648 """Epsilon for numeric stability.
1649 `out = (tensor - v_lower) / (v_upper - v_lower + eps)`;
1650 with `v_lower,v_upper` values at the respective percentiles."""
1652 reference_tensor: TensorId | None = None
1653 """ID of the unprocessed input tensor to compute the percentiles from.
1654 Default: The tensor itself.
1655 """
1657 @field_validator("max_percentile", mode="after")
1658 @classmethod
1659 def min_smaller_max(cls, value: float, info: ValidationInfo) -> float:
1660 if (min_p := info.data["min_percentile"]) >= value:
1661 raise ValueError(f"min_percentile {min_p} >= max_percentile {value}")
1663 return value
1666class ScaleRangeDescr(NodeWithExplicitlySetFields):
1667 """Scale with percentiles.
1669 Examples:
1670 1. Scale linearly to map 5th percentile to 0 and 99.8th percentile to 1.0
1671 - in YAML
1672 ```yaml
1673 preprocessing:
1674 - id: scale_range
1675 kwargs:
1676 axes: ['y', 'x']
1677 max_percentile: 99.8
1678 min_percentile: 5.0
1679 ```
1680 - in Python
1682 >>> preprocessing = [
1683 ... ScaleRangeDescr(
1684 ... kwargs=ScaleRangeKwargs(
1685 ... axes= (AxisId('y'), AxisId('x')),
1686 ... max_percentile= 99.8,
1687 ... min_percentile= 5.0,
1688 ... )
1689 ... )
1690 ... ]
1692 2. Combine the above scaling with additional clipping to clip values outside the range given by the percentiles.
1693 - in YAML
1694 ```yaml
1695 preprocessing:
1696 - id: scale_range
1697 kwargs:
1698 axes: ['y', 'x']
1699 max_percentile: 99.8
1700 min_percentile: 5.0
1701 - id: clip
1702 kwargs:
1703 min: 0.0
1704 max: 1.0
1705 ```
1706 - in Python
1708 >>> preprocessing = [
1709 ... ScaleRangeDescr(
1710 ... kwargs=ScaleRangeKwargs(
1711 ... axes= (AxisId('y'), AxisId('x')),
1712 ... max_percentile= 99.8,
1713 ... min_percentile= 5.0,
1714 ... )
1715 ... ),
1716 ... ClipDescr(
1717 ... kwargs=ClipKwargs(
1718 ... min=0.0,
1719 ... max=1.0,
1720 ... )
1721 ... ),
1722 ... ]
1724 """
1726 implemented_id: ClassVar[Literal["scale_range"]] = "scale_range"
1727 if TYPE_CHECKING:
1728 id: Literal["scale_range"] = "scale_range"
1729 else:
1730 id: Literal["scale_range"]
1731 kwargs: ScaleRangeKwargs = Field(default_factory=ScaleRangeKwargs.model_construct)
1734class ScaleMeanVarianceKwargs(KwargsNode):
1735 """key word arguments for [ScaleMeanVarianceKwargs][]"""
1737 reference_tensor: TensorId
1738 """ID of unprocessed input tensor to match."""
1740 axes: Annotated[Sequence[AxisId] | None, Field(examples=[("batch", "x", "y")])] = (
1741 None
1742 )
1743 """The subset of axes to normalize jointly, i.e. axes to reduce to compute mean/std.
1744 For example to normalize 'batch', 'x' and 'y' jointly in a tensor ('batch', 'channel', 'y', 'x')
1745 resulting in a tensor of equal shape normalized per channel, specify `axes=('batch', 'x', 'y')`.
1746 To normalize samples independently, leave out the 'batch' axis.
1747 Default: Scale all axes jointly."""
1749 eps: Annotated[float, Interval(gt=0, le=0.1)] = 1e-6
1750 """Epsilon for numeric stability:
1751 `out = (tensor - mean) / (std + eps) * (ref_std + eps) + ref_mean.`"""
1754class ScaleMeanVarianceDescr(NodeWithExplicitlySetFields):
1755 """Scale a tensor's data distribution to match another tensor's mean/std.
1756 `out = (tensor - mean) / (std + eps) * (ref_std + eps) + ref_mean.`
1757 """
1759 implemented_id: ClassVar[Literal["scale_mean_variance"]] = "scale_mean_variance"
1760 if TYPE_CHECKING:
1761 id: Literal["scale_mean_variance"] = "scale_mean_variance"
1762 else:
1763 id: Literal["scale_mean_variance"]
1764 kwargs: ScaleMeanVarianceKwargs
1767PreprocessingDescr = Annotated[
1768 BinarizeDescr
1769 | ClipDescr
1770 | EnsureDtypeDescr
1771 | FixedZeroMeanUnitVarianceDescr
1772 | ScaleLinearDescr
1773 | ScaleRangeDescr
1774 | SigmoidDescr
1775 | SoftmaxDescr
1776 | ZeroMeanUnitVarianceDescr,
1777 Discriminator("id"),
1778]
1779PostprocessingDescr = Annotated[
1780 BinarizeDescr
1781 | CellposeFlowDynamicsDescr
1782 | ClipDescr
1783 | CustomProcessingDescr
1784 | EnsureDtypeDescr
1785 | FixedZeroMeanUnitVarianceDescr
1786 | ScaleLinearDescr
1787 | ScaleMeanVarianceDescr
1788 | ScaleRangeDescr
1789 | SigmoidDescr
1790 | SoftmaxDescr
1791 | StardistPostprocessingDescr
1792 | ZeroMeanUnitVarianceDescr,
1793 Discriminator("id"),
1794]
1796IO_AxisT = TypeVar("IO_AxisT", InputAxis, OutputAxis)
1799class TensorDescrBase(Node, Generic[IO_AxisT]):
1800 id: TensorId
1801 """Tensor id. No duplicates are allowed."""
1803 description: Annotated[str, MaxLen(128)] = ""
1804 """free text description"""
1806 axes: NotEmpty[Sequence[IO_AxisT]]
1807 """tensor axes"""
1809 @property
1810 def shape(self):
1811 return tuple(a.size for a in self.axes)
1813 @field_validator("axes", mode="after", check_fields=False)
1814 @classmethod
1815 def _validate_axes(cls, axes: Sequence[AnyAxis]) -> Sequence[AnyAxis]:
1816 batch_axes = [a for a in axes if a.type == "batch"]
1817 if len(batch_axes) > 1:
1818 raise ValueError(
1819 f"Only one batch axis (per tensor) allowed, but got {batch_axes}"
1820 )
1822 seen_ids: set[AxisId] = set()
1823 duplicate_axes_ids: set[AxisId] = set()
1824 for a in axes:
1825 (duplicate_axes_ids if a.id in seen_ids else seen_ids).add(a.id)
1827 if duplicate_axes_ids:
1828 raise ValueError(f"Duplicate axis ids: {duplicate_axes_ids}")
1830 return axes
1832 test_tensor: FAIR[FileDescr_package | None] = None
1833 """An example tensor to use for testing.
1834 Using the model with the test input tensors is expected to yield the test output tensors.
1835 Each test tensor has be a an ndarray in the
1836 [numpy.lib file format](https://numpy.org/doc/stable/reference/generated/numpy.lib.format.html#module-numpy.lib.format).
1837 The file extension must be '.npy'.
1838 Its shape must be valid and along any reproducibly concatenable input axis with parameterized size
1839 larger than the minimal allowed axis size (so blockwise reproducibility checks can be performed).
1840 """
1842 sample_tensor: FAIR[FileDescr_package | None] = None
1843 """A sample tensor to illustrate a possible input/output for the model,
1844 The sample image primarily serves to inform a human user about an example use case
1845 and is typically stored as .hdf5, .png or .tiff.
1846 It has to be readable by the [imageio library](https://imageio.readthedocs.io/en/stable/formats/index.html#supported-formats)
1847 (numpy's `.npy` format is not supported).
1848 The image dimensionality has to match the number of axes specified in this tensor description.
1849 """
1851 @model_validator(mode="after")
1852 def _validate_sample_tensor(self) -> Self:
1853 if self.sample_tensor is None or not get_validation_context().perform_io_checks:
1854 return self
1856 reader = get_reader(self.sample_tensor.source, sha256=self.sample_tensor.sha256)
1857 tensor: NDArray[Any] = imread(
1858 reader.read(),
1859 extension=PurePosixPath(reader.original_file_name).suffix,
1860 )
1861 n_dims = len(tensor.squeeze().shape)
1862 n_dims_min = n_dims_max = len(self.axes)
1864 for a in self.axes:
1865 if isinstance(a, BatchAxis):
1866 n_dims_min -= 1
1867 elif isinstance(a.size, int):
1868 if a.size == 1:
1869 n_dims_min -= 1
1870 elif isinstance(a.size, (ParameterizedSize, DataDependentSize)):
1871 if a.size.min == 1:
1872 n_dims_min -= 1
1873 elif isinstance(a.size, SizeReference):
1874 if a.id != a.size.axis_id:
1875 raise ValueError(
1876 f"Axis {a.id} has a size reference to a different axis {a.size.axis_id}."
1877 )
1878 if a.size.offset < 2:
1879 # size reference may result in singleton axis
1880 n_dims_min -= 1
1881 else:
1882 assert_never(a.size)
1884 n_dims_min = max(0, n_dims_min)
1885 if n_dims < n_dims_min or n_dims > n_dims_max:
1886 raise ValueError(
1887 f"Expected sample tensor to have {n_dims_min} to"
1888 + f" {n_dims_max} dimensions, but found {n_dims} (shape: {tensor.shape})."
1889 )
1891 return self
1893 data: TensorDataDescr | NotEmpty[Sequence[TensorDataDescr]] = (
1894 IntervalOrRatioDataDescr()
1895 )
1896 """Description of the tensor's data values, optionally per channel.
1897 If specified per channel, the data `type` needs to match across channels."""
1899 @property
1900 def dtype(
1901 self,
1902 ) -> Literal[
1903 "float32",
1904 "float64",
1905 "uint8",
1906 "int8",
1907 "uint16",
1908 "int16",
1909 "uint32",
1910 "int32",
1911 "uint64",
1912 "int64",
1913 "bool",
1914 ]:
1915 """dtype as specified under `data.type` or `data[i].type`"""
1916 if isinstance(self.data, collections.abc.Sequence):
1917 return self.data[0].type
1918 else:
1919 return self.data.type
1921 @field_validator("data", mode="after")
1922 @classmethod
1923 def _check_data_type_across_channels(
1924 cls, value: TensorDataDescr | NotEmpty[Sequence[TensorDataDescr]]
1925 ) -> TensorDataDescr | NotEmpty[Sequence[TensorDataDescr]]:
1926 if not isinstance(value, list):
1927 return value
1929 dtypes = {t.type for t in value}
1930 if len(dtypes) > 1:
1931 raise ValueError(
1932 "Tensor data descriptions per channel need to agree in their data"
1933 + f" `type`, but found {dtypes}."
1934 )
1936 return value
1938 @model_validator(mode="after")
1939 def _check_data_matches_channelaxis(self) -> Self:
1940 if not isinstance(self.data, (list, tuple)):
1941 return self
1943 for a in self.axes:
1944 if isinstance(a, ChannelAxis):
1945 size = a.size
1946 assert isinstance(size, int)
1947 break
1948 else:
1949 return self
1951 if len(self.data) != size:
1952 raise ValueError(
1953 f"Got tensor data descriptions for {len(self.data)} channels, but"
1954 + f" '{a.id}' axis has size {size}."
1955 )
1957 return self
1959 def get_axis_sizes_for_array(self, array: NDArray[Any]) -> dict[AxisId, int]:
1960 if len(array.shape) != len(self.axes):
1961 raise ValueError(
1962 f"Dimension mismatch: array shape {array.shape} (#{len(array.shape)})"
1963 + f" incompatible with {len(self.axes)} axes."
1964 )
1965 return {a.id: array.shape[i] for i, a in enumerate(self.axes)}
1968class ConstantPadding(Node):
1969 mode: Literal["constant"] = "constant"
1970 value: int | float = 0
1973class EdgePadding(Node):
1974 mode: Literal["edge"] = "edge"
1977class ReflectPadding(Node):
1978 mode: Literal["reflect"] = "reflect"
1981class SymmetricPadding(Node):
1982 mode: Literal["symmetric"] = "symmetric"
1985Padding: TypeAlias = ConstantPadding | EdgePadding | ReflectPadding | SymmetricPadding
1988class ModelId(ResourceId):
1989 pass
1992class InputTensorDescr(TensorDescrBase[InputAxis]):
1993 id: TensorId = TensorId("input")
1994 """Input tensor id.
1995 No duplicates are allowed across all inputs and outputs."""
1997 output_of: ModelId | None = None
1998 """If this input tensor is the output of another model, specify the model id here.
1999 This model's input id must match the output id of the referenced model.
2000 """
2002 @model_validator(mode="after")
2003 def _validate_output_of(self) -> Self:
2004 if self.output_of is None:
2005 return self
2007 try:
2008 with get_validation_context().replace(perform_io_checks=False):
2009 opened_ref_model = open_bioimageio_yaml(self.output_of)
2010 format_version = opened_ref_model.content["format_version"]
2011 assert isinstance(format_version, str)
2012 if format_version.startswith("0.4"):
2013 ref_model = _ModelDescr04.model_validate(opened_ref_model.content)
2014 else:
2015 ref_model = ModelDescr.model_validate(opened_ref_model.content)
2016 except Exception as e:
2017 raise ValueError(
2018 f"Failed to load model '{self.output_of}' referenced under output_of: {e}"
2019 )
2021 try:
2022 ref_model_outputs = {
2023 t.id if isinstance(t, OutputTensorDescr) else TensorId(t.name)
2024 for t in ref_model.outputs
2025 }
2026 except Exception as e:
2027 raise ValueError(
2028 f"Failed to read output IDs of model '{self.output_of}' referenced under output_of: {e}"
2029 )
2031 if self.id not in ref_model_outputs:
2032 raise ValueError(
2033 f"Input tensor '{self.id}' is specified as output of model '{self.output_of}', "
2034 + f"but that model's outputs are {ref_model_outputs}."
2035 )
2036 return self
2038 optional: bool = False
2039 """indicates that this tensor may be `None`"""
2041 pad: Padding | None = None
2042 """Explicitly specify how to pad this input tensor.
2044 Use `axes[i].pad` to specify padding width.
2046 Note:
2047 Non-blockwise sample prediction only applies padding for axes with a `pad` specification.
2048 """
2050 preprocessing: list[PreprocessingDescr] = Field(
2051 default_factory=cast(Callable[[], list[PreprocessingDescr]], list)
2052 )
2053 """Description of how this input should be preprocessed.
2055 notes:
2056 - If preprocessing does not start with an 'ensure_dtype' entry, it is added
2057 to ensure an input tensor's data type matches the input tensor's data description.
2058 - If preprocessing does not end with an 'ensure_dtype' or 'binarize' entry, an
2059 'ensure_dtype' step is added to ensure preprocessing steps are not unintentionally
2060 changing the data type.
2061 """
2063 @model_validator(mode="after")
2064 def _validate_preprocessing_kwargs(self) -> Self:
2065 axes_ids = [a.id for a in self.axes]
2066 for p in self.preprocessing:
2067 kwargs_axes: Sequence[Any] | None = p.kwargs.get("axes")
2068 if kwargs_axes is None:
2069 continue
2071 if not isinstance(kwargs_axes, collections.abc.Sequence):
2072 raise ValueError(
2073 f"Expected `preprocessing.i.kwargs.axes` to be a sequence, but got {type(kwargs_axes)}"
2074 )
2076 if any(a not in axes_ids for a in kwargs_axes):
2077 raise ValueError(
2078 "`preprocessing.i.kwargs.axes` needs to be subset of axes ids"
2079 )
2081 if isinstance(self.data, (NominalOrOrdinalDataDescr, IntervalOrRatioDataDescr)):
2082 dtype = self.data.type
2083 else:
2084 dtype = self.data[0].type
2086 # ensure `preprocessing` begins with `EnsureDtypeDescr`
2087 if not self.preprocessing or not isinstance(
2088 self.preprocessing[0], EnsureDtypeDescr
2089 ):
2090 self.preprocessing.insert(
2091 0, EnsureDtypeDescr(kwargs=EnsureDtypeKwargs(dtype=dtype))
2092 )
2094 # ensure `preprocessing` ends with `EnsureDtypeDescr` or `BinarizeDescr`
2095 if not isinstance(self.preprocessing[-1], (EnsureDtypeDescr, BinarizeDescr)):
2096 self.preprocessing.append(
2097 EnsureDtypeDescr(kwargs=EnsureDtypeKwargs(dtype=dtype))
2098 )
2100 return self
2103def convert_axes(
2104 axes: str,
2105 *,
2106 shape: Sequence[int] | _ParameterizedInputShape_v0_4 | _ImplicitOutputShape_v0_4,
2107 tensor_type: Literal["input", "output"],
2108 halo: Sequence[int] | None,
2109 size_refs: Mapping[_TensorName_v0_4, Mapping[str, int]],
2110):
2111 ret: list[AnyAxis] = []
2112 for i, a in enumerate(axes):
2113 axis_type = _AXIS_TYPE_MAP.get(a, a)
2114 if axis_type == "batch":
2115 ret.append(BatchAxis())
2116 continue
2118 scale = 1.0
2119 if isinstance(shape, _ParameterizedInputShape_v0_4):
2120 if shape.step[i] == 0:
2121 size = shape.min[i]
2122 else:
2123 size = ParameterizedSize(min=shape.min[i], step=shape.step[i])
2124 elif isinstance(shape, _ImplicitOutputShape_v0_4):
2125 ref_t = str(shape.reference_tensor)
2126 if ref_t.count(".") == 1:
2127 t_id, orig_a_id = ref_t.split(".")
2128 else:
2129 t_id = ref_t
2130 orig_a_id = a
2132 a_id = _AXIS_ID_MAP.get(orig_a_id, a)
2133 if not (orig_scale := shape.scale[i]):
2134 # old way to insert a new axis dimension
2135 size = int(2 * shape.offset[i])
2136 else:
2137 scale = 1 / orig_scale
2138 if axis_type in ("channel", "index"):
2139 # these axes no longer have a scale
2140 offset_from_scale = orig_scale * size_refs.get(
2141 _TensorName_v0_4(t_id), {}
2142 ).get(orig_a_id, 0)
2143 else:
2144 offset_from_scale = 0
2145 size = SizeReference(
2146 tensor_id=TensorId(t_id),
2147 axis_id=AxisId(a_id),
2148 offset=int(offset_from_scale + 2 * shape.offset[i]),
2149 )
2150 else:
2151 size = shape[i]
2153 if axis_type == "time":
2154 if tensor_type == "input":
2155 ret.append(TimeInputAxis(size=size, scale=scale))
2156 else:
2157 assert not isinstance(size, ParameterizedSize)
2158 if halo is None:
2159 ret.append(TimeOutputAxis(size=size, scale=scale))
2160 else:
2161 assert not isinstance(size, int)
2162 ret.append(
2163 TimeOutputAxisWithHalo(size=size, scale=scale, halo=halo[i])
2164 )
2166 elif axis_type == "index":
2167 if tensor_type == "input":
2168 ret.append(IndexInputAxis(size=size))
2169 else:
2170 if isinstance(size, ParameterizedSize):
2171 size = DataDependentSize(min=size.min)
2173 ret.append(IndexOutputAxis(size=size))
2174 elif axis_type == "channel":
2175 assert not isinstance(size, ParameterizedSize)
2176 if isinstance(size, SizeReference):
2177 warnings.warn(
2178 "Conversion of channel size from an implicit output shape may be"
2179 + " wrong"
2180 )
2181 ret.append(
2182 ChannelAxis(
2183 channel_names=[f"channel{i}" for i in range(size.offset)]
2184 )
2185 )
2186 else:
2187 ret.append(
2188 ChannelAxis(channel_names=[f"channel{i}" for i in range(size)])
2189 )
2190 elif axis_type == "space":
2191 if tensor_type == "input":
2192 ret.append(SpaceInputAxis(id=AxisId(a), size=size, scale=scale))
2193 else:
2194 assert not isinstance(size, ParameterizedSize)
2195 if halo is None or halo[i] == 0:
2196 ret.append(SpaceOutputAxis(id=AxisId(a), size=size, scale=scale))
2197 elif isinstance(size, int):
2198 raise NotImplementedError(
2199 f"output axis with halo and fixed size (here {size}) not allowed"
2200 )
2201 else:
2202 ret.append(
2203 SpaceOutputAxisWithHalo(
2204 id=AxisId(a), size=size, scale=scale, halo=halo[i]
2205 )
2206 )
2208 return ret
2211def _axes_letters_to_ids(
2212 axes: str | None,
2213) -> list[AxisId] | None:
2214 if axes is None:
2215 return None
2217 return [AxisId(a) for a in axes]
2220def _get_complement_v04_axis(
2221 tensor_axes: Sequence[str], axes: Sequence[str] | None
2222) -> AxisId | None:
2223 if axes is None:
2224 return None
2226 non_complement_axes = set(axes) | {"b"}
2227 complement_axes = [a for a in tensor_axes if a not in non_complement_axes]
2228 if len(complement_axes) > 1:
2229 raise ValueError(
2230 f"Expected none or a single complement axis, but axes '{axes}' "
2231 + f"for tensor dims '{tensor_axes}' leave '{complement_axes}'."
2232 )
2234 return None if not complement_axes else AxisId(complement_axes[0])
2237def _convert_proc(
2238 p: _PreprocessingDescr_v0_4 | _PostprocessingDescr_v0_4,
2239 tensor_axes: Sequence[str],
2240) -> PreprocessingDescr | PostprocessingDescr:
2241 if isinstance(p, _BinarizeDescr_v0_4):
2242 return BinarizeDescr(kwargs=BinarizeKwargs(threshold=p.kwargs.threshold))
2243 elif isinstance(p, _ClipDescr_v0_4):
2244 return ClipDescr(kwargs=ClipKwargs(min=p.kwargs.min, max=p.kwargs.max))
2245 elif isinstance(p, _SigmoidDescr_v0_4):
2246 return SigmoidDescr()
2247 elif isinstance(p, _ScaleLinearDescr_v0_4):
2248 axes = _axes_letters_to_ids(p.kwargs.axes)
2249 if p.kwargs.axes is None:
2250 axis = None
2251 else:
2252 axis = _get_complement_v04_axis(tensor_axes, p.kwargs.axes)
2254 if axis is None:
2255 assert not isinstance(p.kwargs.gain, list)
2256 assert not isinstance(p.kwargs.offset, list)
2257 kwargs = ScaleLinearKwargs(gain=p.kwargs.gain, offset=p.kwargs.offset)
2258 else:
2259 kwargs = ScaleLinearAlongAxisKwargs(
2260 axis=axis, gain=p.kwargs.gain, offset=p.kwargs.offset
2261 )
2262 return ScaleLinearDescr(kwargs=kwargs)
2263 elif isinstance(p, _ScaleMeanVarianceDescr_v0_4):
2264 return ScaleMeanVarianceDescr(
2265 kwargs=ScaleMeanVarianceKwargs(
2266 axes=_axes_letters_to_ids(p.kwargs.axes),
2267 reference_tensor=TensorId(str(p.kwargs.reference_tensor)),
2268 eps=p.kwargs.eps,
2269 )
2270 )
2271 elif isinstance(p, _ZeroMeanUnitVarianceDescr_v0_4):
2272 if p.kwargs.mode == "fixed":
2273 mean = p.kwargs.mean
2274 std = p.kwargs.std
2275 assert mean is not None
2276 assert std is not None
2278 axis = _get_complement_v04_axis(tensor_axes, p.kwargs.axes)
2280 if axis is None:
2281 if isinstance(mean, list):
2282 raise ValueError("Expected single float value for mean, not <list>")
2283 if isinstance(std, list):
2284 raise ValueError("Expected single float value for std, not <list>")
2285 return FixedZeroMeanUnitVarianceDescr(
2286 kwargs=FixedZeroMeanUnitVarianceKwargs.model_construct(
2287 mean=mean,
2288 std=std,
2289 )
2290 )
2291 else:
2292 if not isinstance(mean, list):
2293 mean = [float(mean)]
2294 if not isinstance(std, list):
2295 std = [float(std)]
2297 return FixedZeroMeanUnitVarianceDescr(
2298 kwargs=FixedZeroMeanUnitVarianceAlongAxisKwargs(
2299 axis=axis, mean=mean, std=std
2300 )
2301 )
2303 else:
2304 axes = _axes_letters_to_ids(p.kwargs.axes) or []
2305 if p.kwargs.mode == "per_dataset":
2306 axes = [AxisId("batch")] + axes
2307 if not axes:
2308 axes = None
2309 return ZeroMeanUnitVarianceDescr(
2310 kwargs=ZeroMeanUnitVarianceKwargs(axes=axes, eps=p.kwargs.eps)
2311 )
2313 elif isinstance(p, _ScaleRangeDescr_v0_4):
2314 return ScaleRangeDescr(
2315 kwargs=ScaleRangeKwargs(
2316 axes=_axes_letters_to_ids(p.kwargs.axes),
2317 min_percentile=p.kwargs.min_percentile,
2318 max_percentile=p.kwargs.max_percentile,
2319 eps=p.kwargs.eps,
2320 )
2321 )
2322 else:
2323 assert_never(p)
2326class _InputTensorConv(
2327 Converter[
2328 _InputTensorDescr_v0_4,
2329 InputTensorDescr,
2330 FileSource,
2331 FileSource | None,
2332 Mapping[_TensorName_v0_4, Mapping[str, int]],
2333 ]
2334):
2335 def _convert(
2336 self,
2337 src: _InputTensorDescr_v0_4,
2338 tgt: type[InputTensorDescr | dict[str, Any]],
2339 test_tensor: FileSource,
2340 sample_tensor: FileSource | None,
2341 size_refs: Mapping[_TensorName_v0_4, Mapping[str, int]],
2342 ) -> InputTensorDescr | dict[str, Any]:
2343 axes: list[InputAxis] = convert_axes( # pyright: ignore[reportAssignmentType]
2344 src.axes,
2345 shape=src.shape,
2346 tensor_type="input",
2347 halo=None,
2348 size_refs=size_refs,
2349 )
2350 prep: list[PreprocessingDescr] = []
2351 for p in src.preprocessing:
2352 cp = _convert_proc(p, src.axes)
2353 assert not isinstance(
2354 cp,
2355 (
2356 CellposeFlowDynamicsDescr,
2357 CustomProcessingDescr,
2358 ScaleMeanVarianceDescr,
2359 StardistPostprocessingDescr,
2360 ),
2361 )
2362 prep.append(cp)
2364 prep.append(EnsureDtypeDescr(kwargs=EnsureDtypeKwargs(dtype="float32")))
2366 return tgt(
2367 axes=axes,
2368 id=TensorId(str(src.name)),
2369 test_tensor=FileDescr(source=test_tensor),
2370 sample_tensor=(
2371 None if sample_tensor is None else FileDescr(source=sample_tensor)
2372 ),
2373 data={"type": src.data_type}, # pyright: ignore[reportArgumentType]
2374 preprocessing=prep,
2375 )
2378_input_tensor_conv = _InputTensorConv(_InputTensorDescr_v0_4, InputTensorDescr)
2381class OutputTensorDescr(TensorDescrBase[OutputAxis]):
2382 id: TensorId = TensorId("output")
2383 """Output tensor id.
2384 No duplicates are allowed across all inputs and outputs."""
2386 postprocessing: list[PostprocessingDescr] = Field(
2387 default_factory=cast(Callable[[], list[PostprocessingDescr]], list)
2388 )
2389 """Description of how this output should be postprocessed.
2391 note: `postprocessing` always ends with an 'ensure_dtype' operation.
2392 If not given this is added to cast to this tensor's `data.type`.
2393 """
2395 @model_validator(mode="after")
2396 def _validate_postprocessing_kwargs(self) -> Self:
2397 axes_ids = [a.id for a in self.axes]
2398 for p in self.postprocessing:
2399 kwargs_axes = p.kwargs.get("axes")
2400 if kwargs_axes is None:
2401 continue
2403 if not isinstance(kwargs_axes, collections.abc.Sequence):
2404 raise ValueError(
2405 f"expected `axes` sequence, but got {type(kwargs_axes)}"
2406 )
2408 kwargs_axes_seq: Sequence[Any] = cast(Sequence[Any], kwargs_axes)
2409 if any(a not in axes_ids for a in kwargs_axes_seq):
2410 raise ValueError("`kwargs.axes` needs to be subset of axes ids")
2412 if isinstance(self.data, (NominalOrOrdinalDataDescr, IntervalOrRatioDataDescr)):
2413 dtype = self.data.type
2414 else:
2415 dtype = self.data[0].type
2417 # ensure `postprocessing` ends with `EnsureDtypeDescr` or `BinarizeDescr`
2418 if not self.postprocessing or not isinstance(
2419 self.postprocessing[-1], (EnsureDtypeDescr, BinarizeDescr)
2420 ):
2421 self.postprocessing.append(
2422 EnsureDtypeDescr(kwargs=EnsureDtypeKwargs(dtype=dtype))
2423 )
2424 return self
2427class _OutputTensorConv(
2428 Converter[
2429 _OutputTensorDescr_v0_4,
2430 OutputTensorDescr,
2431 FileSource,
2432 FileSource | None,
2433 Mapping[_TensorName_v0_4, Mapping[str, int]],
2434 ]
2435):
2436 def _convert(
2437 self,
2438 src: _OutputTensorDescr_v0_4,
2439 tgt: type[OutputTensorDescr | dict[str, Any]],
2440 test_tensor: FileSource,
2441 sample_tensor: FileSource | None,
2442 size_refs: Mapping[_TensorName_v0_4, Mapping[str, int]],
2443 ) -> OutputTensorDescr | dict[str, Any]:
2444 # TODO: split convert_axes into convert_output_axes and convert_input_axes
2445 axes: list[OutputAxis] = convert_axes( # pyright: ignore[reportAssignmentType]
2446 src.axes,
2447 shape=src.shape,
2448 tensor_type="output",
2449 halo=src.halo,
2450 size_refs=size_refs,
2451 )
2452 data_descr: dict[str, Any] = {"type": src.data_type}
2453 if data_descr["type"] == "bool":
2454 data_descr["values"] = [False, True]
2456 return tgt(
2457 axes=axes,
2458 id=TensorId(str(src.name)),
2459 test_tensor=FileDescr(source=test_tensor),
2460 sample_tensor=(
2461 None if sample_tensor is None else FileDescr(source=sample_tensor)
2462 ),
2463 data=data_descr, # pyright: ignore[reportArgumentType]
2464 postprocessing=[_convert_proc(p, src.axes) for p in src.postprocessing],
2465 )
2468_output_tensor_conv = _OutputTensorConv(_OutputTensorDescr_v0_4, OutputTensorDescr)
2471TensorDescr: TypeAlias = InputTensorDescr | OutputTensorDescr
2474def get_halos(
2475 tensors: Mapping[TensorId, TensorDescr],
2476 /,
2477) -> dict[TensorId, dict[AxisId, tuple[int, int]]]:
2478 """Get all input and output halos from tensor descriptions.
2480 Note:
2481 - Input halos are to be padded
2482 - Output halos are to be cropped
2483 """
2484 halos: dict[TensorId, dict[AxisId, tuple[int, int]]] = {}
2485 for descr in tensors.values():
2486 if isinstance(descr, InputTensorDescr):
2487 continue
2488 for axis in descr.axes:
2489 if not isinstance(axis, WithHalo):
2490 continue
2492 ref_scale = next(
2493 a
2494 for a in tensors[axis.size.tensor_id].axes
2495 if a.id == axis.size.axis_id
2496 ).scale
2498 # set output halo (to be cropped)
2499 halos.setdefault(descr.id, {})[axis.id] = (axis.halo, axis.halo)
2500 # set input halo (to be padded)
2501 pad_width = int(axis.halo / axis.scale * ref_scale)
2502 halos.setdefault(axis.size.tensor_id, {})[axis.size.axis_id] = (
2503 pad_width,
2504 pad_width,
2505 )
2507 return halos
2510def validate_tensors(
2511 tensors: Mapping[TensorId, tuple[TensorDescr, NDArray[Any] | None]],
2512 tensor_origin: Literal[
2513 "source", "test_tensor"
2514 ] = "source", # for more precise error messages
2515 *,
2516 pad_inputs: bool | Literal["allow"] = True,
2517 crop_outputs: bool | Literal["allow"] = True,
2518):
2519 """Validate all inputs (and optionally output tensors) against their tensor descriptions.
2521 Args:
2522 tensors: Mapping of tensor id to a tuple of tensor description and optional numpy array.
2523 tensor_origin: String to use in error messages to indicate the origin of the tensors being validated.
2524 pad_inputs: Wether to apply/allow padding of inputs before shape comparison
2525 crop_outputs: Wether to apply/allow cropping of outputs before shape comparison.
2526 """
2527 all_tensor_axes: dict[TensorId, dict[AxisId, tuple[AnyAxis, int | None]]] = {}
2529 def e_msg_location(d: TensorDescr):
2530 return f"{'inputs' if isinstance(d, InputTensorDescr) else 'outputs'}[{d.id}]"
2532 for descr, array in tensors.values():
2533 if array is None:
2534 axis_sizes = {a.id: None for a in descr.axes}
2535 else:
2536 try:
2537 axis_sizes = descr.get_axis_sizes_for_array(array)
2538 except ValueError as e:
2539 raise ValueError(f"{e_msg_location(descr)} {e}")
2541 all_tensor_axes[descr.id] = {a.id: (a, axis_sizes[a.id]) for a in descr.axes}
2543 # get halos to be padded/cropped to validate against halo-adjusted sizes
2544 io_halos = get_halos({k: v[0] for k, v in tensors.items()})
2546 for descr, array in tensors.values():
2547 if array is None:
2548 continue
2550 if descr.dtype in ("float32", "float64"):
2551 invalid_test_tensor_dtype = array.dtype.name not in (
2552 "float32",
2553 "float64",
2554 "uint8",
2555 "int8",
2556 "uint16",
2557 "int16",
2558 "uint32",
2559 "int32",
2560 "uint64",
2561 "int64",
2562 )
2563 else:
2564 invalid_test_tensor_dtype = cast(bool, array.dtype.name != descr.dtype)
2566 if invalid_test_tensor_dtype:
2567 raise ValueError(
2568 f"{tensor_origin} data type '{array.dtype.name}' does not"
2569 + f" match described {e_msg_location(descr)}.dtype '{descr.dtype}'"
2570 )
2572 if array.min() > -1e-4 and array.max() < 1e-4:
2573 raise ValueError(
2574 "Output values are too small for reliable testing."
2575 + f" Values <-1e5 or >=1e5 must be present in {tensor_origin}"
2576 )
2578 for a in descr.axes:
2579 actual_size = all_tensor_axes[descr.id][a.id][1]
2581 if actual_size is None:
2582 continue
2584 if a.size is None:
2585 continue
2587 # add padding width to actual tensor size
2588 total_axis_halo = sum(io_halos.get(descr.id, {}).get(a.id, (0, 0)))
2589 if isinstance(descr, InputTensorDescr):
2590 # pad input halos
2591 actual_size_with_halo = actual_size + total_axis_halo
2592 if pad_inputs is True:
2593 check_sizes = {actual_size_with_halo}
2594 size_hint = " (after padding input halo)"
2595 elif pad_inputs == "allow":
2596 check_sizes = {actual_size, actual_size_with_halo}
2597 size_hint = " (with or without padding input halo)"
2598 elif pad_inputs is False:
2599 check_sizes = {actual_size}
2600 size_hint = ""
2601 else:
2602 assert_never(pad_inputs)
2604 elif isinstance(descr, OutputTensorDescr):
2605 # crop output halos
2606 actual_size_with_halo = max(0, actual_size - total_axis_halo)
2607 if crop_outputs is True:
2608 check_sizes = {actual_size_with_halo}
2609 size_hint = " (after cropping output halo)"
2610 elif crop_outputs == "allow":
2611 check_sizes = {actual_size, actual_size_with_halo}
2612 size_hint = " (with or without cropping output halo)"
2613 elif crop_outputs is False:
2614 check_sizes = {actual_size}
2615 size_hint = ""
2616 else:
2617 assert_never(crop_outputs)
2618 else:
2619 assert_never(descr)
2621 del actual_size # make sure we explicitly use unchanged or halo-adjusted size from here on
2623 if isinstance(a.size, int):
2624 if a.size not in check_sizes:
2625 raise ValueError(
2626 f"{e_msg_location(descr)}.axes[{a.id}]: {tensor_origin} axis "
2627 + f"has incompatible size {check_sizes}{size_hint}, expected {a.size}"
2628 )
2629 elif isinstance(a.size, (ParameterizedSize, DataDependentSize)):
2630 _ = try_all_raise_last(
2631 (partial(a.size.validate_size, s) for s in check_sizes),
2632 f"{e_msg_location(descr)}.axes[{a.id}]: {tensor_origin} axis ",
2633 )
2634 elif isinstance(a.size, SizeReference):
2635 ref_tensor_axes = all_tensor_axes.get(a.size.tensor_id)
2636 if ref_tensor_axes is None:
2637 raise ValueError(
2638 f"{e_msg_location(descr)}.axes[{a.id}].size.tensor_id: Unknown tensor"
2639 + f" reference '{a.size.tensor_id}', available: {list(all_tensor_axes)}"
2640 )
2642 ref_axis, ref_size = ref_tensor_axes.get(a.size.axis_id, (None, None))
2643 if ref_axis is None or ref_size is None:
2644 raise ValueError(
2645 f"{e_msg_location(descr)}.axes[{a.id}].size.axis_id: Unknown tensor axis"
2646 + f" reference '{a.size.tensor_id}.{a.size.axis_id}, available: {list(ref_tensor_axes)}"
2647 )
2649 if a.unit != ref_axis.unit:
2650 raise ValueError(
2651 f"{e_msg_location(descr)}.axes[{a.id}].size: `SizeReference` requires"
2652 + " axis and reference axis to have the same `unit`, but"
2653 + f" {a.unit}!={ref_axis.unit}"
2654 )
2656 if (
2657 expected_size := int(
2658 Fraction(ref_size)
2659 * Fraction(ref_axis.scale)
2660 / Fraction(a.scale)
2661 + a.size.offset
2662 )
2663 ) not in check_sizes:
2664 raise ValueError(
2665 f"{e_msg_location(descr)}.{tensor_origin}: axis '{a.id}' of size"
2666 + f" {check_sizes} invalid for referenced size {ref_size};"
2667 + f" expected {expected_size}"
2668 )
2669 else:
2670 assert_never(a.size)
2673FileDescr_dependencies = Annotated[
2674 FileDescr_package,
2675 WithSuffix((".yaml", ".yml"), case_sensitive=True),
2676 Field(examples=[{"source": "environment.yaml"}]),
2677]
2680class _ArchitectureCallableDescr(Node):
2681 callable: Annotated[Identifier, Field(examples=["MyNetworkClass", "get_my_model"])]
2682 """Identifier of the callable that returns a torch.nn.Module instance."""
2684 kwargs: dict[str, YamlValue] = Field(
2685 default_factory=cast(Callable[[], dict[str, YamlValue]], dict)
2686 )
2687 """key word arguments for the `callable`"""
2690class ArchitectureFromFileDescr(_ArchitectureCallableDescr, FileDescr):
2691 source: Annotated[FileSource, AfterValidator(wo_special_file_name)]
2692 """Architecture source file"""
2694 @model_serializer(mode="wrap", when_used="unless-none")
2695 def _serialize(self, nxt: SerializerFunctionWrapHandler, info: SerializationInfo):
2696 return package_file_descr_serializer(self, nxt, info)
2699class ArchitectureFromLibraryDescr(_ArchitectureCallableDescr):
2700 import_from: str
2701 """Where to import the callable from, i.e. `from <import_from> import <callable>`"""
2704class _ArchFileConv(
2705 Converter[
2706 _CallableFromFile_v0_4,
2707 ArchitectureFromFileDescr,
2708 Sha256 | None,
2709 dict[str, Any],
2710 ]
2711):
2712 def _convert(
2713 self,
2714 src: _CallableFromFile_v0_4,
2715 tgt: type[ArchitectureFromFileDescr | dict[str, Any]],
2716 sha256: Sha256 | None,
2717 kwargs: dict[str, Any],
2718 ) -> ArchitectureFromFileDescr | dict[str, Any]:
2719 if src.startswith("http") and src.count(":") == 2:
2720 http, source, callable_ = src.split(":")
2721 source = f"{http}:{source}"
2722 elif not src.startswith("http") and src.count(":") == 1:
2723 source, callable_ = src.split(":")
2724 else:
2725 source = str(src)
2726 callable_ = str(src)
2727 return tgt(
2728 callable=Identifier(callable_),
2729 source=cast(FileSource, source),
2730 sha256=sha256,
2731 kwargs=kwargs,
2732 )
2735_arch_file_conv = _ArchFileConv(_CallableFromFile_v0_4, ArchitectureFromFileDescr)
2738class _ArchLibConv(
2739 Converter[
2740 _CallableFromDepencency_v0_4, ArchitectureFromLibraryDescr, dict[str, Any]
2741 ]
2742):
2743 def _convert(
2744 self,
2745 src: _CallableFromDepencency_v0_4,
2746 tgt: type[ArchitectureFromLibraryDescr | dict[str, Any]],
2747 kwargs: dict[str, Any],
2748 ) -> ArchitectureFromLibraryDescr | dict[str, Any]:
2749 *mods, callable_ = src.split(".")
2750 import_from = ".".join(mods)
2751 return tgt(
2752 import_from=import_from, callable=Identifier(callable_), kwargs=kwargs
2753 )
2756_arch_lib_conv = _ArchLibConv(
2757 _CallableFromDepencency_v0_4, ArchitectureFromLibraryDescr
2758)
2761class WeightsEntryDescrBase(FileDescr):
2762 type: ClassVar[WeightsFormat]
2763 weights_format_name: ClassVar[str] # human readable
2765 source: Annotated[FileSource, AfterValidator(wo_special_file_name)]
2766 """Source of the weights file."""
2768 authors: list[Author] | None = None
2769 """Authors
2770 Either the person(s) that have trained this model resulting in the original weights file.
2771 (If this is the initial weights entry, i.e. it does not have a `parent`)
2772 Or the person(s) who have converted the weights to this weights format.
2773 (If this is a child weight, i.e. it has a `parent` field)
2774 """
2776 parent: Annotated[WeightsFormat | None, Field(examples=["pytorch_state_dict"])] = (
2777 None
2778 )
2779 """The source weights these weights were converted from.
2780 For example, if a model's weights were converted from the `pytorch_state_dict` format to `torchscript`,
2781 The `pytorch_state_dict` weights entry has no `parent` and is the parent of the `torchscript` weights.
2782 All weight entries except one (the initial set of weights resulting from training the model),
2783 need to have this field."""
2785 comment: str = ""
2786 """A comment about this weights entry, for example how these weights were created."""
2788 @model_validator(mode="after")
2789 def _validate(self) -> Self:
2790 if self.type == self.parent:
2791 raise ValueError("Weights entry can't be it's own parent.")
2793 return self
2795 @model_serializer(mode="wrap", when_used="unless-none")
2796 def _serialize(self, nxt: SerializerFunctionWrapHandler, info: SerializationInfo):
2797 return package_file_descr_serializer(self, nxt, info)
2800class KerasHdf5WeightsDescr(WeightsEntryDescrBase):
2801 type: ClassVar[WeightsFormat] = "keras_hdf5"
2802 weights_format_name: ClassVar[str] = "Keras HDF5"
2803 tensorflow_version: Version
2804 """TensorFlow version used to create these weights."""
2807class KerasV3WeightsDescr(WeightsEntryDescrBase):
2808 type: ClassVar[WeightsFormat] = "keras_v3"
2809 weights_format_name: ClassVar[str] = "Keras v3"
2810 keras_version: Annotated[Version, Ge(Version(3))]
2811 """Keras version used to create these weights."""
2812 backend: tuple[Literal["tensorflow", "jax", "torch"], Version]
2813 """Keras backend used to create these weights."""
2814 source: Annotated[
2815 FileSource,
2816 AfterValidator(wo_special_file_name),
2817 WithSuffix(".keras", case_sensitive=True),
2818 ]
2819 """Source of the .keras weights file."""
2822FileDescr_external_data = Annotated[
2823 FileDescr_package,
2824 WithSuffix(".data", case_sensitive=True),
2825 Field(examples=[{"source": "weights.onnx.data"}]),
2826]
2829class OnnxWeightsDescr(WeightsEntryDescrBase):
2830 type: ClassVar[WeightsFormat] = "onnx"
2831 weights_format_name: ClassVar[str] = "ONNX"
2832 opset_version: Annotated[int, Ge(7)]
2833 """ONNX opset version"""
2835 external_data: FileDescr_external_data | None = None
2836 """Source of the external ONNX data file holding the weights.
2837 (If present **source** holds the ONNX architecture without weights)."""
2839 @model_validator(mode="after")
2840 def _validate_external_data_unique_file_name(self) -> Self:
2841 if self.external_data is not None and (
2842 extract_file_name(self.source)
2843 == extract_file_name(self.external_data.source)
2844 ):
2845 raise ValueError(
2846 f"ONNX `external_data` file name '{extract_file_name(self.external_data.source)}'"
2847 + " must be different from ONNX `source` file name."
2848 )
2850 return self
2853class PytorchStateDictWeightsDescr(WeightsEntryDescrBase):
2854 type: ClassVar[WeightsFormat] = "pytorch_state_dict"
2855 weights_format_name: ClassVar[str] = "Pytorch State Dict"
2856 architecture: ArchitectureFromFileDescr | ArchitectureFromLibraryDescr
2857 pytorch_version: Version
2858 """Version of the PyTorch library used.
2859 If `architecture.depencencies` is specified it has to include pytorch and any version pinning has to be compatible.
2860 """
2861 dependencies: FileDescr_dependencies | None = None
2862 """Custom depencies beyond pytorch described in a Conda environment file.
2863 Allows to specify custom dependencies, see conda docs:
2864 - [Exporting an environment file across platforms](https://conda.io/projects/conda/en/latest/user-guide/tasks/manage-environments.html#exporting-an-environment-file-across-platforms)
2865 - [Creating an environment file manually](https://conda.io/projects/conda/en/latest/user-guide/tasks/manage-environments.html#creating-an-environment-file-manually)
2867 The conda environment file should include pytorch and any version pinning has to be compatible with
2868 **pytorch_version**.
2869 """
2870 strict: bool = True
2871 """Whether to allow missing or unexpected keys or to be strict about the architecture matching the state dict weights."""
2874class TensorflowJsWeightsDescr(WeightsEntryDescrBase):
2875 type: ClassVar[WeightsFormat] = "tensorflow_js"
2876 weights_format_name: ClassVar[str] = "Tensorflow.js"
2877 tensorflow_version: Version
2878 """Version of the TensorFlow library used."""
2880 source: Annotated[FileSource, AfterValidator(wo_special_file_name)]
2881 """The multi-file weights.
2882 All required files/folders should be a zip archive."""
2885class TensorflowSavedModelBundleWeightsDescr(WeightsEntryDescrBase):
2886 type: ClassVar[WeightsFormat] = "tensorflow_saved_model_bundle"
2887 weights_format_name: ClassVar[str] = "Tensorflow Saved Model"
2888 tensorflow_version: Version
2889 """Version of the TensorFlow library used."""
2891 dependencies: FileDescr_dependencies | None = None
2892 """Custom dependencies beyond tensorflow.
2893 Should include tensorflow and any version pinning has to be compatible with **tensorflow_version**."""
2895 source: Annotated[FileSource, AfterValidator(wo_special_file_name)]
2896 """The multi-file weights.
2897 All required files/folders should be a zip archive."""
2900class TorchscriptWeightsDescr(WeightsEntryDescrBase):
2901 type: ClassVar[WeightsFormat] = "torchscript"
2902 weights_format_name: ClassVar[str] = "TorchScript"
2903 pytorch_version: Version
2904 """Version of the PyTorch library used."""
2907SpecificWeightsDescr = (
2908 KerasHdf5WeightsDescr
2909 | KerasV3WeightsDescr
2910 | OnnxWeightsDescr
2911 | PytorchStateDictWeightsDescr
2912 | TensorflowJsWeightsDescr
2913 | TensorflowSavedModelBundleWeightsDescr
2914 | TorchscriptWeightsDescr
2915)
2918class WeightsDescr(Node):
2919 keras_hdf5: KerasHdf5WeightsDescr | None = None
2920 keras_v3: KerasV3WeightsDescr | None = None
2921 onnx: OnnxWeightsDescr | None = None
2922 pytorch_state_dict: PytorchStateDictWeightsDescr | None = None
2923 tensorflow_js: TensorflowJsWeightsDescr | None = None
2924 tensorflow_saved_model_bundle: TensorflowSavedModelBundleWeightsDescr | None = None
2925 torchscript: TorchscriptWeightsDescr | None = None
2927 @model_validator(mode="after")
2928 def check_entries(self) -> Self:
2929 entries = {wtype for wtype, entry in self if entry is not None}
2931 if not entries:
2932 raise ValueError("Missing weights entry")
2934 entries_wo_parent = {
2935 wtype
2936 for wtype, entry in self
2937 if entry is not None and hasattr(entry, "parent") and entry.parent is None
2938 }
2939 if len(entries_wo_parent) != 1:
2940 issue_warning(
2941 "Exactly one weights entry may not specify the `parent` field (got"
2942 + " {value}). That entry is considered the original set of model weights."
2943 + " Other weight formats are created through conversion of the orignal or"
2944 + " already converted weights. They have to reference the weights format"
2945 + " they were converted from as their `parent`.",
2946 value=len(entries_wo_parent),
2947 field="weights",
2948 )
2950 for wtype, entry in self:
2951 if entry is None:
2952 continue
2954 assert hasattr(entry, "type")
2955 assert hasattr(entry, "parent")
2956 assert wtype == entry.type
2957 if (
2958 entry.parent is not None and entry.parent not in entries
2959 ): # self reference checked for `parent` field
2960 raise ValueError(
2961 f"`weights.{wtype}.parent={entry.parent} not in specified weight"
2962 + f" formats: {entries}"
2963 )
2965 return self
2967 def __getitem__(
2968 self,
2969 key: WeightsFormat,
2970 ):
2971 if key == "keras_hdf5":
2972 ret = self.keras_hdf5
2973 elif key == "keras_v3":
2974 ret = self.keras_v3
2975 elif key == "onnx":
2976 ret = self.onnx
2977 elif key == "pytorch_state_dict":
2978 ret = self.pytorch_state_dict
2979 elif key == "tensorflow_js":
2980 ret = self.tensorflow_js
2981 elif key == "tensorflow_saved_model_bundle":
2982 ret = self.tensorflow_saved_model_bundle
2983 elif key == "torchscript":
2984 ret = self.torchscript
2985 else:
2986 raise KeyError(key)
2988 if ret is None:
2989 raise KeyError(key)
2991 return ret
2993 @overload
2994 def __setitem__(
2995 self, key: Literal["keras_hdf5"], value: KerasHdf5WeightsDescr | None
2996 ) -> None: ...
2997 @overload
2998 def __setitem__(
2999 self, key: Literal["keras_v3"], value: KerasV3WeightsDescr | None
3000 ) -> None: ...
3001 @overload
3002 def __setitem__(
3003 self, key: Literal["onnx"], value: OnnxWeightsDescr | None
3004 ) -> None: ...
3005 @overload
3006 def __setitem__(
3007 self,
3008 key: Literal["pytorch_state_dict"],
3009 value: PytorchStateDictWeightsDescr | None,
3010 ) -> None: ...
3011 @overload
3012 def __setitem__(
3013 self, key: Literal["tensorflow_js"], value: TensorflowJsWeightsDescr | None
3014 ) -> None: ...
3015 @overload
3016 def __setitem__(
3017 self,
3018 key: Literal["tensorflow_saved_model_bundle"],
3019 value: TensorflowSavedModelBundleWeightsDescr | None,
3020 ) -> None: ...
3021 @overload
3022 def __setitem__(
3023 self, key: Literal["torchscript"], value: TorchscriptWeightsDescr | None
3024 ) -> None: ...
3026 def __setitem__(
3027 self,
3028 key: WeightsFormat,
3029 value: SpecificWeightsDescr | None,
3030 ):
3031 if key == "keras_hdf5":
3032 if value is not None and not isinstance(value, KerasHdf5WeightsDescr):
3033 raise TypeError(
3034 f"Expected KerasHdf5WeightsDescr or None for key 'keras_hdf5', got {type(value)}"
3035 )
3036 self.keras_hdf5 = value
3037 elif key == "keras_v3":
3038 if value is not None and not isinstance(value, KerasV3WeightsDescr):
3039 raise TypeError(
3040 f"Expected KerasV3WeightsDescr or None for key 'keras_v3', got {type(value)}"
3041 )
3042 self.keras_v3 = value
3043 elif key == "onnx":
3044 if value is not None and not isinstance(value, OnnxWeightsDescr):
3045 raise TypeError(
3046 f"Expected OnnxWeightsDescr or None for key 'onnx', got {type(value)}"
3047 )
3048 self.onnx = value
3049 elif key == "pytorch_state_dict":
3050 if value is not None and not isinstance(
3051 value, PytorchStateDictWeightsDescr
3052 ):
3053 raise TypeError(
3054 f"Expected PytorchStateDictWeightsDescr or None for key 'pytorch_state_dict', got {type(value)}"
3055 )
3056 self.pytorch_state_dict = value
3057 elif key == "tensorflow_js":
3058 if value is not None and not isinstance(value, TensorflowJsWeightsDescr):
3059 raise TypeError(
3060 f"Expected TensorflowJsWeightsDescr or None for key 'tensorflow_js', got {type(value)}"
3061 )
3062 self.tensorflow_js = value
3063 elif key == "tensorflow_saved_model_bundle":
3064 if value is not None and not isinstance(
3065 value, TensorflowSavedModelBundleWeightsDescr
3066 ):
3067 raise TypeError(
3068 f"Expected TensorflowSavedModelBundleWeightsDescr or None for key 'tensorflow_saved_model_bundle', got {type(value)}"
3069 )
3070 self.tensorflow_saved_model_bundle = value
3071 elif key == "torchscript":
3072 if value is not None and not isinstance(value, TorchscriptWeightsDescr):
3073 raise TypeError(
3074 f"Expected TorchscriptWeightsDescr or None for key 'torchscript', got {type(value)}"
3075 )
3076 self.torchscript = value
3077 else:
3078 raise KeyError(key)
3080 @property
3081 def available_formats(self) -> dict[WeightsFormat, SpecificWeightsDescr]:
3082 return {
3083 **({} if self.keras_hdf5 is None else {"keras_hdf5": self.keras_hdf5}),
3084 **({} if self.keras_v3 is None else {"keras_v3": self.keras_v3}),
3085 **({} if self.onnx is None else {"onnx": self.onnx}),
3086 **(
3087 {}
3088 if self.pytorch_state_dict is None
3089 else {"pytorch_state_dict": self.pytorch_state_dict}
3090 ),
3091 **(
3092 {}
3093 if self.tensorflow_js is None
3094 else {"tensorflow_js": self.tensorflow_js}
3095 ),
3096 **(
3097 {}
3098 if self.tensorflow_saved_model_bundle is None
3099 else {
3100 "tensorflow_saved_model_bundle": self.tensorflow_saved_model_bundle
3101 }
3102 ),
3103 **({} if self.torchscript is None else {"torchscript": self.torchscript}),
3104 }
3106 @property
3107 def missing_formats(self) -> set[WeightsFormat]:
3108 return {
3109 wf for wf in get_args(WeightsFormat) if wf not in self.available_formats
3110 }
3113class LinkedModel(LinkedResourceBase):
3114 """Reference to a bioimage.io model."""
3116 id: ModelId
3117 """A valid model `id` from the bioimage.io collection."""
3120class _DataDepSize(NamedTuple):
3121 min: StrictInt
3122 max: StrictInt | None
3125class _AxisSizes(NamedTuple):
3126 """the lenghts of all axes of model inputs and outputs"""
3128 inputs: dict[tuple[TensorId, AxisId], int]
3129 outputs: dict[tuple[TensorId, AxisId], int | _DataDepSize]
3132class _TensorSizes(NamedTuple):
3133 """_AxisSizes as nested dicts"""
3135 inputs: dict[TensorId, dict[AxisId, int]]
3136 outputs: dict[TensorId, dict[AxisId, int | _DataDepSize]]
3139_RT = TypeVar("_RT", RelativeTolerance, Literal[0])
3140_AT = TypeVar("_AT", AbsoluteTolerance, Literal[0])
3143class _ReproducibilityToleranceBase(Node, ABC, Generic[_RT, _AT], extra="allow"):
3144 """Describes what small numerical differences -- if any -- may be tolerated
3145 in the generated output when executing in different environments.
3147 A tensor element *output* is considered mismatched to the **test_tensor** if
3148 abs(*output* - **test_tensor**) > **absolute_tolerance** + **relative_tolerance** * abs(**test_tensor**).
3149 (Internally we call [numpy.testing.assert_allclose](https://numpy.org/doc/stable/reference/generated/numpy.testing.assert_allclose.html).)
3151 Motivation:
3152 For testing we can request the respective deep learning frameworks to be as
3153 reproducible as possible by setting seeds and chosing deterministic algorithms,
3154 but differences in operating systems, available hardware and installed drivers
3155 may still lead to numerical differences.
3156 """
3158 mismatched_elements_per_million: MismatchedElementsPerMillion = 100
3159 """Maximum number of mismatched elements/pixels per million to tolerate."""
3161 weights_formats: Sequence[WeightsFormat] = ()
3162 """Limits the weights formats these details apply to."""
3164 relative_tolerance: _RT
3165 absolute_tolerance: _AT
3167 @model_serializer(mode="wrap")
3168 def serialize(
3169 self,
3170 handler: SerializerFunctionWrapHandler,
3171 ) -> dict[str, Any]:
3172 """explicitly serialize tolerance values
3174 (even if they are default values and `exclude_defaults=True`).
3175 """
3176 data = handler(self)
3177 data["relative_tolerance"] = self.relative_tolerance
3178 data["absolute_tolerance"] = self.absolute_tolerance
3179 data["mismatched_elements_per_million"] = self.mismatched_elements_per_million
3180 return data
3183class ReproducibilityTolerance(
3184 _ReproducibilityToleranceBase[RelativeTolerance, AbsoluteTolerance]
3185):
3186 output_ids: Sequence[TensorId] = ()
3187 """Limits the output tensor IDs these reproducibility details apply to.
3189 If empty, the reproducibility details apply to all outputs."""
3191 relative_tolerance: RelativeTolerance = 1e-3
3192 """Maximum relative tolerance of reproduced test tensor.
3193 Needs to be 0 for discrete (integer and boolean) outputs.
3194 """
3196 absolute_tolerance: AbsoluteTolerance = 1e-3
3197 """Maximum absolute tolerance of reproduced test tensor.
3199 The `absolute_tolerance` may not be greater than 1% of the maximum absolute value of the test tensor
3200 (this serves to prevent false positives in the presence of very small numbers).
3201 Needs to be 0 for discrete (integer and boolean) outputs.
3202 """
3205class DiscreteReproducibilityTolerance(
3206 _ReproducibilityToleranceBase[Literal[0], Literal[0]]
3207):
3208 output_ids: Literal["any_discrete_output"] = "any_discrete_output"
3209 """Limits the output tensor IDs to all outputs of integer or boolean data type."""
3211 relative_tolerance: Literal[0] = 0
3212 """Relative tolerance does not apply to discrete outputs"""
3214 absolute_tolerance: Literal[0] = 0
3215 """Absolute tolerance does not apply to discrete outputs"""
3217 mismatched_elements_per_million: MismatchedElementsPerMillion = 1000
3218 """Maximum number of mismatched elements/pixels per million to tolerate.
3220 Note: Increased default mismatched elements per million compared to
3221 [`ReproducibilityTolerance`][ReproducibilityTolerance]/[`ContinuousReproducibilityTolerance`][ContinuousReproducibilityTolerance],
3222 since a single pixel mismatch can be more significant than for continuous outputs with numeric tolerance."""
3225class ContinuousReproducibilityTolerance(
3226 _ReproducibilityToleranceBase[RelativeTolerance, AbsoluteTolerance]
3227):
3228 output_ids: Literal["any_continuous_output"] = "any_continuous_output"
3229 """Limits the output tensor IDs to all outputs of float data type."""
3231 relative_tolerance: RelativeTolerance = 1e-3
3232 """Maximum relative tolerance of reproduced test tensor.
3233 Needs to be 0 for discrete (integer and boolean) outputs.
3234 """
3236 absolute_tolerance: AbsoluteTolerance = 1e-3
3237 """Maximum absolute tolerance of reproduced test tensor.
3239 The `absolute_tolerance` may not be greater than 1% of the maximum absolute value of the test tensor
3240 (this serves to prevent false positives in the presence of very small numbers).
3241 Needs to be 0 for discrete (integer and boolean) outputs.
3242 """
3245class BiasRisksLimitations(Node, extra="allow"):
3246 """Known biases, risks, technical limitations, and recommendations for model use."""
3248 known_biases: str = dedent("""\
3249 In general bioimage models may suffer from biases caused by:
3251 - Imaging protocol dependencies
3252 - Use of a specific cell type
3253 - Species-specific training data limitations
3255 """)
3256 """Biases in training data or model behavior."""
3258 risks: str = dedent("""\
3259 Common risks in bioimage analysis include:
3261 - Erroneously assuming generalization to unseen experimental conditions
3262 - Trusting (overconfident) model outputs without validation
3263 - Misinterpretation of results
3265 """)
3266 """Potential risks in the context of bioimage analysis."""
3268 limitations: str | None = None
3269 """Technical limitations and failure modes."""
3271 recommendations: str = "Users (both direct and downstream) should be made aware of the risks, biases and limitations of the model."
3272 """Mitigation strategies regarding `known_biases`, `risks`, and `limitations`, as well as applicable best practices.
3274 Consider:
3275 - How to use a validation dataset?
3276 - How to manually validate?
3277 - Feasibility of domain adaptation for different experimental setups?
3279 """
3281 def format_md(self) -> str:
3282 if self.limitations is None:
3283 limitations_header = ""
3284 else:
3285 limitations_header = "## Limitations\n\n"
3287 return f"""# Bias, Risks, and Limitations
3289{self.known_biases}
3291{self.risks}
3293{limitations_header}{self.limitations or ""}
3295## Recommendations
3297{self.recommendations}
3299"""
3302class TrainingDetails(Node, extra="allow"):
3303 training_preprocessing: str | None = None
3304 """Detailed image preprocessing steps during model training:
3306 Mention:
3307 - *Normalization methods*
3308 - *Augmentation strategies*
3309 - *Resizing/resampling procedures*
3310 - *Artifact handling*
3312 """
3314 training_epochs: float | None = None
3315 """Number of training epochs."""
3317 training_batch_size: float | None = None
3318 """Batch size used in training."""
3320 initial_learning_rate: float | None = None
3321 """Initial learning rate used in training."""
3323 learning_rate_schedule: str | None = None
3324 """Learning rate schedule used in training."""
3326 loss_function: str | None = None
3327 """Loss function used in training, e.g. nn.MSELoss."""
3329 loss_function_kwargs: dict[str, YamlValue] = Field(
3330 default_factory=cast(Callable[[], dict[str, YamlValue]], dict)
3331 )
3332 """key word arguments for the `loss_function`"""
3334 optimizer: str | None = None
3335 """optimizer, e.g. torch.optim.Adam"""
3337 optimizer_kwargs: dict[str, YamlValue] = Field(
3338 default_factory=cast(Callable[[], dict[str, YamlValue]], dict)
3339 )
3340 """key word arguments for the `optimizer`"""
3342 regularization: str | None = None
3343 """Regularization techniques used during training, e.g. drop-out or weight decay."""
3345 training_duration: float | None = None
3346 """Total training duration in hours."""
3349class Evaluation(Node, extra="allow"):
3350 model_id: ModelId | None = None
3351 """Model being evaluated."""
3353 dataset_id: DatasetId
3354 """Dataset used for evaluation."""
3356 dataset_source: HttpUrl
3357 """Source of the dataset."""
3359 dataset_role: Literal["train", "validation", "test", "independent", "unknown"]
3360 """Role of the dataset used for evaluation.
3362 - `train`: dataset was (part of) the training data
3363 - `validation`: dataset was (part of) the validation data used during training, e.g. used for model selection or hyperparameter tuning
3364 - `test`: dataset was (part of) the designated test data; not used during training or validation, but acquired from the same source/distribution as training data
3365 - `independent`: dataset is entirely independent test data; not used during training or validation, and acquired from a different source/distribution than training data
3366 - `unknown`: role of the dataset is unknown; choose this if you are not certain if (a subset) of the data was seen by the model during training.
3367 """
3369 sample_count: int
3370 """Number of evaluated samples."""
3372 evaluation_factors: list[Annotated[str, MaxLen(16)]]
3373 """(Abbreviations of) each evaluation factor.
3375 Evaluation factors are criteria along which model performance is evaluated, e.g. different image conditions
3376 like 'low SNR', 'high cell density', or different biological conditions like 'cell type A', 'cell type B'.
3377 An 'overall' factor may be included to summarize performance across all conditions.
3378 """
3380 evaluation_factors_long: list[str]
3381 """Descriptions (long form) of each evaluation factor."""
3383 metrics: list[Annotated[str, MaxLen(16)]]
3384 """(Abbreviations of) metrics used for evaluation."""
3386 metrics_long: list[str]
3387 """Description of each metric used."""
3389 @model_validator(mode="after")
3390 def _validate_list_lengths(self) -> Self:
3391 if len(self.evaluation_factors) != len(self.evaluation_factors_long):
3392 raise ValueError(
3393 "`evaluation_factors` and `evaluation_factors_long` must have the same length"
3394 )
3396 if len(self.metrics) != len(self.metrics_long):
3397 raise ValueError("`metrics` and `metrics_long` must have the same length")
3399 if len(self.results) != len(self.metrics):
3400 raise ValueError("`results` must have the same number of rows as `metrics`")
3402 for row in self.results:
3403 if len(row) != len(self.evaluation_factors):
3404 raise ValueError(
3405 "`results` must have the same number of columns (in every row) as `evaluation_factors`"
3406 )
3408 return self
3410 results: list[list[str | float | int]]
3411 """Results for each metric (rows; outer list) and each evaluation factor (columns; inner list)."""
3413 results_summary: str | None = None
3414 """Interpretation of results for general audience.
3416 Consider:
3417 - Overall model performance
3418 - Comparison to existing methods
3419 - Limitations and areas for improvement
3421"""
3423 def format_md(self):
3424 results_header = ["Metric"] + self.evaluation_factors
3425 results_table_cells = [results_header, ["---"] * len(results_header)] + [
3426 [metric] + [str(r) for r in row]
3427 for metric, row in zip(self.metrics, self.results)
3428 ]
3430 results_table = "".join(
3431 "| " + " | ".join(row) + " |\n" for row in results_table_cells
3432 )
3433 factors = "".join(
3434 f"\n - {ef}: {efl}"
3435 for ef, efl in zip(self.evaluation_factors, self.evaluation_factors_long)
3436 )
3437 metrics = "".join(
3438 f"\n - {em}: {eml}" for em, eml in zip(self.metrics, self.metrics_long)
3439 )
3441 return f"""## Testing Data, Factors & Metrics
3443Evaluation of {self.model_id or "this"} model on the {self.dataset_id} dataset (dataset role: {self.dataset_role}).
3445### Testing Data
3447- **Source:** [{self.dataset_id}]({self.dataset_source})
3448- **Size:** {self.sample_count} evaluated samples
3450### Factors
3451{factors}
3453### Metrics
3454{metrics}
3456## Results
3458### Quantitative Results
3460{results_table}
3462### Summary
3464{self.results_summary or "missing"}
3466"""
3469class EnvironmentalImpact(Node, extra="allow"):
3470 """Environmental considerations for model training and deployment.
3472 Carbon emissions can be estimated using the [Machine Learning Impact calculator](https://mlco2.github.io/impact#compute) presented in [Lacoste et al. (2019)](https://arxiv.org/abs/1910.09700).
3473 """
3475 hardware_type: str | None = None
3476 """GPU/CPU specifications"""
3478 hours_used: float | None = None
3479 """Total compute hours"""
3481 cloud_provider: str | None = None
3482 """If applicable"""
3484 compute_region: str | None = None
3485 """Geographic location"""
3487 co2_emitted: float | None = None
3488 """kg CO2 equivalent
3490 Carbon emissions can be estimated using the [Machine Learning Impact calculator](https://mlco2.github.io/impact#compute) presented in [Lacoste et al. (2019)](https://arxiv.org/abs/1910.09700).
3491 """
3493 def format_md(self):
3494 """Filled Markdown template section following [Hugging Face Model Card Template](https://huggingface.co/docs/hub/en/model-card-annotated)."""
3495 if self == self.__class__():
3496 return ""
3498 ret = "# Environmental Impact\n\n"
3499 if self.hardware_type is not None:
3500 ret += f"- **Hardware Type:** {self.hardware_type}\n"
3501 if self.hours_used is not None:
3502 ret += f"- **Hours used:** {self.hours_used}\n"
3503 if self.cloud_provider is not None:
3504 ret += f"- **Cloud Provider:** {self.cloud_provider}\n"
3505 if self.compute_region is not None:
3506 ret += f"- **Compute Region:** {self.compute_region}\n"
3507 if self.co2_emitted is not None:
3508 ret += f"- **Carbon Emitted:** {self.co2_emitted} kg CO2e\n"
3510 return ret + "\n"
3513class BioimageioConfig(Node, extra="allow"):
3514 reproducibility_tolerance: Sequence[
3515 ReproducibilityTolerance
3516 | ContinuousReproducibilityTolerance
3517 | DiscreteReproducibilityTolerance
3518 ] = Field(
3519 default_factory=lambda: (
3520 ContinuousReproducibilityTolerance.model_construct(),
3521 DiscreteReproducibilityTolerance.model_construct(),
3522 )
3523 )
3524 """Tolerances to allow when reproducing the model's test outputs
3525 from the model's test inputs.
3526 Only the first entry matching tensor id and weights format is considered.
3527 For defaults see [`ContinuousReproducibilityTolerance`][ContinuousReproducibilityTolerance]/[`DiscreteReproducibilityTolerance`][DiscreteReproducibilityTolerance]
3528 """
3530 @model_serializer(mode="wrap")
3531 def _serialize(
3532 self,
3533 handler: SerializerFunctionWrapHandler,
3534 ) -> dict[str, Any]:
3535 """explicitly serialize reproducibility_tolerance
3537 (even if they are default values and `exclude_defaults=True`).
3538 """
3539 data = handler(self)
3540 data["reproducibility_tolerance"] = self.reproducibility_tolerance
3541 return data
3543 funded_by: str | None = None
3544 """Funding agency, grant number if applicable"""
3546 architecture_type: Annotated[str, MaxLen(32)] | None = (
3547 None # TODO: add to differentiated tags
3548 )
3549 """Model architecture type, e.g., 3D U-Net, ResNet, transformer"""
3551 architecture_description: str | None = None
3552 """Text description of model architecture."""
3554 modality: str | None = None # TODO: add to differentiated tags
3555 """Input modality, e.g., fluorescence microscopy, electron microscopy"""
3557 target_structure: list[str] = Field( # TODO: add to differentiated tags
3558 default_factory=cast(Callable[[], list[str]], list)
3559 )
3560 """Biological structure(s) the model is designed to analyze, e.g., nuclei, mitochondria, cells"""
3562 task: str | None = None # TODO: add to differentiated tags
3563 """Bioimage-specific task type, e.g., segmentation, classification, detection, denoising"""
3565 new_version: ModelId | None = None
3566 """A new version of this model exists with a different model id."""
3568 out_of_scope_use: str | None = None
3569 """Describe how the model may be misused in bioimage analysis contexts and what users should **not** do with the model."""
3571 bias_risks_limitations: BiasRisksLimitations = Field(
3572 default_factory=BiasRisksLimitations.model_construct
3573 )
3574 """Description of known bias, risks, and technical limitations for in-scope model use."""
3576 model_parameter_count: int | None = None
3577 """Total number of model parameters."""
3579 training: TrainingDetails = Field(default_factory=TrainingDetails.model_construct)
3580 """Details on how the model was trained."""
3582 inference_time: str | None = None
3583 """Average inference time per image/tile. Specify hardware and image size. Multiple examples can be given."""
3585 memory_requirements_inference: str | None = None
3586 """GPU memory needed for inference. Multiple examples with different image size can be given."""
3588 memory_requirements_training: str | None = None
3589 """GPU memory needed for training. Multiple examples with different image/batch sizes can be given."""
3591 evaluations: list[Evaluation] = Field(
3592 default_factory=cast(Callable[[], list[Evaluation]], list)
3593 )
3594 """Quantitative model evaluations.
3596 Note:
3597 At the moment we recommend to include only a single test dataset
3598 (with evaluation factors that may mark subsets of the dataset)
3599 to avoid confusion and make the presentation of results cleaner.
3600 """
3602 environmental_impact: EnvironmentalImpact = Field(
3603 default_factory=EnvironmentalImpact.model_construct
3604 )
3605 """Environmental considerations for model training and deployment"""
3608class Config(Node, extra="allow"):
3609 bioimageio: BioimageioConfig = Field(
3610 default_factory=BioimageioConfig.model_construct
3611 )
3612 stardist: YamlValue = None
3615class ModelDescr(GenericModelDescrBase):
3616 """Specification of the fields used in a bioimage.io-compliant RDF to describe AI models with pretrained weights.
3617 These fields are typically stored in a YAML file which we call a model resource description file (model RDF).
3618 """
3620 implemented_format_version: ClassVar[Literal["0.5.15"]] = "0.5.15"
3621 if TYPE_CHECKING:
3622 format_version: Literal["0.5.15"] = "0.5.15"
3623 else:
3624 format_version: Literal["0.5.15"]
3625 """Version of the bioimage.io model description specification used.
3626 When creating a new model always use the latest micro/patch version described here.
3627 The `format_version` is important for any consumer software to understand how to parse the fields.
3628 """
3630 implemented_type: ClassVar[Literal["model"]] = "model"
3631 if TYPE_CHECKING:
3632 type: Literal["model"] = "model"
3633 else:
3634 type: Literal["model"]
3635 """Specialized resource type 'model'"""
3637 id: ModelId | None = None
3638 """bioimage.io-wide unique resource identifier
3639 assigned by bioimage.io; version **un**specific."""
3641 authors: FAIR[list[Author]] = Field(
3642 default_factory=cast(Callable[[], list[Author]], list)
3643 )
3644 """The authors are the creators of the model RDF and the primary points of contact."""
3646 documentation: FAIR[FileDescr_documentation | None] = None
3647 """Additional model documentation.
3648 The recommended documentation source file name is `README.md`. An `.md` suffix is mandatory.
3649 The documentation should include a '#[#] Validation' (sub)section
3650 with details on how to quantitatively validate the model on unseen data."""
3652 @field_validator("documentation", mode="after")
3653 @classmethod
3654 def _validate_documentation(cls, value: FileDescr | None) -> FileDescr | None:
3655 if not get_validation_context().perform_io_checks or value is None:
3656 return value
3658 doc_reader = get_reader(value)
3659 doc_content = doc_reader.read().decode(encoding="utf-8")
3660 if not re.search("#.*[vV]alidation", doc_content):
3661 issue_warning(
3662 "No '# Validation' (sub)section found in {value}.",
3663 value=value,
3664 field="documentation",
3665 )
3667 return value
3669 inputs: NotEmpty[Sequence[InputTensorDescr]]
3670 """Describes the input tensors expected by this model."""
3672 @field_validator("inputs", mode="after")
3673 @classmethod
3674 def _validate_input_axes(
3675 cls, inputs: Sequence[InputTensorDescr]
3676 ) -> Sequence[InputTensorDescr]:
3677 input_size_refs = cls._get_axes_with_independent_size(inputs)
3679 for i, ipt in enumerate(inputs):
3680 valid_independent_refs: dict[
3681 tuple[TensorId, AxisId],
3682 tuple[TensorDescr, AnyAxis, int | ParameterizedSize],
3683 ] = {
3684 **{
3685 (ipt.id, a.id): (ipt, a, a.size)
3686 for a in ipt.axes
3687 if not isinstance(a, BatchAxis)
3688 and isinstance(a.size, (int, ParameterizedSize))
3689 },
3690 **input_size_refs,
3691 }
3692 for a, ax in enumerate(ipt.axes):
3693 cls._validate_axis(
3694 "inputs",
3695 i=i,
3696 tensor_id=ipt.id,
3697 a=a,
3698 axis=ax,
3699 valid_independent_refs=valid_independent_refs,
3700 )
3701 return inputs
3703 @staticmethod
3704 def _validate_axis(
3705 field_name: str,
3706 i: int,
3707 tensor_id: TensorId,
3708 a: int,
3709 axis: AnyAxis,
3710 valid_independent_refs: dict[
3711 tuple[TensorId, AxisId],
3712 tuple[TensorDescr, AnyAxis, int | ParameterizedSize],
3713 ],
3714 ):
3715 if isinstance(axis, BatchAxis) or isinstance(
3716 axis.size, (int, ParameterizedSize, DataDependentSize)
3717 ):
3718 return
3719 elif not isinstance(axis.size, SizeReference):
3720 assert_never(axis.size)
3722 # validate axis.size SizeReference
3723 ref = (axis.size.tensor_id, axis.size.axis_id)
3724 if ref not in valid_independent_refs:
3725 raise ValueError(
3726 "Invalid tensor axis reference at"
3727 + f" {field_name}[{i}].axes[{a}].size: {axis.size}."
3728 )
3729 if ref == (tensor_id, axis.id):
3730 raise ValueError(
3731 "Self-referencing not allowed for"
3732 + f" {field_name}[{i}].axes[{a}].size: {axis.size}"
3733 )
3734 if axis.type == "channel":
3735 if valid_independent_refs[ref][1].type != "channel":
3736 raise ValueError(
3737 "A channel axis' size may only reference another fixed size"
3738 + " channel axis."
3739 )
3740 if isinstance(axis.channel_names, str) and "{i}" in axis.channel_names:
3741 ref_size = valid_independent_refs[ref][2]
3742 assert isinstance(ref_size, int), (
3743 "channel axis ref (another channel axis) has to specify fixed"
3744 + " size"
3745 )
3746 generated_channel_names = [
3747 axis.channel_names.format(i=i) for i in range(1, ref_size + 1)
3748 ]
3749 axis.channel_names = generated_channel_names
3751 if (ax_unit := getattr(axis, "unit", None)) != (
3752 ref_unit := getattr(valid_independent_refs[ref][1], "unit", None)
3753 ):
3754 raise ValueError(
3755 "The units of an axis and its reference axis need to match, but"
3756 + f" '{ax_unit}' != '{ref_unit}'."
3757 )
3758 ref_axis = valid_independent_refs[ref][1]
3759 if isinstance(ref_axis, BatchAxis):
3760 raise ValueError(
3761 f"Invalid reference axis '{ref_axis.id}' for {tensor_id}.{axis.id}"
3762 + " (a batch axis is not allowed as reference)."
3763 )
3765 if isinstance(axis, WithHalo):
3766 min_size = axis.size.get_size(axis, ref_axis, n=0)
3767 if (min_size - 2 * axis.halo) < 1:
3768 raise ValueError(
3769 f"axis {axis.id} with minimum size {min_size} is too small for halo"
3770 + f" {axis.halo}."
3771 )
3773 ref_halo = axis.halo * axis.scale / ref_axis.scale
3774 if ref_halo != int(ref_halo):
3775 raise ValueError(
3776 f"Inferred halo for {'.'.join(ref)} is not an integer ({ref_halo} ="
3777 + f" {tensor_id}.{axis.id}.halo {axis.halo}"
3778 + f" * {tensor_id}.{axis.id}.scale {axis.scale}"
3779 + f" / {'.'.join(ref)}.scale {ref_axis.scale})."
3780 )
3782 def validate_input_tensors(
3783 self,
3784 sources: Sequence[NDArray[Any]] | Mapping[TensorId, NDArray[Any] | None],
3785 *,
3786 pad_inputs: bool | Literal["allow"] = True,
3787 crop_outputs: bool | Literal["allow"] = True,
3788 ) -> Mapping[TensorId, NDArray[Any] | None]:
3789 """Check if the given input tensors match the model's input tensor descriptions.
3790 This includes checks of tensor shapes and dtypes, but not of the actual values.
3791 """
3792 if not isinstance(sources, collections.abc.Mapping):
3793 sources = {descr.id: tensor for descr, tensor in zip(self.inputs, sources)}
3795 tensors = {
3796 **{descr.id: (descr, sources.get(descr.id)) for descr in self.inputs},
3797 **{ # outputs are required for halo
3798 descr.id: (descr, None) for descr in self.outputs
3799 },
3800 }
3801 validate_tensors(tensors, pad_inputs=pad_inputs, crop_outputs=crop_outputs)
3803 return sources
3805 @model_validator(mode="after")
3806 def _validate_test_tensors(self) -> Self:
3807 if not get_validation_context().perform_io_checks:
3808 return self
3810 test_inputs = {
3811 descr.id: (
3812 descr,
3813 None if descr.test_tensor is None else load_array(descr.test_tensor),
3814 )
3815 for descr in self.inputs
3816 }
3817 test_outputs = {
3818 descr.id: (
3819 descr,
3820 None if descr.test_tensor is None else load_array(descr.test_tensor),
3821 )
3822 for descr in self.outputs
3823 }
3825 validate_tensors(
3826 {**test_inputs, **test_outputs},
3827 tensor_origin="test_tensor",
3828 pad_inputs="allow",
3829 crop_outputs="allow",
3830 )
3832 for descr, array in test_inputs.values():
3833 if array is None:
3834 continue
3836 axis_sizes = descr.get_axis_sizes_for_array(array)
3837 for axis in descr.axes:
3838 if (
3839 axis.concatenable == "reproducible"
3840 and isinstance(axis.size, ParameterizedSize)
3841 and axis_sizes[axis.id] <= axis.size.min
3842 ):
3843 raise ValueError(
3844 f"inputs[{descr.id}].axes[{axis.id}]: test_tensor axis size "
3845 + f"{axis_sizes[axis.id]} must be larger than minimum size "
3846 + f"{axis.size.min} for concatenable='reproducible'"
3847 )
3849 seen_output_ids: set[TensorId] = (
3850 set()
3851 ) # reproducibility tolerance is only applicable to the first matching output tensor id
3852 for rep_tol in self.config.bioimageio.reproducibility_tolerance:
3853 if not rep_tol.output_ids:
3854 out_arrays: dict[TensorId, NDArray[Any] | None] = {
3855 k: v[1] for k, v in test_outputs.items() if k not in seen_output_ids
3856 }
3857 else:
3858 out_arrays = {}
3859 for k, v in test_outputs.items():
3860 if k in seen_output_ids:
3861 continue
3863 if rep_tol.output_ids == "any_discrete_output":
3864 if not (
3865 v[0].dtype.startswith("int")
3866 or v[0].dtype.startswith("uint")
3867 or v[0].dtype.startswith("bool")
3868 ):
3869 continue
3870 elif rep_tol.output_ids == "any_continuous_output":
3871 if not v[0].dtype.startswith("float"):
3872 continue
3873 elif k not in rep_tol.output_ids:
3874 continue
3876 out_arrays[k] = v[1]
3878 for out_id, array in out_arrays.items():
3879 seen_output_ids.add(out_id)
3880 if array is None:
3881 continue
3883 if rep_tol.absolute_tolerance > (max_test_value := array.max()) * 0.01:
3884 raise ValueError(
3885 "config.bioimageio.reproducibility_tolerance.absolute_tolerance="
3886 + f"{rep_tol.absolute_tolerance} > 0.01*{max_test_value}"
3887 + f" (1% of the maximum value of the test tensor '{out_id}')"
3888 )
3890 return self
3892 @model_validator(mode="after")
3893 def _validate_tensor_references_in_proc_kwargs(self, info: ValidationInfo) -> Self:
3894 ipt_refs = {t.id for t in self.inputs}
3895 missing_refs = [
3896 k["reference_tensor"]
3897 for k in [p.kwargs for ipt in self.inputs for p in ipt.preprocessing]
3898 + [p.kwargs for out in self.outputs for p in out.postprocessing]
3899 if "reference_tensor" in k
3900 and k["reference_tensor"] is not None
3901 and k["reference_tensor"] not in ipt_refs
3902 ]
3904 if missing_refs:
3905 raise ValueError(
3906 f"`reference_tensor`s {missing_refs} not found. Valid input tensor"
3907 + f" references are: {ipt_refs}."
3908 )
3910 return self
3912 name: Annotated[
3913 str,
3914 RestrictCharacters(string.ascii_letters + string.digits + "_+- ()"),
3915 MinLen(5),
3916 MaxLen(128),
3917 warn(Annotated[str, MaxLen(64)], "Name longer than 64 characters.", INFO),
3918 ]
3919 """A human-readable name of this model.
3920 It should be no longer than 64 characters
3921 and may only contain letter, number, underscore, minus, parentheses and spaces.
3922 We recommend to chose a name that refers to the model's task and image modality.
3923 """
3925 outputs: NotEmpty[Sequence[OutputTensorDescr]]
3926 """Describes the output tensors."""
3928 @model_validator(mode="after")
3929 def _validate_concatenable_input_axes(self) -> Self:
3930 output_refs = {
3931 (axis.size.tensor_id, axis.size.axis_id)
3932 for output in self.outputs
3933 for axis in output.axes
3934 if isinstance(axis.size, SizeReference)
3935 }
3936 has_output_batch = any(
3937 isinstance(axis, BatchAxis)
3938 for output in self.outputs
3939 for axis in output.axes
3940 )
3941 missing = [
3942 f"{input_tensor.id}.{axis.id}"
3943 for input_tensor in self.inputs
3944 for axis in input_tensor.axes
3945 if axis.concatenable
3946 and (
3947 not has_output_batch
3948 if isinstance(axis, BatchAxis)
3949 else (input_tensor.id, axis.id) not in output_refs
3950 )
3951 ]
3952 if missing:
3953 raise ValueError(
3954 f"Concatenable input axes must be referenced by an output axis size: {missing}."
3955 + " Either set `concatenable: false` for these input axes,"
3956 + " or add an output axis with a `size` reference"
3957 + " (`tensor_id`, `axis_id`) to each of them"
3958 + " (for a batch axis: add a batch axis to an output tensor)."
3959 )
3960 return self
3962 @field_validator("outputs", mode="after")
3963 @classmethod
3964 def _validate_tensor_ids(
3965 cls, outputs: Sequence[OutputTensorDescr], info: ValidationInfo
3966 ) -> Sequence[OutputTensorDescr]:
3967 tensor_ids = [
3968 t.id for t in info.data.get("inputs", []) + info.data.get("outputs", [])
3969 ]
3970 duplicate_tensor_ids: list[str] = []
3971 seen: set[str] = set()
3972 for t in tensor_ids:
3973 if t in seen:
3974 duplicate_tensor_ids.append(t)
3976 seen.add(t)
3978 if duplicate_tensor_ids:
3979 raise ValueError(f"Duplicate tensor ids: {duplicate_tensor_ids}")
3981 return outputs
3983 @staticmethod
3984 def _get_axes_with_parameterized_size(
3985 io: Sequence[InputTensorDescr] | Sequence[OutputTensorDescr],
3986 ):
3987 return {
3988 f"{t.id}.{a.id}": (t, a, a.size)
3989 for t in io
3990 for a in t.axes
3991 if not isinstance(a, BatchAxis) and isinstance(a.size, ParameterizedSize)
3992 }
3994 @staticmethod
3995 def _get_axes_with_independent_size(
3996 io: Sequence[InputTensorDescr] | Sequence[OutputTensorDescr],
3997 ):
3998 return {
3999 (t.id, a.id): (t, a, a.size)
4000 for t in io
4001 for a in t.axes
4002 if not isinstance(a, BatchAxis)
4003 and isinstance(a.size, (int, ParameterizedSize))
4004 }
4006 @field_validator("outputs", mode="after")
4007 @classmethod
4008 def _validate_output_axes(
4009 cls, outputs: list[OutputTensorDescr], info: ValidationInfo
4010 ) -> list[OutputTensorDescr]:
4011 input_size_refs = cls._get_axes_with_independent_size(
4012 info.data.get("inputs", [])
4013 )
4014 output_size_refs = cls._get_axes_with_independent_size(outputs)
4016 for i, out in enumerate(outputs):
4017 valid_independent_refs: dict[
4018 tuple[TensorId, AxisId],
4019 tuple[TensorDescr, AnyAxis, int | ParameterizedSize],
4020 ] = {
4021 **{
4022 (out.id, a.id): (out, a, a.size)
4023 for a in out.axes
4024 if not isinstance(a, BatchAxis)
4025 and isinstance(a.size, (int, ParameterizedSize))
4026 },
4027 **input_size_refs,
4028 **output_size_refs,
4029 }
4030 for a, ax in enumerate(out.axes):
4031 cls._validate_axis(
4032 "outputs",
4033 i,
4034 out.id,
4035 a,
4036 ax,
4037 valid_independent_refs=valid_independent_refs,
4038 )
4040 return outputs
4042 packaged_by: list[Author] = Field(
4043 default_factory=cast(Callable[[], list[Author]], list)
4044 )
4045 """The persons that have packaged and uploaded this model.
4046 Only required if those persons differ from the `authors`."""
4048 parent: LinkedModel | None = None
4049 """The model from which this model is derived, e.g. by fine-tuning the weights."""
4051 @model_validator(mode="after")
4052 def _validate_parent_is_not_self(self) -> Self:
4053 if self.parent is not None and self.parent.id == self.id:
4054 raise ValueError("A model description may not reference itself as parent.")
4056 return self
4058 run_mode: Annotated[
4059 RunMode | None,
4060 warn(None, "Run mode '{value}' has limited support across consumer softwares."),
4061 ] = None
4062 """Custom run mode for this model: for more complex prediction procedures like test time
4063 data augmentation that currently cannot be expressed in the specification.
4064 No standard run modes are defined yet."""
4066 timestamp: Datetime = Field(default_factory=Datetime.now)
4067 """Timestamp in [ISO 8601](#https://en.wikipedia.org/wiki/ISO_8601) format
4068 with a few restrictions listed [here](https://docs.python.org/3/library/datetime.html#datetime.datetime.fromisoformat).
4069 (In Python a datetime object is valid, too)."""
4071 training_data: Annotated[
4072 None | LinkedDataset | DatasetDescr | DatasetDescr02,
4073 Field(union_mode="left_to_right"),
4074 ] = None
4075 """The dataset used to train this model"""
4077 weights: Annotated[WeightsDescr, WrapSerializer(package_weights)]
4078 """The weights for this model.
4079 Weights can be given for different formats, but should otherwise be equivalent.
4080 The available weight formats determine which consumers can use this model."""
4082 config: Config = Field(default_factory=Config.model_construct)
4084 @model_validator(mode="after")
4085 def _validate_reproducibility_tolerance_output_ids(self) -> Self:
4086 seen_output_ids: set[TensorId] = set()
4087 for rep_tol in self.config.bioimageio.reproducibility_tolerance:
4088 if not rep_tol.output_ids:
4089 continue
4091 if rep_tol.output_ids == "any_discrete_output":
4092 applicable_output_ids = [
4093 t.id
4094 for t in self.outputs
4095 if t.dtype.startswith("int")
4096 or t.dtype.startswith("uint")
4097 or t.dtype.startswith("bool")
4098 ]
4099 elif rep_tol.output_ids == "any_continuous_output":
4100 applicable_output_ids = [
4101 t.id for t in self.outputs if t.dtype.startswith("float")
4102 ]
4103 else:
4104 applicable_output_ids = rep_tol.output_ids
4106 for out_id in applicable_output_ids:
4107 if out_id in seen_output_ids:
4108 continue
4109 else:
4110 seen_output_ids.add(out_id)
4112 discrete_values = next(
4113 (
4114 t.dtype.startswith("int")
4115 or t.dtype.startswith("uint")
4116 or t.dtype.startswith("bool")
4117 for t in self.outputs
4118 if t.id == out_id
4119 ),
4120 None,
4121 )
4122 if discrete_values is None:
4123 raise ValueError(
4124 f"config.bioimageio.reproducibility_tolerance.output_ids contains '{out_id}', which is not a valid output tensor id."
4125 )
4126 if discrete_values and rep_tol.relative_tolerance != 0:
4127 raise ValueError(
4128 f"config.bioimageio.reproducibility_tolerance.output_ids contains '{out_id}', which is a discrete output tensor, but config.bioimageio.reproducibility_tolerance.relative_tolerance={rep_tol.relative_tolerance} is not 0."
4129 )
4130 if discrete_values and rep_tol.absolute_tolerance != 0:
4131 raise ValueError(
4132 f"config.bioimageio.reproducibility_tolerance.output_ids contains '{out_id}', which is a discrete output tensor, but config.bioimageio.reproducibility_tolerance.absolute_tolerance={rep_tol.absolute_tolerance} is not 0."
4133 )
4135 return self
4137 @model_validator(mode="after")
4138 def _add_default_cover(self) -> Self:
4139 if not get_validation_context().perform_io_checks or self.covers:
4140 return self
4142 try:
4143 generated_covers = generate_covers(
4144 [
4145 (t, load_array(t.test_tensor))
4146 for t in self.inputs
4147 if t.test_tensor is not None
4148 ],
4149 [
4150 (t, load_array(t.test_tensor))
4151 for t in self.outputs
4152 if t.test_tensor is not None
4153 ],
4154 )
4155 except Exception as e:
4156 issue_warning(
4157 "Failed to generate cover image(s): {e}",
4158 value=self.covers,
4159 msg_context={"e": e},
4160 field="covers",
4161 )
4162 else:
4163 self.covers.extend(generated_covers)
4165 return self
4167 def get_input_test_arrays(self) -> list[NDArray[Any]]:
4168 return self._get_test_arrays(self.inputs)
4170 def get_output_test_arrays(self) -> list[NDArray[Any]]:
4171 return self._get_test_arrays(self.outputs)
4173 @staticmethod
4174 def _get_test_arrays(
4175 io_descr: Sequence[InputTensorDescr] | Sequence[OutputTensorDescr],
4176 ):
4177 ts: list[FileDescr] = []
4178 for d in io_descr:
4179 if d.test_tensor is None:
4180 raise ValueError(
4181 f"Failed to get test arrays: description of '{d.id}' is missing a `test_tensor`."
4182 )
4183 ts.append(d.test_tensor)
4185 data = [load_array(t) for t in ts]
4186 assert all(isinstance(d, np.ndarray) for d in data)
4187 return data
4189 @staticmethod
4190 def get_batch_size(tensor_sizes: Mapping[TensorId, Mapping[AxisId, int]]) -> int:
4191 batch_size = 1
4192 tensor_with_batchsize: TensorId | None = None
4193 for tid in tensor_sizes:
4194 for aid, s in tensor_sizes[tid].items():
4195 if aid != BATCH_AXIS_ID or s == 1 or s == batch_size:
4196 continue
4198 if batch_size != 1:
4199 assert tensor_with_batchsize is not None
4200 raise ValueError(
4201 f"batch size mismatch for tensors '{tensor_with_batchsize}' ({batch_size}) and '{tid}' ({s})"
4202 )
4204 batch_size = s
4205 tensor_with_batchsize = tid
4207 return batch_size
4209 def get_output_tensor_sizes(
4210 self, input_sizes: Mapping[TensorId, Mapping[AxisId, int]]
4211 ) -> dict[TensorId, dict[AxisId, int]]:
4212 """Returns the tensor output sizes for given **input_sizes**.
4213 Unknown input axes are passed through (assuming they would be stacked to/unstacked from the batch axis).
4214 Data-dependent output sizes are set to -1.
4216 Note:
4217 A warning is logged if the calculated output sizes do not match the output tensor sizes
4218 inferred from the model descriptions with parameters inferred fromthe given input sizes.
4219 This is likely the case if the input sizes are not valid according to the model description.
4220 """
4221 # get tensor sizes for valid inputs that can be parameterized by batch size and axis size parameters `n` (for each parameterized axis)
4222 batch_size = self.get_batch_size(input_sizes)
4223 stackable_input_axes: dict[AxisId, int] = {}
4224 stackable_input_axes_per_input: dict[TensorId, set[AxisId]] = {}
4225 for m, in_sizes in input_sizes.items():
4226 input_descrs = {t.id: t for t in self.inputs}
4227 if m not in input_descrs:
4228 logger.warning(
4229 "Ignoring unexpected input tensor '{}'.",
4230 m,
4231 )
4232 continue
4233 ipt_descr = input_descrs[m]
4234 stackable_input_axes_per_input[m] = set()
4235 for a, s in in_sizes.items():
4236 if a not in [ax.id for ax in ipt_descr.axes]:
4237 stackable_input_axes_per_input[m].add(a)
4238 if a not in stackable_input_axes:
4239 stackable_input_axes[a] = s
4240 elif stackable_input_axes[a] != s:
4241 raise ValueError(
4242 f"Input axis '{a}' has inconsistent sizes across input tensors: {stackable_input_axes[a]} vs {s}"
4243 )
4245 if not all(
4246 stackable_per_input == set(stackable_input_axes)
4247 for stackable_per_input in stackable_input_axes_per_input.values()
4248 ):
4249 raise ValueError(
4250 "Not all input tensors have the same set of additonal axes that could otherwise be treated as a stacked batch dimension. "
4251 + f"Extra axes per input: {stackable_input_axes_per_input}"
4252 )
4254 ns = self.get_ns(input_sizes)
4255 valid_tensor_sizes = self.get_tensor_sizes(ns, batch_size=batch_size)
4257 input_sizes_refs = {
4258 ipt.id: {
4259 ax.id: (ax, input_sizes[ipt.id][ax.id])
4260 for ax in ipt.axes
4261 if not isinstance(ax, BatchAxis) and ax.id in input_sizes[ipt.id]
4262 }
4263 for ipt in self.inputs
4264 if ipt.id in input_sizes
4265 }
4266 output_sizes: dict[TensorId, dict[AxisId, int]] = {
4267 out.id: {} for out in self.outputs
4268 }
4269 for out in self.outputs:
4270 for ax in out.axes:
4271 if isinstance(ax, BatchAxis):
4272 s = batch_size
4273 elif isinstance(ax.size, int):
4274 s = ax.size
4275 elif isinstance(ax.size, SizeReference):
4276 if (
4277 ax.size.tensor_id not in input_sizes_refs
4278 or ax.size.axis_id not in input_sizes_refs[ax.size.tensor_id]
4279 ):
4280 logger.warning(
4281 "Output axis {}.{} references input axis {}.{}, which is not present in the provided input sizes."
4282 + " Assuming the output is optional and not produced for this input.",
4283 out.id,
4284 ax.id,
4285 ax.size.tensor_id,
4286 ax.size.axis_id,
4287 )
4288 continue
4290 ref_ax, ref_size = input_sizes_refs[ax.size.tensor_id][
4291 ax.size.axis_id
4292 ]
4293 s = ax.size.get_size(ax, ref_ax, ref_size=ref_size)
4294 elif isinstance(ax.size, DataDependentSize):
4295 s = -1
4296 else:
4297 assert_never(ax.size)
4299 output_sizes[out.id][ax.id] = s
4300 if isinstance(ax, BatchAxis):
4301 # insert extra input dimensions to be passed through like the batch axis
4302 for a, s in stackable_input_axes.items():
4303 output_sizes[out.id][a] = s
4305 if valid_tensor_sizes.outputs != output_sizes:
4306 if valid_tensor_sizes.inputs != input_sizes:
4307 logger.trace(
4308 "Input sizes do not match the model's input tensor descriptions which may lead to inconsistent output sizes."
4309 + " Expected: {}, got: {}.",
4310 valid_tensor_sizes.inputs,
4311 input_sizes,
4312 )
4313 else:
4314 logger.error(
4315 "Directly calculated output sizes do not match the output tensor sizes inferred from the model descriptions with the given input size parameters."
4316 + " Expected: {}, got: {}.",
4317 valid_tensor_sizes.outputs,
4318 output_sizes,
4319 )
4321 return output_sizes
4323 def get_ns(self, input_sizes: Mapping[TensorId, Mapping[AxisId, int]]):
4324 """get parameter `n` for each parameterized axis
4325 such that the valid input size is >= the given input size"""
4326 ret: dict[tuple[TensorId, AxisId], ParameterizedSize_N] = {}
4327 axes_per_member = {t.id: {a.id: a for a in t.axes} for t in self.inputs}
4328 for tid in input_sizes:
4329 axes = axes_per_member.get(tid)
4330 if axes is None:
4331 continue
4332 for aid, s in input_sizes[tid].items():
4333 axis_descr = axes.get(aid)
4334 if axis_descr is None:
4335 continue
4336 if isinstance(axis_descr.size, ParameterizedSize):
4337 ret[(tid, aid)] = axis_descr.size.get_n(s)
4338 elif axis_descr.size is None or isinstance(
4339 axis_descr.size, (int, SizeReference)
4340 ):
4341 pass
4342 else:
4343 assert_never(axis_descr.size)
4345 return ret
4347 def get_tensor_sizes(
4348 self,
4349 ns: Mapping[tuple[TensorId, AxisId], ParameterizedSize_N] | ParameterizedSize_N,
4350 batch_size: int,
4351 max_input_shape: Mapping[TensorId, Mapping[AxisId, int]] | None = None,
4352 ) -> _TensorSizes:
4353 max_axis_sizes: dict[tuple[TensorId, AxisId], int] = {}
4354 for m, this_max_axis_sizes in (max_input_shape or {}).items():
4355 for a, s in this_max_axis_sizes.items():
4356 max_axis_sizes[(m, a)] = s
4358 axis_sizes = self.get_axis_sizes(
4359 ns, batch_size=batch_size, max_input_shape=max_axis_sizes
4360 )
4361 return _TensorSizes(
4362 {
4363 t: {
4364 aa: axis_sizes.inputs[(tt, aa)]
4365 for tt, aa in axis_sizes.inputs
4366 if tt == t
4367 }
4368 for t in {tt for tt, _ in axis_sizes.inputs}
4369 },
4370 {
4371 t: {
4372 aa: axis_sizes.outputs[(tt, aa)]
4373 for tt, aa in axis_sizes.outputs
4374 if tt == t
4375 }
4376 for t in {tt for tt, _ in axis_sizes.outputs}
4377 },
4378 )
4380 def get_axis_sizes(
4381 self,
4382 ns: Mapping[tuple[TensorId, AxisId], ParameterizedSize_N] | ParameterizedSize_N,
4383 batch_size: int | None = None,
4384 *,
4385 max_input_shape: Mapping[tuple[TensorId, AxisId], int] | None = None,
4386 ) -> _AxisSizes:
4387 """Determine input and output block shape for scale factors **ns**
4388 of parameterized input sizes.
4390 Args:
4391 ns: Scale factor `n` for each axis (keyed by (tensor_id, axis_id))
4392 that is parameterized as `size = min + n * step`.
4393 batch_size: The desired size of the batch dimension.
4394 If given **batch_size** overwrites any batch size present in
4395 **max_input_shape**. Default 1.
4396 max_input_shape: Limits the derived block shapes.
4397 Each axis for which the input size, parameterized by `n`, is larger
4398 than **max_input_shape** is set to the minimal value `n_min` for which
4399 this is still true.
4400 Use this for small input samples or large values of **ns**.
4401 Or simply whenever you know the full input shape.
4403 Returns:
4404 Resolved axis sizes for model inputs and outputs.
4405 """
4406 max_input_shape = max_input_shape or {}
4407 if batch_size is None:
4408 for (_t_id, a_id), s in max_input_shape.items():
4409 if a_id == BATCH_AXIS_ID:
4410 batch_size = s
4411 break
4412 else:
4413 batch_size = 1
4415 all_axes = {
4416 t.id: {a.id: a for a in t.axes} for t in chain(self.inputs, self.outputs)
4417 }
4419 inputs: dict[tuple[TensorId, AxisId], int] = {}
4420 outputs: dict[tuple[TensorId, AxisId], int | _DataDepSize] = {}
4422 def get_axis_size(a: InputAxis | OutputAxis):
4423 if isinstance(a, BatchAxis):
4424 if not isinstance(ns, int) and (t_descr.id, a.id) in ns:
4425 logger.warning(
4426 "Ignoring unexpected size increment factor (n) for batch axis"
4427 + " of tensor '{}'.",
4428 t_descr.id,
4429 )
4430 return batch_size
4431 elif isinstance(a.size, int):
4432 if not isinstance(ns, int) and (t_descr.id, a.id) in ns:
4433 logger.warning(
4434 "Ignoring unexpected size increment factor (n) for fixed size"
4435 + " axis '{}' of tensor '{}'.",
4436 a.id,
4437 t_descr.id,
4438 )
4439 return a.size
4440 elif isinstance(a.size, ParameterizedSize):
4441 n = ns if isinstance(ns, int) else ns.get((t_descr.id, a.id))
4442 if n is None:
4443 raise ValueError(
4444 "Size increment factor (n) missing for parametrized axis"
4445 + f" '{a.id}' of tensor '{t_descr.id}'."
4446 )
4447 s_max = max_input_shape.get((t_descr.id, a.id))
4448 if s_max is not None:
4449 n = min(n, a.size.get_n(s_max))
4451 return a.size.get_size(n)
4453 elif isinstance(a.size, SizeReference):
4454 if not isinstance(ns, int) and (t_descr.id, a.id) in ns:
4455 logger.warning(
4456 "Ignoring unexpected size increment factor (n) for axis '{}'"
4457 + " of tensor '{}' with size reference.",
4458 a.id,
4459 t_descr.id,
4460 )
4461 assert not isinstance(a, BatchAxis)
4462 ref_axis = all_axes[a.size.tensor_id][a.size.axis_id]
4463 assert not isinstance(ref_axis, BatchAxis)
4464 ref_key = (a.size.tensor_id, a.size.axis_id)
4465 ref_size = inputs.get(ref_key, outputs.get(ref_key))
4466 assert ref_size is not None, ref_key
4467 assert not isinstance(ref_size, _DataDepSize), ref_key
4468 return a.size.get_size(
4469 axis=a,
4470 ref_axis=ref_axis,
4471 ref_size=ref_size,
4472 )
4473 elif isinstance(a.size, DataDependentSize):
4474 if not isinstance(ns, int) and (t_descr.id, a.id) in ns:
4475 logger.warning(
4476 "Ignoring unexpected increment factor (n) for data dependent"
4477 + " size axis '{}' of tensor '{}'.",
4478 a.id,
4479 t_descr.id,
4480 )
4481 return _DataDepSize(a.size.min, a.size.max)
4482 else:
4483 assert_never(a.size)
4485 # first resolve all , but the `SizeReference` input sizes
4486 for t_descr in self.inputs:
4487 for a in t_descr.axes:
4488 if not isinstance(a.size, SizeReference):
4489 s = get_axis_size(a)
4490 assert not isinstance(s, _DataDepSize)
4491 inputs[t_descr.id, a.id] = s
4493 # resolve all other input axis sizes
4494 for t_descr in self.inputs:
4495 for a in t_descr.axes:
4496 if isinstance(a.size, SizeReference):
4497 s = get_axis_size(a)
4498 assert not isinstance(s, _DataDepSize)
4499 inputs[t_descr.id, a.id] = s
4501 # resolve all output axis sizes
4502 for t_descr in self.outputs:
4503 for a in t_descr.axes:
4504 assert not isinstance(a.size, ParameterizedSize)
4505 s = get_axis_size(a)
4506 outputs[t_descr.id, a.id] = s
4508 return _AxisSizes(inputs=inputs, outputs=outputs)
4510 @model_validator(mode="before")
4511 @classmethod
4512 def _convert(cls, data: dict[str, Any]) -> dict[str, Any]:
4513 cls.convert_from_old_format_wo_validation(data)
4514 return data
4516 @classmethod
4517 def convert_from_old_format_wo_validation(cls, data: dict[str, Any]) -> None:
4518 """Convert metadata following an older format version to this classes' format
4519 without validating the result.
4520 """
4521 if (
4522 data.get("type") == "model"
4523 and isinstance(fv := data.get("format_version"), str)
4524 and fv.count(".") == 2
4525 ):
4526 fv_parts = fv.split(".")
4527 if any(not p.isdigit() for p in fv_parts):
4528 return
4530 fv_tuple = tuple(map(int, fv_parts))
4532 assert cls.implemented_format_version_tuple[0:2] == (0, 5)
4533 if fv_tuple[:2] in ((0, 3), (0, 4)):
4534 m04 = _ModelDescr_v0_4.load(data)
4535 if isinstance(m04, InvalidDescr):
4536 try:
4537 updated = _model_conv.convert_as_dict(
4538 m04 # pyright: ignore[reportArgumentType]
4539 )
4540 except Exception as e:
4541 logger.error(
4542 "Failed to convert from invalid model 0.4 description."
4543 + f"\nerror: {e}"
4544 + "\nProceeding with model 0.5 validation without conversion."
4545 )
4546 updated = None
4547 else:
4548 updated = _model_conv.convert_as_dict(m04)
4550 if updated is not None:
4551 data.clear()
4552 data.update(updated)
4554 elif fv_tuple[:2] == (0, 5):
4555 # bump patch version
4556 data["format_version"] = cls.implemented_format_version
4558 if fv_tuple[:2] in ((0, 3), (0, 4)) or (
4559 fv_tuple[:2] == (0, 5) and fv_tuple[2] < 11
4560 ):
4561 convert_plain_covers_and_docs_and_icon(data)
4563 if fv_tuple < (0, 5, 15):
4564 # before 0.5.15 input axes were not concatenable by default
4565 ipts = data.get("inputs") or [] # pyright: ignore[reportUnknownVariableType]
4566 if isinstance(ipts, Sequence):
4567 for ipt in ipts: # pyright: ignore[reportUnknownVariableType]
4568 if not isinstance(ipt, dict):
4569 continue
4571 axes = ipt.get("axes") or [] # pyright: ignore[reportUnknownVariableType]
4572 if not isinstance(axes, Sequence):
4573 continue
4574 for ax in axes: # pyright: ignore[reportUnknownVariableType]
4575 if isinstance(ax, dict) and ax.get("type") in (
4576 "index",
4577 "time",
4578 "space",
4579 ):
4580 ax.setdefault("concatenable", False)
4583class _ModelConv(Converter[_ModelDescr_v0_4, ModelDescr]):
4584 def _convert(
4585 self, src: _ModelDescr_v0_4, tgt: type[ModelDescr | dict[str, Any]]
4586 ) -> ModelDescr | dict[str, Any]:
4587 name = "".join(
4588 c if c in string.ascii_letters + string.digits + "_+- ()" else " "
4589 for c in src.name
4590 )
4592 def conv_authors(auths: Sequence[_Author_v0_4] | None):
4593 conv = (
4594 _author_conv.convert if TYPE_CHECKING else _author_conv.convert_as_dict
4595 )
4596 return None if auths is None else [conv(a) for a in auths]
4598 if TYPE_CHECKING:
4599 arch_file_conv = _arch_file_conv.convert
4600 arch_lib_conv = _arch_lib_conv.convert
4601 else:
4602 arch_file_conv = _arch_file_conv.convert_as_dict
4603 arch_lib_conv = _arch_lib_conv.convert_as_dict
4605 input_size_refs = {
4606 ipt.name: {
4607 a: s
4608 for a, s in zip(
4609 ipt.axes,
4610 (
4611 ipt.shape.min
4612 if isinstance(ipt.shape, _ParameterizedInputShape_v0_4)
4613 else ipt.shape
4614 ),
4615 )
4616 }
4617 for ipt in src.inputs
4618 if ipt.shape
4619 }
4620 output_size_refs = {
4621 **{
4622 out.name: {a: s for a, s in zip(out.axes, out.shape)}
4623 for out in src.outputs
4624 if not isinstance(out.shape, _ImplicitOutputShape_v0_4)
4625 },
4626 **input_size_refs,
4627 }
4629 return tgt(
4630 attachments=(
4631 []
4632 if src.attachments is None
4633 else [FileDescr(source=f) for f in src.attachments.files]
4634 ),
4635 authors=[_author_conv.convert_as_dict(a) for a in src.authors], # pyright: ignore[reportArgumentType]
4636 cite=[{"text": c.text, "doi": c.doi, "url": c.url} for c in src.cite], # pyright: ignore[reportArgumentType]
4637 config=src.config, # pyright: ignore[reportArgumentType]
4638 covers=[{"source": c} for c in src.covers], # pyright: ignore[reportArgumentType]
4639 description=src.description,
4640 documentation={"source": src.documentation} if src.documentation else None, # pyright: ignore[reportArgumentType]
4641 format_version="0.5.15",
4642 git_repo=src.git_repo, # pyright: ignore[reportArgumentType]
4643 icon={"source": src.icon} if src.icon else None, # pyright: ignore[reportArgumentType]
4644 id=None if src.id is None else ModelId(src.id),
4645 id_emoji=src.id_emoji,
4646 license=src.license, # type: ignore
4647 links=src.links,
4648 maintainers=[_maintainer_conv.convert_as_dict(m) for m in src.maintainers], # pyright: ignore[reportArgumentType]
4649 name=name,
4650 tags=src.tags,
4651 type=src.type,
4652 uploader=src.uploader,
4653 version=src.version,
4654 inputs=[ # pyright: ignore[reportArgumentType]
4655 _input_tensor_conv.convert_as_dict(ipt, tt, st, input_size_refs)
4656 for ipt, tt, st in zip(
4657 src.inputs,
4658 src.test_inputs,
4659 src.sample_inputs or [None] * len(src.test_inputs),
4660 )
4661 ],
4662 outputs=[ # pyright: ignore[reportArgumentType]
4663 _output_tensor_conv.convert_as_dict(out, tt, st, output_size_refs)
4664 for out, tt, st in zip(
4665 src.outputs,
4666 src.test_outputs,
4667 src.sample_outputs or [None] * len(src.test_outputs),
4668 )
4669 ],
4670 parent=(
4671 None
4672 if src.parent is None
4673 else LinkedModel(
4674 id=ModelId(
4675 str(src.parent.id)
4676 + (
4677 ""
4678 if src.parent.version_number is None
4679 else f"/{src.parent.version_number}"
4680 )
4681 )
4682 )
4683 ),
4684 training_data=(
4685 None
4686 if src.training_data is None
4687 else (
4688 LinkedDataset(
4689 id=DatasetId(
4690 str(src.training_data.id)
4691 + (
4692 ""
4693 if src.training_data.version_number is None
4694 else f"/{src.training_data.version_number}"
4695 )
4696 )
4697 )
4698 if isinstance(src.training_data, LinkedDataset02)
4699 else src.training_data
4700 )
4701 ),
4702 packaged_by=[_author_conv.convert_as_dict(a) for a in src.packaged_by], # pyright: ignore[reportArgumentType]
4703 run_mode=src.run_mode,
4704 timestamp=src.timestamp,
4705 weights=(WeightsDescr if TYPE_CHECKING else dict)(
4706 keras_hdf5=(w := src.weights.keras_hdf5)
4707 and (KerasHdf5WeightsDescr if TYPE_CHECKING else dict)(
4708 authors=conv_authors(w.authors),
4709 source=w.source,
4710 tensorflow_version=w.tensorflow_version or Version("1.15"),
4711 parent=w.parent,
4712 ),
4713 onnx=(w := src.weights.onnx)
4714 and (OnnxWeightsDescr if TYPE_CHECKING else dict)(
4715 source=w.source,
4716 authors=conv_authors(w.authors),
4717 parent=w.parent,
4718 opset_version=w.opset_version or 15,
4719 ),
4720 pytorch_state_dict=(w := src.weights.pytorch_state_dict)
4721 and (PytorchStateDictWeightsDescr if TYPE_CHECKING else dict)(
4722 source=w.source,
4723 authors=conv_authors(w.authors),
4724 parent=w.parent,
4725 architecture=(
4726 arch_file_conv(
4727 w.architecture,
4728 w.architecture_sha256,
4729 w.kwargs,
4730 )
4731 if isinstance(w.architecture, _CallableFromFile_v0_4)
4732 else arch_lib_conv(w.architecture, w.kwargs)
4733 ),
4734 pytorch_version=w.pytorch_version or Version("1.10"),
4735 dependencies=(
4736 None
4737 if w.dependencies is None
4738 else (FileDescr if TYPE_CHECKING else dict)(
4739 source=cast(
4740 FileSource,
4741 str(deps := w.dependencies)[
4742 (
4743 len("conda:")
4744 if str(deps).startswith("conda:")
4745 else 0
4746 ) :
4747 ],
4748 )
4749 )
4750 ),
4751 ),
4752 tensorflow_js=(w := src.weights.tensorflow_js)
4753 and (TensorflowJsWeightsDescr if TYPE_CHECKING else dict)(
4754 source=w.source,
4755 authors=conv_authors(w.authors),
4756 parent=w.parent,
4757 tensorflow_version=w.tensorflow_version or Version("1.15"),
4758 ),
4759 tensorflow_saved_model_bundle=(
4760 w := src.weights.tensorflow_saved_model_bundle
4761 )
4762 and (TensorflowSavedModelBundleWeightsDescr if TYPE_CHECKING else dict)(
4763 authors=conv_authors(w.authors),
4764 parent=w.parent,
4765 source=w.source,
4766 tensorflow_version=w.tensorflow_version or Version("1.15"),
4767 dependencies=(
4768 None
4769 if w.dependencies is None
4770 else (FileDescr if TYPE_CHECKING else dict)(
4771 source=cast(
4772 FileSource,
4773 (str(w.dependencies).removeprefix("conda:")),
4774 )
4775 )
4776 ),
4777 ),
4778 torchscript=(w := src.weights.torchscript)
4779 and (TorchscriptWeightsDescr if TYPE_CHECKING else dict)(
4780 source=w.source,
4781 authors=conv_authors(w.authors),
4782 parent=w.parent,
4783 pytorch_version=w.pytorch_version or Version("1.10"),
4784 ),
4785 ),
4786 )
4789_model_conv = _ModelConv(_ModelDescr_v0_4, ModelDescr)
4792# create better cover images for 3d data and non-image outputs
4793def generate_covers(
4794 inputs: Sequence[tuple[InputTensorDescr, NDArray[Any]]],
4795 outputs: Sequence[tuple[OutputTensorDescr, NDArray[Any]]],
4796) -> list[FileDescr]:
4797 def squeeze(
4798 data: NDArray[Any], axes: Sequence[AnyAxis]
4799 ) -> tuple[NDArray[Any], list[AnyAxis]]:
4800 """apply numpy.ndarray.squeeze while keeping track of the axis descriptions remaining"""
4801 if data.ndim != len(axes):
4802 raise ValueError(
4803 f"tensor shape {data.shape} does not match described axes"
4804 + f" {[a.id for a in axes]}"
4805 )
4807 axes = [deepcopy(a) for a, s in zip(axes, data.shape) if s != 1]
4808 return data.squeeze(), axes
4810 def normalize(
4811 data: NDArray[Any], axis: tuple[int, ...] | None, eps: float = 1e-7
4812 ) -> NDArray[np.float32]:
4813 data = data.astype("float32")
4814 data -= data.min(axis=axis, keepdims=True)
4815 data /= data.max(axis=axis, keepdims=True) + eps
4816 return data
4818 def to_2d_image(data: NDArray[Any], axes: Sequence[AnyAxis]):
4819 original_shape = data.shape
4820 original_axes = list(axes)
4821 data, axes = squeeze(data, axes)
4823 # take slice fom any batch or index axis if needed
4824 # and convert the first channel axis and take a slice from any additional channel axes
4825 slices: tuple[slice, ...] = ()
4826 ndim = data.ndim
4827 ndim_need = 3 if any(isinstance(a, ChannelAxis) for a in axes) else 2
4828 has_c_axis = False
4829 for i, a in enumerate(axes):
4830 s = data.shape[i]
4831 assert s > 1
4832 if (
4833 isinstance(a, (BatchAxis, IndexInputAxis, IndexOutputAxis))
4834 and ndim > ndim_need
4835 ):
4836 data = data[slices + (slice(s // 2 - 1, s // 2),)]
4837 ndim -= 1
4838 elif isinstance(a, ChannelAxis):
4839 if has_c_axis:
4840 # second channel axis
4841 data = data[slices + (slice(0, 1),)]
4842 ndim -= 1
4843 else:
4844 has_c_axis = True
4845 if s == 2:
4846 # visualize two channels with cyan and magenta
4847 data = np.concatenate(
4848 [
4849 data[slices + (slice(1, 2),)],
4850 data[slices + (slice(0, 1),)],
4851 (
4852 data[slices + (slice(0, 1),)]
4853 + data[slices + (slice(1, 2),)]
4854 )
4855 / 2, # TODO: take maximum instead?
4856 ],
4857 axis=i,
4858 )
4859 elif data.shape[i] == 3:
4860 pass # visualize 3 channels as RGB
4861 else:
4862 # visualize first 3 channels as RGB
4863 data = data[slices + (slice(3),)]
4865 assert data.shape[i] == 3
4867 slices += (slice(None),)
4869 data, axes = squeeze(data, axes)
4870 assert len(axes) == ndim
4871 # take slice from z axis if needed
4872 slices = ()
4873 if ndim > ndim_need:
4874 for i, a in enumerate(axes):
4875 s = data.shape[i]
4876 if a.id == AxisId("z"):
4877 data = data[slices + (slice(s // 2 - 1, s // 2),)]
4878 data, axes = squeeze(data, axes)
4879 ndim -= 1
4880 break
4882 slices += (slice(None),)
4884 # take slice from any space or time axis
4885 slices = ()
4887 for i, a in enumerate(axes):
4888 if ndim <= ndim_need:
4889 break
4891 s = data.shape[i]
4892 assert s > 1
4893 if isinstance(
4894 a, (SpaceInputAxis, SpaceOutputAxis, TimeInputAxis, TimeOutputAxis)
4895 ):
4896 data = data[slices + (slice(s // 2 - 1, s // 2),)]
4897 ndim -= 1
4899 slices += (slice(None),)
4901 del slices
4902 data, axes = squeeze(data, axes)
4903 assert len(axes) == ndim
4905 if (has_c_axis and ndim != 3) or (not has_c_axis and ndim != 2):
4906 raise ValueError(
4907 f"Failed to construct cover image from shape {original_shape} with axes {[a.id for a in original_axes]}."
4908 )
4910 if not has_c_axis:
4911 assert ndim == 2
4912 data = np.repeat(data[:, :, None], 3, axis=2)
4913 axes.append(ChannelAxis(channel_names=list("RGB")))
4914 ndim += 1
4916 assert ndim == 3
4918 # transpose axis order such that longest axis comes first...
4919 axis_order: list[int] = [int(i) for i in np.argsort(list(data.shape))]
4920 axis_order.reverse()
4921 # ... and channel axis is last
4922 c = next(i for i in range(3) if isinstance(axes[i], ChannelAxis))
4923 axis_order.append(axis_order.pop(c))
4924 axes = [axes[ao] for ao in axis_order]
4925 data = cast(NDArray[Any], data.transpose(axis_order))
4927 # h, w = data.shape[:2]
4928 # if h / w in (1.0 or 2.0):
4929 # pass
4930 # elif h / w < 2:
4931 # TODO: enforce 2:1 or 1:1 aspect ratio for generated cover images
4933 norm_along = (
4934 tuple(i for i, a in enumerate(axes) if a.type in ("space", "time")) or None
4935 )
4936 # normalize the data and map to 8 bit
4937 data = normalize(data, norm_along)
4938 data = (data * 255).astype("uint8")
4940 return data
4942 def create_diagonal_split_image(im0: NDArray[Any], im1: NDArray[Any]):
4943 assert im0.dtype == im1.dtype == np.uint8
4944 assert im0.shape == im1.shape
4945 assert im0.ndim == 3
4946 N, M, C = im0.shape
4947 assert C == 3
4948 out = np.ones((N, M, C), dtype="uint8")
4949 for c in range(C):
4950 outc = np.tril(im0[..., c])
4951 mask = outc == 0
4952 outc[mask] = np.triu(im1[..., c])[mask]
4953 out[..., c] = outc
4955 return out
4957 if not inputs:
4958 raise ValueError("Missing test input tensor for cover generation.")
4960 if not outputs:
4961 raise ValueError("Missing test output tensor for cover generation.")
4963 ipt_descr, ipt = inputs[0]
4964 out_descr, out = outputs[0]
4966 ipt_img = to_2d_image(ipt, ipt_descr.axes)
4967 out_img = to_2d_image(out, out_descr.axes)
4969 cover_folder = Path(mkdtemp())
4970 if ipt_img.shape == out_img.shape:
4971 covers = [cover_folder / "cover.png"]
4972 imwrite(covers[0], create_diagonal_split_image(ipt_img, out_img))
4973 else:
4974 covers = [cover_folder / "input.png", cover_folder / "output.png"]
4975 imwrite(covers[0], ipt_img)
4976 imwrite(covers[1], out_img)
4978 return [FileDescr(source=c) for c in covers]