Coverage for src/bioimageio/spec/model/v0_4.py: 92%

651 statements  

« prev     ^ index     » next       coverage.py v7.17.3, created at 2026-11-17 16:20 +0000

1from __future__ import annotations 

2 

3from collections.abc import Callable, Mapping, Sequence 

4from typing import ( 

5 TYPE_CHECKING, 

6 Annotated, 

7 Any, 

8 ClassVar, 

9 Literal, 

10 cast, 

11 get_args, 

12) 

13 

14import numpy as np 

15from annotated_types import Ge, Interval, MaxLen, MinLen, MultipleOf 

16from loguru import logger 

17from numpy.typing import NDArray 

18from pydantic import ( 

19 AllowInfNan, 

20 Discriminator, 

21 Field, 

22 RootModel, 

23 SerializationInfo, 

24 SerializerFunctionWrapHandler, 

25 StringConstraints, 

26 TypeAdapter, 

27 ValidationInfo, 

28 WrapSerializer, 

29 field_validator, 

30 model_validator, 

31) 

32from typing_extensions import Self, assert_never 

33 

34from .._internal.common_nodes import ( 

35 KwargsNode, 

36 Node, 

37 NodeWithExplicitlySetFields, 

38) 

39from .._internal.constants import SHA256_HINT 

40from .._internal.field_validation import validate_unique_entries 

41from .._internal.field_warning import issue_warning, warn 

42from .._internal.io import BioimageioYamlContent, WithSuffix 

43from .._internal.io import FileDescr as FileDescr 

44from .._internal.io_basics import Sha256 as Sha256 

45from .._internal.io_packaging import FileSource_package, include_in_package 

46from .._internal.io_utils import load_array 

47from .._internal.packaging_context import packaging_context_var 

48from .._internal.types import Datetime as Datetime 

49from .._internal.types import FileSource, LowerCaseIdentifier 

50from .._internal.types import Identifier as Identifier 

51from .._internal.types import LicenseId as LicenseId 

52from .._internal.types import NotEmpty as NotEmpty 

53from .._internal.url import HttpUrl as HttpUrl 

54from .._internal.validated_string_with_inner_node import ValidatedStringWithInnerNode 

55from .._internal.validator_annotations import AfterValidator, RestrictCharacters 

56from .._internal.version_type import Version as Version 

57from .._internal.warning_levels import ALERT, INFO 

58from ..dataset.v0_2 import VALID_COVER_IMAGE_EXTENSIONS as VALID_COVER_IMAGE_EXTENSIONS 

59from ..dataset.v0_2 import DatasetDescr as DatasetDescr 

60from ..dataset.v0_2 import LinkedDataset as LinkedDataset 

61from ..generic.v0_2 import AttachmentsDescr as AttachmentsDescr 

62from ..generic.v0_2 import Author as Author 

63from ..generic.v0_2 import BadgeDescr as BadgeDescr 

64from ..generic.v0_2 import CiteEntry as CiteEntry 

65from ..generic.v0_2 import Doi as Doi 

66from ..generic.v0_2 import GenericModelDescrBase 

67from ..generic.v0_2 import LinkedResource as LinkedResource 

68from ..generic.v0_2 import Maintainer as Maintainer 

69from ..generic.v0_2 import OrcidId as OrcidId 

70from ..generic.v0_2 import RelativeFilePath as RelativeFilePath 

71from ..generic.v0_2 import ResourceId as ResourceId 

72from ..generic.v0_2 import Uploader as Uploader 

73from ._v0_4_converter import convert_from_older_format 

74 

75 

76class ModelId(ResourceId): 

77 pass 

78 

79 

80AxesStr = Annotated[ 

81 str, RestrictCharacters("bitczyx"), AfterValidator(validate_unique_entries) 

82] 

83AxesInCZYX = Annotated[ 

84 str, RestrictCharacters("czyx"), AfterValidator(validate_unique_entries) 

85] 

86 

87PostprocessingName = Literal[ 

88 "binarize", 

89 "clip", 

90 "scale_linear", 

91 "sigmoid", 

92 "zero_mean_unit_variance", 

93 "scale_range", 

94 "scale_mean_variance", 

95] 

96PreprocessingName = Literal[ 

97 "binarize", 

98 "clip", 

99 "scale_linear", 

100 "sigmoid", 

101 "zero_mean_unit_variance", 

102 "scale_range", 

103] 

104 

105 

106class TensorName(LowerCaseIdentifier): 

107 pass 

108 

109 

110class CallableFromDepencencyNode(Node): 

111 _submodule_adapter: ClassVar[TypeAdapter[Identifier]] = TypeAdapter(Identifier) 

112 

113 module_name: str 

114 """The Python module that implements **callable_name**.""" 

115 

116 @field_validator("module_name", mode="after") 

117 def _check_submodules(cls, module_name: str) -> str: 

118 for submod in module_name.split("."): 

119 _ = cls._submodule_adapter.validate_python(submod) 

120 

121 return module_name 

122 

123 callable_name: Identifier 

124 """The callable Python identifier implemented in module **module_name**.""" 

125 

126 

127class CallableFromDepencency(ValidatedStringWithInnerNode[CallableFromDepencencyNode]): 

128 _inner_node_class = CallableFromDepencencyNode 

129 root_model: ClassVar[type[RootModel[Any]]] = RootModel[ 

130 Annotated[ 

131 str, 

132 StringConstraints(strip_whitespace=True, pattern=r"^.+\..+$"), 

133 ] 

134 ] 

135 

136 @classmethod 

137 def _get_data(cls, valid_string_data: str): 

138 *mods, callname = valid_string_data.split(".") 

139 return {"module_name": ".".join(mods), "callable_name": callname} 

140 

141 @property 

142 def module_name(self): 

143 """The Python module that implements **callable_name**.""" 

144 return self._inner_node.module_name 

145 

146 @property 

147 def callable_name(self): 

148 """The callable Python identifier implemented in module **module_name**.""" 

149 return self._inner_node.callable_name 

150 

151 

152class CallableFromFileNode(Node): 

153 source_file: Annotated[ 

154 RelativeFilePath | HttpUrl, 

155 Field(union_mode="left_to_right"), 

156 include_in_package, 

157 ] 

158 """The Python source file that implements **callable_name**.""" 

159 callable_name: Identifier 

160 """The callable Python identifier implemented in **source_file**.""" 

161 

162 

163class CallableFromFile(ValidatedStringWithInnerNode[CallableFromFileNode]): 

164 _inner_node_class = CallableFromFileNode 

165 root_model: ClassVar[type[RootModel[Any]]] = RootModel[ 

166 Annotated[ 

167 str, 

168 StringConstraints(strip_whitespace=True, pattern=r"^.+:.+$"), 

169 ] 

170 ] 

171 

172 @classmethod 

173 def _get_data(cls, valid_string_data: str): 

174 *file_parts, callname = valid_string_data.split(":") 

175 return {"source_file": ":".join(file_parts), "callable_name": callname} 

176 

177 @property 

178 def source_file(self): 

179 """The Python source file that implements **callable_name**.""" 

180 return self._inner_node.source_file 

181 

182 @property 

183 def callable_name(self): 

184 """The callable Python identifier implemented in **source_file**.""" 

185 return self._inner_node.callable_name 

186 

187 

188CustomCallable = Annotated[ 

189 CallableFromFile | CallableFromDepencency, Field(union_mode="left_to_right") 

190] 

191 

192 

193class DependenciesNode(Node): 

194 manager: Annotated[NotEmpty[str], Field(examples=["conda", "maven", "pip"])] 

195 """Dependency manager""" 

196 

197 file: FileSource_package 

198 """Dependency file""" 

199 

200 

201class Dependencies(ValidatedStringWithInnerNode[DependenciesNode]): 

202 _inner_node_class = DependenciesNode 

203 root_model: ClassVar[type[RootModel[Any]]] = RootModel[ 

204 Annotated[ 

205 str, 

206 StringConstraints(strip_whitespace=True, pattern=r"^.+:.+$"), 

207 ] 

208 ] 

209 

210 @classmethod 

211 def _get_data(cls, valid_string_data: str): 

212 manager, *file_parts = valid_string_data.split(":") 

213 return {"manager": manager, "file": ":".join(file_parts)} 

214 

215 @property 

216 def manager(self): 

217 """Dependency manager""" 

218 return self._inner_node.manager 

219 

220 @property 

221 def file(self): 

222 """Dependency file""" 

223 return self._inner_node.file 

224 

225 

226WeightsFormat = Literal[ 

227 "keras_hdf5", 

228 "onnx", 

229 "pytorch_state_dict", 

230 "tensorflow_js", 

231 "tensorflow_saved_model_bundle", 

232 "torchscript", 

233] 

234 

235 

236class WeightsEntryDescrBase(FileDescr): 

237 type: ClassVar[WeightsFormat] 

238 weights_format_name: ClassVar[str] # human readable 

239 

240 source: FileSource_package 

241 """The weights file.""" 

242 

243 attachments: Annotated[ 

244 AttachmentsDescr | None, 

245 warn(None, "Weights entry depends on additional attachments.", ALERT), 

246 ] = None 

247 """Attachments that are specific to this weights entry.""" 

248 

249 authors: list[Author] | None = None 

250 """Authors 

251 Either the person(s) that have trained this model resulting in the original weights file. 

252 (If this is the initial weights entry, i.e. it does not have a `parent`) 

253 Or the person(s) who have converted the weights to this weights format. 

254 (If this is a child weight, i.e. it has a `parent` field) 

255 """ 

256 

257 dependencies: Annotated[ 

258 Dependencies | None, 

259 warn( 

260 None, 

261 "Custom dependencies ({value}) specified. Avoid this whenever possible " 

262 + "to allow execution in a wider range of software environments.", 

263 ), 

264 Field( 

265 examples=[ 

266 "conda:environment.yaml", 

267 "maven:./pom.xml", 

268 "pip:./requirements.txt", 

269 ] 

270 ), 

271 ] = None 

272 """Dependency manager and dependency file, specified as `<dependency manager>:<relative file path>`.""" 

273 

274 parent: Annotated[WeightsFormat | None, Field(examples=["pytorch_state_dict"])] = ( 

275 None 

276 ) 

277 """The source weights these weights were converted from. 

278 For example, if a model's weights were converted from the `pytorch_state_dict` format to `torchscript`, 

279 The `pytorch_state_dict` weights entry has no `parent` and is the parent of the `torchscript` weights. 

280 All weight entries except one (the initial set of weights resulting from training the model), 

281 need to have this field.""" 

282 

283 @model_validator(mode="after") 

284 def check_parent_is_not_self(self) -> Self: 

285 if self.type == self.parent: 

286 raise ValueError("Weights entry can't be it's own parent.") 

287 

288 return self 

289 

290 

291class KerasHdf5WeightsDescr(WeightsEntryDescrBase): 

292 type: ClassVar[WeightsFormat] = "keras_hdf5" 

293 weights_format_name: ClassVar[str] = "Keras HDF5" 

294 tensorflow_version: Version | None = None 

295 """TensorFlow version used to create these weights""" 

296 

297 @field_validator("tensorflow_version", mode="after") 

298 @classmethod 

299 def _tfv(cls, value: Any): 

300 if value is None: 

301 issue_warning( 

302 "missing. Please specify the TensorFlow version" 

303 + " these weights were created with.", 

304 value=value, 

305 severity=ALERT, 

306 field="tensorflow_version", 

307 ) 

308 return value 

309 

310 

311class OnnxWeightsDescr(WeightsEntryDescrBase): 

312 type: ClassVar[WeightsFormat] = "onnx" 

313 weights_format_name: ClassVar[str] = "ONNX" 

314 opset_version: Annotated[int, Ge(7)] | None = None 

315 """ONNX opset version""" 

316 

317 @field_validator("opset_version", mode="after") 

318 @classmethod 

319 def _ov(cls, value: Any): 

320 if value is None: 

321 issue_warning( 

322 "Missing ONNX opset version (aka ONNX opset number). " 

323 + "Please specify the ONNX opset version these weights were created" 

324 + " with.", 

325 value=value, 

326 severity=ALERT, 

327 field="opset_version", 

328 ) 

329 return value 

330 

331 

332class PytorchStateDictWeightsDescr(WeightsEntryDescrBase): 

333 type: ClassVar[WeightsFormat] = "pytorch_state_dict" 

334 weights_format_name: ClassVar[str] = "Pytorch State Dict" 

335 architecture: CustomCallable = Field( 

336 examples=["my_function.py:MyNetworkClass", "my_module.submodule.get_my_model"] 

337 ) 

338 """callable returning a torch.nn.Module instance. 

339 Local implementation: `<relative path to file>:<identifier of implementation within the file>`. 

340 Implementation in a dependency: `<dependency-package>.<[dependency-module]>.<identifier>`.""" 

341 

342 architecture_sha256: Annotated[ 

343 Sha256 | None, 

344 Field( 

345 description=( 

346 "The SHA256 of the architecture source file, if the architecture is not" 

347 " defined in a module listed in `dependencies`\n" 

348 ) 

349 + SHA256_HINT, 

350 ), 

351 ] = None 

352 """The SHA256 of the architecture source file, 

353 if the architecture is not defined in a module listed in `dependencies`""" 

354 

355 @model_validator(mode="after") 

356 def check_architecture_sha256(self) -> Self: 

357 if isinstance(self.architecture, CallableFromFile): 

358 if self.architecture_sha256 is None: 

359 raise ValueError( 

360 "Missing required `architecture_sha256` for `architecture` with" 

361 + " source file." 

362 ) 

363 elif self.architecture_sha256 is not None: 

364 raise ValueError( 

365 "Got `architecture_sha256` for architecture that does not have a source" 

366 + " file." 

367 ) 

368 

369 return self 

370 

371 kwargs: dict[str, Any] = Field( 

372 default_factory=cast(Callable[[], dict[str, Any]], dict) 

373 ) 

374 """key word arguments for the `architecture` callable""" 

375 

376 pytorch_version: Version | None = None 

377 """Version of the PyTorch library used. 

378 If `depencencies` is specified it should include pytorch and the verison has to match. 

379 (`dependencies` overrules `pytorch_version`)""" 

380 

381 @field_validator("pytorch_version", mode="after") 

382 @classmethod 

383 def _ptv(cls, value: Any): 

384 if value is None: 

385 issue_warning( 

386 "missing. Please specify the PyTorch version these" 

387 + " PyTorch state dict weights were created with.", 

388 value=value, 

389 severity=ALERT, 

390 field="pytorch_version", 

391 ) 

392 return value 

393 

394 

395class TorchscriptWeightsDescr(WeightsEntryDescrBase): 

396 type: ClassVar[WeightsFormat] = "torchscript" 

397 weights_format_name: ClassVar[str] = "TorchScript" 

398 pytorch_version: Version | None = None 

399 """Version of the PyTorch library used.""" 

400 

401 @field_validator("pytorch_version", mode="after") 

402 @classmethod 

403 def _ptv(cls, value: Any): 

404 if value is None: 

405 issue_warning( 

406 "missing. Please specify the PyTorch version these" 

407 + " Torchscript weights were created with.", 

408 value=value, 

409 severity=ALERT, 

410 field="pytorch_version", 

411 ) 

412 return value 

413 

414 

415class TensorflowJsWeightsDescr(WeightsEntryDescrBase): 

416 type: ClassVar[WeightsFormat] = "tensorflow_js" 

417 weights_format_name: ClassVar[str] = "Tensorflow.js" 

418 tensorflow_version: Version | None = None 

419 """Version of the TensorFlow library used.""" 

420 

421 @field_validator("tensorflow_version", mode="after") 

422 @classmethod 

423 def _tfv(cls, value: Any): 

424 if value is None: 

425 issue_warning( 

426 "missing. Please specify the TensorFlow version" 

427 + " these TensorflowJs weights were created with.", 

428 value=value, 

429 severity=ALERT, 

430 field="tensorflow_version", 

431 ) 

432 return value 

433 

434 source: FileSource_package 

435 """The multi-file weights. 

436 All required files/folders should be a zip archive.""" 

437 

438 

439class TensorflowSavedModelBundleWeightsDescr(WeightsEntryDescrBase): 

440 type: ClassVar[WeightsFormat] = "tensorflow_saved_model_bundle" 

441 weights_format_name: ClassVar[str] = "Tensorflow Saved Model" 

442 tensorflow_version: Version | None = None 

443 """Version of the TensorFlow library used.""" 

444 

445 @field_validator("tensorflow_version", mode="after") 

446 @classmethod 

447 def _tfv(cls, value: Any): 

448 if value is None: 

449 issue_warning( 

450 "missing. Please specify the TensorFlow version" 

451 + " these Tensorflow saved model bundle weights were created with.", 

452 value=value, 

453 severity=ALERT, 

454 field="tensorflow_version", 

455 ) 

456 return value 

457 

458 

459class WeightsDescr(Node): 

460 keras_hdf5: KerasHdf5WeightsDescr | None = None 

461 onnx: OnnxWeightsDescr | None = None 

462 pytorch_state_dict: PytorchStateDictWeightsDescr | None = None 

463 tensorflow_js: TensorflowJsWeightsDescr | None = None 

464 tensorflow_saved_model_bundle: TensorflowSavedModelBundleWeightsDescr | None = None 

465 torchscript: TorchscriptWeightsDescr | None = None 

466 

467 @model_validator(mode="after") 

468 def check_one_entry(self) -> Self: 

469 if all( 

470 entry is None 

471 for entry in [ 

472 self.keras_hdf5, 

473 self.onnx, 

474 self.pytorch_state_dict, 

475 self.tensorflow_js, 

476 self.tensorflow_saved_model_bundle, 

477 self.torchscript, 

478 ] 

479 ): 

480 raise ValueError("Missing weights entry") 

481 

482 return self 

483 

484 def __getitem__( 

485 self, 

486 key: WeightsFormat, 

487 ): 

488 if key == "keras_hdf5": 

489 ret = self.keras_hdf5 

490 elif key == "onnx": 

491 ret = self.onnx 

492 elif key == "pytorch_state_dict": 

493 ret = self.pytorch_state_dict 

494 elif key == "tensorflow_js": 

495 ret = self.tensorflow_js 

496 elif key == "tensorflow_saved_model_bundle": 

497 ret = self.tensorflow_saved_model_bundle 

498 elif key == "torchscript": 

499 ret = self.torchscript 

500 else: 

501 raise KeyError(key) 

502 

503 if ret is None: 

504 raise KeyError(key) 

505 

506 return ret 

507 

508 @property 

509 def available_formats(self): 

510 return { 

511 **({} if self.keras_hdf5 is None else {"keras_hdf5": self.keras_hdf5}), 

512 **({} if self.onnx is None else {"onnx": self.onnx}), 

513 **( 

514 {} 

515 if self.pytorch_state_dict is None 

516 else {"pytorch_state_dict": self.pytorch_state_dict} 

517 ), 

518 **( 

519 {} 

520 if self.tensorflow_js is None 

521 else {"tensorflow_js": self.tensorflow_js} 

522 ), 

523 **( 

524 {} 

525 if self.tensorflow_saved_model_bundle is None 

526 else { 

527 "tensorflow_saved_model_bundle": self.tensorflow_saved_model_bundle 

528 } 

529 ), 

530 **({} if self.torchscript is None else {"torchscript": self.torchscript}), 

531 } 

532 

533 @property 

534 def missing_formats(self): 

535 return { 

536 wf for wf in get_args(WeightsFormat) if wf not in self.available_formats 

537 } 

538 

539 

540class ParameterizedInputShape(Node): 

541 """A sequence of valid shapes given by `shape_k = min + k * step for k in {0, 1, ...}`.""" 

542 

543 min: NotEmpty[list[int]] 

544 """The minimum input shape""" 

545 

546 step: NotEmpty[list[int]] 

547 """The minimum shape change""" 

548 

549 def __len__(self) -> int: 

550 return len(self.min) 

551 

552 @model_validator(mode="after") 

553 def matching_lengths(self) -> Self: 

554 if len(self.min) != len(self.step): 

555 raise ValueError("`min` and `step` required to have the same length") 

556 

557 return self 

558 

559 

560class ImplicitOutputShape(Node): 

561 """Output tensor shape depending on an input tensor shape. 

562 `shape(output_tensor) = shape(input_tensor) * scale + 2 * offset`""" 

563 

564 reference_tensor: TensorName 

565 """Name of the reference tensor.""" 

566 

567 scale: NotEmpty[list[float | None]] 

568 """output_pix/input_pix for each dimension. 

569 'null' values indicate new dimensions, whose length is defined by 2*`offset`""" 

570 

571 offset: NotEmpty[list[int | Annotated[float, MultipleOf(0.5)]]] 

572 """Position of origin wrt to input.""" 

573 

574 def __len__(self) -> int: 

575 return len(self.scale) 

576 

577 @model_validator(mode="after") 

578 def matching_lengths(self) -> Self: 

579 if len(self.scale) != len(self.offset): 

580 raise ValueError( 

581 f"scale {self.scale} has to have same length as offset {self.offset}!" 

582 ) 

583 # if we have an expanded dimension, make sure that it's offet is not zero 

584 for sc, off in zip(self.scale, self.offset): 

585 if sc is None and not off: 

586 raise ValueError("`offset` must not be zero if `scale` is none/zero") 

587 

588 return self 

589 

590 

591class TensorDescrBase(Node): 

592 name: TensorName 

593 """Tensor name. No duplicates are allowed.""" 

594 

595 description: str = "" 

596 

597 axes: AxesStr 

598 """Axes identifying characters. Same length and order as the axes in `shape`. 

599 | axis | description | 

600 | --- | --- | 

601 | b | batch (groups multiple samples) | 

602 | i | instance/index/element | 

603 | t | time | 

604 | c | channel | 

605 | z | spatial dimension z | 

606 | y | spatial dimension y | 

607 | x | spatial dimension x | 

608 """ 

609 

610 data_range: ( 

611 tuple[Annotated[float, AllowInfNan(True)], Annotated[float, AllowInfNan(True)]] 

612 | None 

613 ) = None 

614 """Tuple `(minimum, maximum)` specifying the allowed range of the data in this tensor. 

615 If not specified, the full data range that can be expressed in `data_type` is allowed.""" 

616 

617 

618class BinarizeKwargs(KwargsNode): 

619 """key word arguments for `BinarizeDescr`""" 

620 

621 threshold: float 

622 """The fixed threshold""" 

623 

624 

625class BinarizeDescr(NodeWithExplicitlySetFields): 

626 """BinarizeDescr the tensor with a fixed `BinarizeKwargs.threshold`. 

627 Values above the threshold will be set to one, values below the threshold to zero. 

628 """ 

629 

630 implemented_name: ClassVar[Literal["binarize"]] = "binarize" 

631 if TYPE_CHECKING: 

632 name: Literal["binarize"] = "binarize" 

633 else: 

634 name: Literal["binarize"] 

635 

636 kwargs: BinarizeKwargs 

637 

638 

639class ClipKwargs(KwargsNode): 

640 """key word arguments for `ClipDescr`""" 

641 

642 min: float 

643 """minimum value for clipping""" 

644 max: float 

645 """maximum value for clipping""" 

646 

647 

648class ClipDescr(NodeWithExplicitlySetFields): 

649 """Clip tensor values to a range. 

650 

651 Set tensor values below `ClipKwargs.min` to `ClipKwargs.min` 

652 and above `ClipKwargs.max` to `ClipKwargs.max`. 

653 """ 

654 

655 implemented_name: ClassVar[Literal["clip"]] = "clip" 

656 if TYPE_CHECKING: 

657 name: Literal["clip"] = "clip" 

658 else: 

659 name: Literal["clip"] 

660 

661 kwargs: ClipKwargs 

662 

663 

664class ScaleLinearKwargs(KwargsNode): 

665 """key word arguments for `ScaleLinearDescr`""" 

666 

667 axes: Annotated[AxesInCZYX | None, Field(examples=["xy"])] = None 

668 """The subset of axes to scale jointly. 

669 For example xy to scale the two image axes for 2d data jointly.""" 

670 

671 gain: float | list[float] = 1.0 

672 """multiplicative factor""" 

673 

674 offset: float | list[float] = 0.0 

675 """additive term""" 

676 

677 @model_validator(mode="after") 

678 def either_gain_or_offset(self) -> Self: 

679 if ( 

680 self.gain == 1.0 

681 or isinstance(self.gain, list) 

682 and all(g == 1.0 for g in self.gain) 

683 ) and ( 

684 self.offset == 0.0 

685 or isinstance(self.offset, list) 

686 and all(off == 0.0 for off in self.offset) 

687 ): 

688 raise ValueError( 

689 "Redunt linear scaling not allowd. Set `gain` != 1.0 and/or `offset` !=" 

690 + " 0.0." 

691 ) 

692 

693 return self 

694 

695 

696class ScaleLinearDescr(NodeWithExplicitlySetFields): 

697 """Fixed linear scaling.""" 

698 

699 implemented_name: ClassVar[Literal["scale_linear"]] = "scale_linear" 

700 if TYPE_CHECKING: 

701 name: Literal["scale_linear"] = "scale_linear" 

702 else: 

703 name: Literal["scale_linear"] 

704 

705 kwargs: ScaleLinearKwargs 

706 

707 

708class SigmoidDescr(NodeWithExplicitlySetFields): 

709 """The logistic sigmoid funciton, a.k.a. expit function.""" 

710 

711 implemented_name: ClassVar[Literal["sigmoid"]] = "sigmoid" 

712 if TYPE_CHECKING: 

713 name: Literal["sigmoid"] = "sigmoid" 

714 else: 

715 name: Literal["sigmoid"] 

716 

717 @property 

718 def kwargs(self) -> KwargsNode: 

719 """empty kwargs""" 

720 return KwargsNode() 

721 

722 

723class ZeroMeanUnitVarianceKwargs(KwargsNode): 

724 """key word arguments for `ZeroMeanUnitVarianceDescr`""" 

725 

726 mode: Literal["fixed", "per_dataset", "per_sample"] = "fixed" 

727 """Mode for computing mean and variance. 

728 | mode | description | 

729 | ----------- | ------------------------------------ | 

730 | fixed | Fixed values for mean and variance | 

731 | per_dataset | Compute for the entire dataset | 

732 | per_sample | Compute for each sample individually | 

733 """ 

734 axes: Annotated[AxesInCZYX, Field(examples=["xy"])] 

735 """The subset of axes to normalize jointly. 

736 For example `xy` to normalize the two image axes for 2d data jointly.""" 

737 

738 mean: Annotated[ 

739 float | NotEmpty[list[float]] | None, Field(examples=[(1.1, 2.2, 3.3)]) 

740 ] = None 

741 """The mean value(s) to use for `mode: fixed`. 

742 For example `[1.1, 2.2, 3.3]` in the case of a 3 channel image with `axes: xy`.""" 

743 # todo: check if means match input axes (for mode 'fixed') 

744 

745 std: Annotated[ 

746 float | NotEmpty[list[float]] | None, Field(examples=[(0.1, 0.2, 0.3)]) 

747 ] = None 

748 """The standard deviation values to use for `mode: fixed`. Analogous to mean.""" 

749 

750 eps: Annotated[float, Interval(gt=0, le=0.1)] = 1e-6 

751 """epsilon for numeric stability: `out = (tensor - mean) / (std + eps)`.""" 

752 

753 @model_validator(mode="after") 

754 def mean_and_std_match_mode(self) -> Self: 

755 if self.mode == "fixed" and (self.mean is None or self.std is None): 

756 raise ValueError("`mean` and `std` are required for `mode: fixed`.") 

757 elif self.mode != "fixed" and (self.mean is not None or self.std is not None): 

758 raise ValueError(f"`mean` and `std` not allowed for `mode: {self.mode}`") 

759 

760 return self 

761 

762 

763class ZeroMeanUnitVarianceDescr(NodeWithExplicitlySetFields): 

764 """Subtract mean and divide by variance.""" 

765 

766 implemented_name: ClassVar[Literal["zero_mean_unit_variance"]] = ( 

767 "zero_mean_unit_variance" 

768 ) 

769 if TYPE_CHECKING: 

770 name: Literal["zero_mean_unit_variance"] = "zero_mean_unit_variance" 

771 else: 

772 name: Literal["zero_mean_unit_variance"] 

773 

774 kwargs: ZeroMeanUnitVarianceKwargs 

775 

776 

777class ScaleRangeKwargs(KwargsNode): 

778 """key word arguments for `ScaleRangeDescr` 

779 

780 For `min_percentile`=0.0 (the default) and `max_percentile`=100 (the default) 

781 this processing step normalizes data to the [0, 1] intervall. 

782 For other percentiles the normalized values will partially be outside the [0, 1] 

783 intervall. Use `ScaleRange` followed by `ClipDescr` if you want to limit the 

784 normalized values to a range. 

785 """ 

786 

787 mode: Literal["per_dataset", "per_sample"] 

788 """Mode for computing percentiles. 

789 | mode | description | 

790 | ----------- | ------------------------------------ | 

791 | per_dataset | compute for the entire dataset | 

792 | per_sample | compute for each sample individually | 

793 """ 

794 axes: Annotated[AxesInCZYX, Field(examples=["xy"])] 

795 """The subset of axes to normalize jointly. 

796 For example xy to normalize the two image axes for 2d data jointly.""" 

797 

798 min_percentile: Annotated[int | float, Interval(ge=0, lt=100)] = 0.0 

799 """The lower percentile used to determine the value to align with zero.""" 

800 

801 max_percentile: Annotated[int | float, Interval(gt=1, le=100)] = 100.0 

802 """The upper percentile used to determine the value to align with one. 

803 Has to be bigger than `min_percentile`. 

804 The range is 1 to 100 instead of 0 to 100 to avoid mistakenly 

805 accepting percentiles specified in the range 0.0 to 1.0.""" 

806 

807 @model_validator(mode="after") 

808 def min_smaller_max(self, info: ValidationInfo) -> Self: 

809 if self.min_percentile >= self.max_percentile: 

810 raise ValueError( 

811 f"min_percentile {self.min_percentile} >= max_percentile" 

812 + f" {self.max_percentile}" 

813 ) 

814 

815 return self 

816 

817 eps: Annotated[float, Interval(gt=0, le=0.1)] = 1e-6 

818 """Epsilon for numeric stability. 

819 `out = (tensor - v_lower) / (v_upper - v_lower + eps)`; 

820 with `v_lower,v_upper` values at the respective percentiles.""" 

821 

822 reference_tensor: TensorName | None = None 

823 """Tensor name to compute the percentiles from. Default: The tensor itself. 

824 For any tensor in `inputs` only input tensor references are allowed. 

825 For a tensor in `outputs` only input tensor refereences are allowed if `mode: per_dataset`""" 

826 

827 

828class ScaleRangeDescr(NodeWithExplicitlySetFields): 

829 """Scale with percentiles.""" 

830 

831 implemented_name: ClassVar[Literal["scale_range"]] = "scale_range" 

832 if TYPE_CHECKING: 

833 name: Literal["scale_range"] = "scale_range" 

834 else: 

835 name: Literal["scale_range"] 

836 

837 kwargs: ScaleRangeKwargs 

838 

839 

840class ScaleMeanVarianceKwargs(KwargsNode): 

841 """key word arguments for `ScaleMeanVarianceDescr`""" 

842 

843 mode: Literal["per_dataset", "per_sample"] 

844 """Mode for computing mean and variance. 

845 | mode | description | 

846 | ----------- | ------------------------------------ | 

847 | per_dataset | Compute for the entire dataset | 

848 | per_sample | Compute for each sample individually | 

849 """ 

850 

851 reference_tensor: TensorName 

852 """Name of tensor to match.""" 

853 

854 axes: Annotated[AxesInCZYX | None, Field(examples=["xy"])] = None 

855 """The subset of axes to scale jointly. 

856 For example xy to normalize the two image axes for 2d data jointly. 

857 Default: scale all non-batch axes jointly.""" 

858 

859 eps: Annotated[float, Interval(gt=0, le=0.1)] = 1e-6 

860 """Epsilon for numeric stability: 

861 "`out = (tensor - mean) / (std + eps) * (ref_std + eps) + ref_mean.""" 

862 

863 

864class ScaleMeanVarianceDescr(NodeWithExplicitlySetFields): 

865 """Scale the tensor s.t. its mean and variance match a reference tensor.""" 

866 

867 implemented_name: ClassVar[Literal["scale_mean_variance"]] = "scale_mean_variance" 

868 if TYPE_CHECKING: 

869 name: Literal["scale_mean_variance"] = "scale_mean_variance" 

870 else: 

871 name: Literal["scale_mean_variance"] 

872 

873 kwargs: ScaleMeanVarianceKwargs 

874 

875 

876PreprocessingDescr = Annotated[ 

877 BinarizeDescr 

878 | ClipDescr 

879 | ScaleLinearDescr 

880 | SigmoidDescr 

881 | ZeroMeanUnitVarianceDescr 

882 | ScaleRangeDescr, 

883 Discriminator("name"), 

884] 

885PostprocessingDescr = Annotated[ 

886 BinarizeDescr 

887 | ClipDescr 

888 | ScaleLinearDescr 

889 | SigmoidDescr 

890 | ZeroMeanUnitVarianceDescr 

891 | ScaleRangeDescr 

892 | ScaleMeanVarianceDescr, 

893 Discriminator("name"), 

894] 

895 

896 

897class InputTensorDescr(TensorDescrBase): 

898 data_type: Literal["float32", "uint8", "uint16"] 

899 """For now an input tensor is expected to be given as `float32`. 

900 The data flow in bioimage.io models is explained 

901 [in this diagram.](https://docs.google.com/drawings/d/1FTw8-Rn6a6nXdkZ_SkMumtcjvur9mtIhRqLwnKqZNHM/edit).""" 

902 

903 shape: Annotated[ 

904 Sequence[int] | ParameterizedInputShape, 

905 Field( 

906 examples=[(1, 512, 512, 1), {"min": (1, 64, 64, 1), "step": (0, 32, 32, 0)}] 

907 ), 

908 ] 

909 """Specification of input tensor shape.""" 

910 

911 preprocessing: list[PreprocessingDescr] = Field( 

912 default_factory=cast( # TODO: (py>3.8) use list[PreprocessingDesr] 

913 Callable[[], list[PreprocessingDescr]], list 

914 ) 

915 ) 

916 """Description of how this input should be preprocessed.""" 

917 

918 @model_validator(mode="after") 

919 def zero_batch_step_and_one_batch_size(self) -> Self: 

920 bidx = self.axes.find("b") 

921 if bidx == -1: 

922 return self 

923 

924 if isinstance(self.shape, ParameterizedInputShape): 

925 step = self.shape.step 

926 shape = self.shape.min 

927 if step[bidx] != 0: 

928 raise ValueError( 

929 "Input shape step has to be zero in the batch dimension (the batch" 

930 + " dimension can always be increased, but `step` should specify how" 

931 + " to increase the minimal shape to find the largest single batch" 

932 + " shape)" 

933 ) 

934 else: 

935 shape = self.shape 

936 

937 if shape[bidx] != 1: 

938 raise ValueError("Input shape has to be 1 in the batch dimension b.") 

939 

940 return self 

941 

942 @model_validator(mode="after") 

943 def validate_preprocessing_kwargs(self) -> Self: 

944 for p in self.preprocessing: 

945 kwargs_axes = p.kwargs.get("axes") 

946 if isinstance(kwargs_axes, str) and any( 

947 a not in self.axes for a in kwargs_axes 

948 ): 

949 raise ValueError("`kwargs.axes` needs to be subset of `axes`") 

950 

951 return self 

952 

953 

954class OutputTensorDescr(TensorDescrBase): 

955 data_type: Literal[ 

956 "float32", 

957 "float64", 

958 "uint8", 

959 "int8", 

960 "uint16", 

961 "int16", 

962 "uint32", 

963 "int32", 

964 "uint64", 

965 "int64", 

966 "bool", 

967 ] 

968 """Data type. 

969 The data flow in bioimage.io models is explained 

970 [in this diagram.](https://docs.google.com/drawings/d/1FTw8-Rn6a6nXdkZ_SkMumtcjvur9mtIhRqLwnKqZNHM/edit).""" 

971 

972 @property 

973 def dtype(self): 

974 """alias for `data_type`""" 

975 return self.data_type 

976 

977 shape: Sequence[int] | ImplicitOutputShape 

978 """Output tensor shape.""" 

979 

980 halo: Sequence[int] | None = None 

981 """The `halo` that should be cropped from the output tensor to avoid boundary effects. 

982 The `halo` is to be cropped from both sides, i.e. `shape_after_crop = shape - 2 * halo`. 

983 To document a `halo` that is already cropped by the model `shape.offset` has to be used instead.""" 

984 

985 postprocessing: list[PostprocessingDescr] = Field( 

986 default_factory=cast(Callable[[], list[PostprocessingDescr]], list) 

987 ) 

988 """Description of how this output should be postprocessed.""" 

989 

990 @model_validator(mode="after") 

991 def matching_halo_length(self) -> Self: 

992 if self.halo and len(self.halo) != len(self.shape): 

993 raise ValueError( 

994 f"halo {self.halo} has to have same length as shape {self.shape}!" 

995 ) 

996 

997 return self 

998 

999 @model_validator(mode="after") 

1000 def validate_postprocessing_kwargs(self) -> Self: 

1001 for p in self.postprocessing: 

1002 kwargs_axes = p.kwargs.get("axes", "") 

1003 if not isinstance(kwargs_axes, str): 

1004 raise ValueError(f"Expected {kwargs_axes} to be a string") 

1005 

1006 if any(a not in self.axes for a in kwargs_axes): 

1007 raise ValueError("`kwargs.axes` needs to be subset of axes") 

1008 

1009 return self 

1010 

1011 

1012KnownRunMode = Literal["deepimagej"] 

1013 

1014 

1015class RunMode(Node): 

1016 name: Annotated[ 

1017 KnownRunMode | str, warn(KnownRunMode, "Unknown run mode '{value}'.") 

1018 ] 

1019 """Run mode name""" 

1020 

1021 kwargs: dict[str, Any] = Field( 

1022 default_factory=cast(Callable[[], dict[str, Any]], dict) 

1023 ) 

1024 """Run mode specific key word arguments""" 

1025 

1026 

1027class LinkedModel(Node): 

1028 """Reference to a bioimage.io model.""" 

1029 

1030 id: Annotated[ModelId, Field(examples=["affable-shark", "ambitious-sloth"])] 

1031 """A valid model `id` from the bioimage.io collection.""" 

1032 

1033 version_number: int | None = None 

1034 """version number (n-th published version, not the semantic version) of linked model""" 

1035 

1036 

1037def package_weights( 

1038 value: Node, # Union[v0_4.WeightsDescr, v0_5.WeightsDescr] 

1039 handler: SerializerFunctionWrapHandler, 

1040 info: SerializationInfo, 

1041): 

1042 ctxt = packaging_context_var.get() 

1043 if ctxt is not None and ctxt.weights_priority_order is not None: 

1044 for wf in ctxt.weights_priority_order: 

1045 w = getattr(value, wf, None) 

1046 if w is not None: 

1047 break 

1048 else: 

1049 raise ValueError( 

1050 "None of the weight formats in `weights_priority_order`" 

1051 + f" ({ctxt.weights_priority_order}) is present in the given model." 

1052 ) 

1053 

1054 assert isinstance(w, Node), type(w) 

1055 # construct WeightsDescr with new single weight format entry 

1056 new_w = w.model_construct(**{k: v for k, v in w if k != "parent"}) 

1057 value = value.model_construct(None, **{wf: new_w}) 

1058 

1059 return handler(value) 

1060 

1061 

1062class ModelDescr(GenericModelDescrBase): 

1063 """Specification of the fields used in a bioimage.io-compliant RDF that describes AI models with pretrained weights. 

1064 

1065 These fields are typically stored in a YAML file which we call a model resource description file (model RDF). 

1066 """ 

1067 

1068 implemented_format_version: ClassVar[Literal["0.4.10"]] = "0.4.10" 

1069 if TYPE_CHECKING: 

1070 format_version: Literal["0.4.10"] = "0.4.10" 

1071 else: 

1072 format_version: Literal["0.4.10"] 

1073 """Version of the bioimage.io model description specification used. 

1074 When creating a new model always use the latest micro/patch version described here. 

1075 The `format_version` is important for any consumer software to understand how to parse the fields. 

1076 """ 

1077 

1078 implemented_type: ClassVar[Literal["model"]] = "model" 

1079 if TYPE_CHECKING: 

1080 type: Literal["model"] = "model" 

1081 else: 

1082 type: Literal["model"] 

1083 """Specialized resource type 'model'""" 

1084 

1085 id: ModelId | None = None 

1086 """bioimage.io-wide unique resource identifier 

1087 assigned by bioimage.io; version **un**specific.""" 

1088 

1089 authors: NotEmpty[ # pyright: ignore[reportGeneralTypeIssues] # make mandatory 

1090 list[Author] 

1091 ] 

1092 """The authors are the creators of the model RDF and the primary points of contact.""" 

1093 

1094 documentation: Annotated[ 

1095 FileSource_package, 

1096 Field( 

1097 examples=[ 

1098 "https://raw.githubusercontent.com/bioimage-io/spec-bioimage-io/main/example_descriptions/models/unet2d_nuclei_broad/README.md", 

1099 "README.md", 

1100 ], 

1101 ), 

1102 ] 

1103 """URL or relative path to a markdown file with additional documentation. 

1104 The recommended documentation file name is `README.md`. An `.md` suffix is mandatory. 

1105 The documentation should include a '[#[#]]# Validation' (sub)section 

1106 with details on how to quantitatively validate the model on unseen data.""" 

1107 

1108 inputs: NotEmpty[list[InputTensorDescr]] 

1109 """Describes the input tensors expected by this model.""" 

1110 

1111 license: Annotated[ 

1112 LicenseId | str, 

1113 warn(LicenseId, "Unknown license id '{value}'."), 

1114 Field(examples=["CC0-1.0", "MIT", "BSD-2-Clause"]), 

1115 ] 

1116 """A [SPDX license identifier](https://spdx.org/licenses/). 

1117 We do notsupport custom license beyond the SPDX license list, if you need that please 

1118 [open a GitHub issue](https://github.com/bioimage-io/spec-bioimage-io/issues/new/choose 

1119 ) to discuss your intentions with the community.""" 

1120 

1121 name: Annotated[ 

1122 str, 

1123 MinLen(1), 

1124 warn(Annotated[str, MinLen(5)], "Name shorter than 5 characters.", INFO), 

1125 warn(Annotated[str, MaxLen(64)], "Name longer than 64 characters.", INFO), 

1126 ] 

1127 """A human-readable name of this model. 

1128 It should be no longer than 64 characters and only contain letter, number, underscore, minus or space characters.""" 

1129 

1130 outputs: NotEmpty[list[OutputTensorDescr]] 

1131 """Describes the output tensors.""" 

1132 

1133 @field_validator("inputs", "outputs") 

1134 @classmethod 

1135 def unique_tensor_descr_names( 

1136 cls, value: Sequence[InputTensorDescr | OutputTensorDescr] 

1137 ) -> Sequence[InputTensorDescr | OutputTensorDescr]: 

1138 unique_names = {str(v.name) for v in value} 

1139 if len(unique_names) != len(value): 

1140 raise ValueError("Duplicate tensor descriptor names") 

1141 

1142 return value 

1143 

1144 @model_validator(mode="after") 

1145 def unique_io_names(self) -> Self: 

1146 unique_names = {str(ss.name) for s in (self.inputs, self.outputs) for ss in s} 

1147 if len(unique_names) != (len(self.inputs) + len(self.outputs)): 

1148 raise ValueError("Duplicate tensor descriptor names across inputs/outputs") 

1149 

1150 return self 

1151 

1152 @model_validator(mode="after") 

1153 def minimum_shape2valid_output(self) -> Self: 

1154 tensors_by_name: dict[TensorName, InputTensorDescr | OutputTensorDescr] = { 

1155 t.name: t for t in self.inputs + self.outputs 

1156 } 

1157 

1158 for out in self.outputs: 

1159 if isinstance(out.shape, ImplicitOutputShape): 

1160 ndim_ref = len(tensors_by_name[out.shape.reference_tensor].shape) 

1161 ndim_out_ref = len( 

1162 [scale for scale in out.shape.scale if scale is not None] 

1163 ) 

1164 if ndim_ref != ndim_out_ref: 

1165 expanded_dim_note = ( 

1166 " Note that expanded dimensions (`scale`: null) are not" 

1167 + f" counted for {out.name}'sdimensionality here." 

1168 if None in out.shape.scale 

1169 else "" 

1170 ) 

1171 raise ValueError( 

1172 f"Referenced tensor '{out.shape.reference_tensor}' with" 

1173 + f" {ndim_ref} dimensions does not match output tensor" 

1174 + f" '{out.name}' with" 

1175 + f" {ndim_out_ref} dimensions.{expanded_dim_note}" 

1176 ) 

1177 

1178 min_out_shape = self._get_min_shape(out, tensors_by_name) 

1179 if out.halo: 

1180 halo = out.halo 

1181 halo_msg = f" for halo {out.halo}" 

1182 else: 

1183 halo = [0] * len(min_out_shape) 

1184 halo_msg = "" 

1185 

1186 if any(s - 2 * h < 1 for s, h in zip(min_out_shape, halo)): 

1187 raise ValueError( 

1188 f"Minimal shape {min_out_shape} of output {out.name} is too" 

1189 + f" small{halo_msg}." 

1190 ) 

1191 

1192 return self 

1193 

1194 @classmethod 

1195 def _get_min_shape( 

1196 cls, 

1197 t: InputTensorDescr | OutputTensorDescr, 

1198 tensors_by_name: dict[TensorName, InputTensorDescr | OutputTensorDescr], 

1199 ) -> Sequence[int]: 

1200 """output with subtracted halo has to result in meaningful output even for the minimal input 

1201 see https://github.com/bioimage-io/spec-bioimage-io/issues/392 

1202 """ 

1203 if isinstance(t.shape, Sequence): 

1204 return t.shape 

1205 elif isinstance(t.shape, ParameterizedInputShape): 

1206 return t.shape.min 

1207 elif isinstance(t.shape, ImplicitOutputShape): 

1208 pass 

1209 else: 

1210 assert_never(t.shape) 

1211 

1212 ref_shape = cls._get_min_shape( 

1213 tensors_by_name[t.shape.reference_tensor], tensors_by_name 

1214 ) 

1215 

1216 if None not in t.shape.scale: 

1217 scale: Sequence[float, ...] = t.shape.scale # type: ignore 

1218 else: 

1219 expanded_dims = [idx for idx, sc in enumerate(t.shape.scale) if sc is None] 

1220 new_ref_shape: list[int] = [] 

1221 for idx in range(len(t.shape.scale)): 

1222 ref_idx = idx - sum(int(exp < idx) for exp in expanded_dims) 

1223 new_ref_shape.append(1 if idx in expanded_dims else ref_shape[ref_idx]) 

1224 

1225 ref_shape = new_ref_shape 

1226 assert len(ref_shape) == len(t.shape.scale) 

1227 scale = [0.0 if sc is None else sc for sc in t.shape.scale] 

1228 

1229 offset = t.shape.offset 

1230 assert len(offset) == len(scale) 

1231 return [int(rs * s + 2 * off) for rs, s, off in zip(ref_shape, scale, offset)] 

1232 

1233 @model_validator(mode="after") 

1234 def validate_tensor_references_in_inputs(self) -> Self: 

1235 for t in self.inputs: 

1236 for proc in t.preprocessing: 

1237 if "reference_tensor" not in proc.kwargs: 

1238 continue 

1239 

1240 ref_tensor = proc.kwargs["reference_tensor"] 

1241 if ref_tensor is not None and str(ref_tensor) not in { 

1242 str(t.name) for t in self.inputs 

1243 }: 

1244 raise ValueError(f"'{ref_tensor}' not found in inputs") 

1245 

1246 if ref_tensor == t.name: 

1247 raise ValueError( 

1248 f"invalid self reference for preprocessing of tensor {t.name}" 

1249 ) 

1250 

1251 return self 

1252 

1253 @model_validator(mode="after") 

1254 def validate_tensor_references_in_outputs(self) -> Self: 

1255 for t in self.outputs: 

1256 for proc in t.postprocessing: 

1257 if "reference_tensor" not in proc.kwargs: 

1258 continue 

1259 ref_tensor = proc.kwargs["reference_tensor"] 

1260 if ref_tensor is not None and str(ref_tensor) not in { 

1261 str(t.name) for t in self.inputs 

1262 }: 

1263 raise ValueError(f"{ref_tensor} not found in inputs") 

1264 

1265 return self 

1266 

1267 packaged_by: list[Author] = Field( 

1268 default_factory=cast(Callable[[], list[Author]], list) 

1269 ) 

1270 """The persons that have packaged and uploaded this model. 

1271 Only required if those persons differ from the `authors`.""" 

1272 

1273 parent: LinkedModel | None = None 

1274 """The model from which this model is derived, e.g. by fine-tuning the weights.""" 

1275 

1276 @field_validator("parent", mode="before") 

1277 @classmethod 

1278 def ignore_url_parent(cls, parent: Any): 

1279 if isinstance(parent, dict): 

1280 return None 

1281 

1282 else: 

1283 return parent 

1284 

1285 run_mode: RunMode | None = None 

1286 """Custom run mode for this model: for more complex prediction procedures like test time 

1287 data augmentation that currently cannot be expressed in the specification. 

1288 No standard run modes are defined yet.""" 

1289 

1290 sample_inputs: list[FileSource_package] = Field( 

1291 default_factory=cast(Callable[[], list[FileSource]], list) 

1292 ) 

1293 """URLs/relative paths to sample inputs to illustrate possible inputs for the model, 

1294 for example stored as PNG or TIFF images. 

1295 The sample files primarily serve to inform a human user about an example use case""" 

1296 

1297 sample_outputs: list[FileSource_package] = Field( 

1298 default_factory=cast(Callable[[], list[FileSource]], list) 

1299 ) 

1300 """URLs/relative paths to sample outputs corresponding to the `sample_inputs`.""" 

1301 

1302 test_inputs: NotEmpty[ 

1303 list[Annotated[FileSource_package, WithSuffix(".npy", case_sensitive=True)]] 

1304 ] 

1305 """Test input tensors compatible with the `inputs` description for a **single test case**. 

1306 This means if your model has more than one input, you should provide one URL/relative path for each input. 

1307 Each test input should be a file with an ndarray in 

1308 [numpy.lib file format](https://numpy.org/doc/stable/reference/generated/numpy.lib.format.html#module-numpy.lib.format). 

1309 The extension must be '.npy'.""" 

1310 

1311 test_outputs: NotEmpty[ 

1312 list[Annotated[FileSource_package, WithSuffix(".npy", case_sensitive=True)]] 

1313 ] 

1314 """Analog to `test_inputs`.""" 

1315 

1316 timestamp: Datetime 

1317 """Timestamp in [ISO 8601](#https://en.wikipedia.org/wiki/ISO_8601) format 

1318 with a few restrictions listed [here](https://docs.python.org/3/library/datetime.html#datetime.datetime.fromisoformat).""" 

1319 

1320 training_data: LinkedDataset | DatasetDescr | None = None 

1321 """The dataset used to train this model""" 

1322 

1323 weights: Annotated[WeightsDescr, WrapSerializer(package_weights)] 

1324 """The weights for this model. 

1325 Weights can be given for different formats, but should otherwise be equivalent. 

1326 The available weight formats determine which consumers can use this model.""" 

1327 

1328 @model_validator(mode="before") 

1329 @classmethod 

1330 def _convert_from_older_format( 

1331 cls, data: BioimageioYamlContent, / 

1332 ) -> BioimageioYamlContent: 

1333 convert_from_older_format(data) 

1334 return data 

1335 

1336 @staticmethod 

1337 def get_batch_size(tensor_sizes: Mapping[TensorName, Mapping[AxesStr, int]]) -> int: 

1338 batch_size = 1 

1339 tensor_with_batchsize: TensorName | None = None 

1340 for tid in tensor_sizes: 

1341 for aid, s in tensor_sizes[tid].items(): 

1342 if aid != "b" or s == 1 or s == batch_size: 

1343 continue 

1344 

1345 if batch_size != 1: 

1346 assert tensor_with_batchsize is not None 

1347 raise ValueError( 

1348 f"batch size mismatch for tensors '{tensor_with_batchsize}' ({batch_size}) and '{tid}' ({s})" 

1349 ) 

1350 

1351 batch_size = s 

1352 tensor_with_batchsize = tid 

1353 

1354 return batch_size 

1355 

1356 def get_output_tensor_sizes( 

1357 self, input_sizes: Mapping[TensorName, Mapping[AxesStr, int]] 

1358 ) -> dict[TensorName, dict[AxesStr, int]]: 

1359 """backport of model.v0_5.ModelDescr.get_output_tensor_sizes()""" 

1360 batch_size = self.get_batch_size(input_sizes) 

1361 input_descrs = {t.name: t for t in self.inputs} 

1362 stackable_input_axes: dict[AxesStr, int] = {} 

1363 stackable_input_axes_per_input: dict[TensorName, set[AxesStr]] = {} 

1364 for m, in_sizes in input_sizes.items(): 

1365 if m not in input_descrs: 

1366 logger.warning("Ignoring unexpected input tensor '{}'.", m) 

1367 continue 

1368 

1369 stackable_input_axes_per_input[m] = set() 

1370 for a, s in in_sizes.items(): 

1371 if a not in input_descrs[m].axes: 

1372 stackable_input_axes_per_input[m].add(a) 

1373 if a not in stackable_input_axes: 

1374 stackable_input_axes[a] = s 

1375 elif stackable_input_axes[a] != s: 

1376 raise ValueError( 

1377 f"Input axis '{a}' has inconsistent sizes across input tensors: {stackable_input_axes[a]} vs {s}" 

1378 ) 

1379 

1380 if not all( 

1381 stackable_per_input == set(stackable_input_axes) 

1382 for stackable_per_input in stackable_input_axes_per_input.values() 

1383 ): 

1384 raise ValueError( 

1385 "Not all input tensors have the same set of additonal axes that could otherwise be treated as a stacked batch dimension. " 

1386 + f"Extra axes per input: {stackable_input_axes_per_input}" 

1387 ) 

1388 

1389 input_sizes_refs = { 

1390 ipt.name: { 

1391 ax: (ax, input_sizes[ipt.name][ax]) 

1392 for ax in ipt.axes 

1393 if ax != "b" and ax in input_sizes[ipt.name] 

1394 } 

1395 for ipt in self.inputs 

1396 if ipt.name in input_sizes 

1397 } 

1398 output_sizes: dict[TensorName, dict[AxesStr, int]] = { 

1399 out.name: {} for out in self.outputs 

1400 } 

1401 for out in self.outputs: 

1402 for i, ax in enumerate(out.axes): 

1403 if ax == "b": 

1404 s = batch_size 

1405 elif isinstance(out.shape, Sequence): 

1406 s = out.shape[i] 

1407 elif isinstance(out.shape, ImplicitOutputShape): 

1408 if ( 

1409 out.shape.reference_tensor not in input_sizes_refs 

1410 or ax not in input_sizes_refs[out.shape.reference_tensor] 

1411 ): 

1412 logger.warning( 

1413 "Output axis {}.{} references input axis {}.{}, which is not present in the provided input sizes." 

1414 + " Assuming the output is optional and not produced for this input.", 

1415 out.name, 

1416 ax, 

1417 out.shape.reference_tensor, 

1418 ax, 

1419 ) 

1420 continue 

1421 

1422 _ref_ax, ref_size = input_sizes_refs[out.shape.reference_tensor][ax] 

1423 s = ( 

1424 ref_size * scale 

1425 if (scale := out.shape.scale[i]) is not None 

1426 else 0 

1427 ) + 2 * out.shape.offset[i] 

1428 assert s == int(s) 

1429 s = int(s) 

1430 else: 

1431 assert_never(out.shape) 

1432 

1433 output_sizes[out.name][ax] = s 

1434 if ax == "b": 

1435 # insert extra input dimensions to be passed through like the batch axis 

1436 for a, s in stackable_input_axes.items(): 

1437 output_sizes[out.name][a] = s 

1438 

1439 return output_sizes 

1440 

1441 def get_input_test_arrays(self) -> list[NDArray[Any]]: 

1442 data = [load_array(ipt) for ipt in self.test_inputs] 

1443 assert all(isinstance(d, np.ndarray) for d in data) 

1444 return data 

1445 

1446 def get_output_test_arrays(self) -> list[NDArray[Any]]: 

1447 data = [load_array(out) for out in self.test_outputs] 

1448 assert all(isinstance(d, np.ndarray) for d in data) 

1449 return data