nidavellir-tools 0.1.0__tar.gz
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- nidavellir_tools-0.1.0/.gitignore +14 -0
- nidavellir_tools-0.1.0/CHANGELOG.md +17 -0
- nidavellir_tools-0.1.0/Dockerfile +11 -0
- nidavellir_tools-0.1.0/LICENSE +22 -0
- nidavellir_tools-0.1.0/PKG-INFO +115 -0
- nidavellir_tools-0.1.0/README.md +77 -0
- nidavellir_tools-0.1.0/pyproject.toml +80 -0
- nidavellir_tools-0.1.0/src/nidavellir_tools/__init__.py +10 -0
- nidavellir_tools-0.1.0/src/nidavellir_tools/build_model_package.py +293 -0
- nidavellir_tools-0.1.0/src/nidavellir_tools/cli.py +59 -0
- nidavellir_tools-0.1.0/src/nidavellir_tools/create_sample_tensors.py +94 -0
- nidavellir_tools-0.1.0/src/nidavellir_tools/examples/README.md +19 -0
- nidavellir_tools-0.1.0/src/nidavellir_tools/examples/model-package.example.yaml +70 -0
- nidavellir_tools-0.1.0/src/nidavellir_tools/model-card-template.md +18 -0
- nidavellir_tools-0.1.0/src/nidavellir_tools/model_package_registry.py +468 -0
- nidavellir_tools-0.1.0/src/nidavellir_tools/run_artifacts.py +170 -0
- nidavellir_tools-0.1.0/src/nidavellir_tools/sample_tensors.py +113 -0
- nidavellir_tools-0.1.0/tests/test_cli.py +17 -0
- nidavellir_tools-0.1.0/tests/test_export_model.py +178 -0
- nidavellir_tools-0.1.0/tests/test_model_registry.py +187 -0
- nidavellir_tools-0.1.0/tests/test_run_artifacts.py +101 -0
- nidavellir_tools-0.1.0/tests/test_sample_tensors.py +52 -0
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
# Changelog
|
|
2
|
+
|
|
3
|
+
All notable changes to this project will be documented here.
|
|
4
|
+
|
|
5
|
+
## [Unreleased]
|
|
6
|
+
|
|
7
|
+
## [0.1.0] - 2026-09-13
|
|
8
|
+
|
|
9
|
+
- Extract the reusable Nidavellir tools from `nuxnet-training`.
|
|
10
|
+
- Adopt a `src/` Python package layout and `pyproject.toml` build.
|
|
11
|
+
- Add installable CLI entry points and a standalone container definition.
|
|
12
|
+
- Build BioImage.IO-compatible model packages with provenance and test tensors.
|
|
13
|
+
- Stage, inspect, validate, and publish model packages.
|
|
14
|
+
- Load parent packages and export fine-tuned child packages.
|
|
15
|
+
|
|
16
|
+
[Unreleased]: https://github.com/luiskuhn/nidavellir-tools/compare/v0.1.0...HEAD
|
|
17
|
+
[0.1.0]: https://github.com/luiskuhn/nidavellir-tools/releases/tag/v0.1.0
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2021, Lukas Heumos
|
|
4
|
+
Copyright (c) 2026, Luis Kuhn Cuellar (Quantitative Biology Center)
|
|
5
|
+
|
|
6
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
7
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
8
|
+
in the Software without restriction, including without limitation the rights
|
|
9
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
10
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
11
|
+
furnished to do so, subject to the following conditions:
|
|
12
|
+
|
|
13
|
+
The above copyright notice and this permission notice shall be included in all
|
|
14
|
+
copies or substantial portions of the Software.
|
|
15
|
+
|
|
16
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
17
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
18
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
19
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
20
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
21
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
22
|
+
SOFTWARE.
|
|
@@ -0,0 +1,115 @@
|
|
|
1
|
+
Metadata-Version: 2.5
|
|
2
|
+
Name: nidavellir-tools
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Reusable model packaging and transfer-learning utilities
|
|
5
|
+
Project-URL: Homepage, https://github.com/luiskuhn/nidavellir-tools
|
|
6
|
+
Project-URL: Issues, https://github.com/luiskuhn/nidavellir-tools/issues
|
|
7
|
+
Project-URL: Repository, https://github.com/luiskuhn/nidavellir-tools
|
|
8
|
+
Author: Luis Kuhn Cuellar
|
|
9
|
+
License-Expression: MIT
|
|
10
|
+
License-File: LICENSE
|
|
11
|
+
Keywords: bioimageio,machine-learning,model-packaging,pytorch,transfer-learning
|
|
12
|
+
Classifier: Development Status :: 3 - Alpha
|
|
13
|
+
Classifier: Intended Audience :: Developers
|
|
14
|
+
Classifier: Intended Audience :: Science/Research
|
|
15
|
+
Classifier: Programming Language :: Python :: 3
|
|
16
|
+
Classifier: Programming Language :: Python :: 3.10
|
|
17
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
18
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
19
|
+
Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
|
|
20
|
+
Requires-Python: >=3.10
|
|
21
|
+
Requires-Dist: numpy<3,>=1.26
|
|
22
|
+
Requires-Dist: pyyaml<7,>=6
|
|
23
|
+
Requires-Dist: tifffile>=2024.8
|
|
24
|
+
Requires-Dist: torch<3,>=2.4
|
|
25
|
+
Provides-Extra: bioimageio
|
|
26
|
+
Requires-Dist: bioimageio-core<0.12,>=0.11; extra == 'bioimageio'
|
|
27
|
+
Provides-Extra: dev
|
|
28
|
+
Requires-Dist: build>=1.2; extra == 'dev'
|
|
29
|
+
Requires-Dist: pytest-cov>=5; extra == 'dev'
|
|
30
|
+
Requires-Dist: pytest>=8; extra == 'dev'
|
|
31
|
+
Requires-Dist: ruff>=0.6; extra == 'dev'
|
|
32
|
+
Requires-Dist: twine>=5; extra == 'dev'
|
|
33
|
+
Provides-Extra: huggingface
|
|
34
|
+
Requires-Dist: huggingface-hub<2,>=0.24; extra == 'huggingface'
|
|
35
|
+
Provides-Extra: mlflow
|
|
36
|
+
Requires-Dist: mlflow<3,>=2.16; extra == 'mlflow'
|
|
37
|
+
Description-Content-Type: text/markdown
|
|
38
|
+
|
|
39
|
+
# Nidavellir Tools
|
|
40
|
+
|
|
41
|
+
Nidavellir Tools packages trained PyTorch models with reproducibility metadata,
|
|
42
|
+
portable test tensors, and BioImage.IO-compatible artifacts. It also stages and
|
|
43
|
+
loads packaged models for transfer-learning runs.
|
|
44
|
+
|
|
45
|
+
The library is intentionally independent of any model architecture, training
|
|
46
|
+
framework, microscopy modality, or dataset. Consuming projects remain
|
|
47
|
+
responsible for their model, DataLoader, augmentation, model RDF, and model card.
|
|
48
|
+
|
|
49
|
+
> **Status:** the initial API may change before version 1.0.
|
|
50
|
+
|
|
51
|
+
## Installation
|
|
52
|
+
|
|
53
|
+
Install the core package from PyPI:
|
|
54
|
+
|
|
55
|
+
```bash
|
|
56
|
+
python -m pip install nidavellir-tools
|
|
57
|
+
```
|
|
58
|
+
|
|
59
|
+
Optional integrations are installed explicitly, for example:
|
|
60
|
+
|
|
61
|
+
```bash
|
|
62
|
+
python -m pip install "nidavellir-tools[bioimageio,huggingface,mlflow]"
|
|
63
|
+
```
|
|
64
|
+
|
|
65
|
+
For development from a checkout, use `python -m pip install -e ".[dev]"`.
|
|
66
|
+
|
|
67
|
+
## Command line
|
|
68
|
+
|
|
69
|
+
```bash
|
|
70
|
+
nidavellir --help
|
|
71
|
+
nidavellir build --help
|
|
72
|
+
nidavellir samples --help
|
|
73
|
+
nidavellir inspect --help
|
|
74
|
+
nidavellir validate --help
|
|
75
|
+
```
|
|
76
|
+
|
|
77
|
+
The existing command names remain available during migration:
|
|
78
|
+
|
|
79
|
+
```bash
|
|
80
|
+
nidavellir-build --help
|
|
81
|
+
nidavellir-registry --help
|
|
82
|
+
nidavellir-samples --help
|
|
83
|
+
```
|
|
84
|
+
|
|
85
|
+
## Image axes
|
|
86
|
+
|
|
87
|
+
Sample TIFF creation supports model tensors described by explicit BioImage.IO
|
|
88
|
+
axes. Standard 2D and 3D layouts include `BCYX` and `BCZYX`. The exact NPY
|
|
89
|
+
tensors retain the complete model input/output boundary, including the batch
|
|
90
|
+
dimension; TIFFs are presentation samples derived from one selected batch item.
|
|
91
|
+
|
|
92
|
+
## Containerized development
|
|
93
|
+
|
|
94
|
+
```bash
|
|
95
|
+
docker build -t nidavellir-tools:dev .
|
|
96
|
+
docker run --rm nidavellir-tools:dev --help
|
|
97
|
+
```
|
|
98
|
+
|
|
99
|
+
Run tests without modifying the host Python environment:
|
|
100
|
+
|
|
101
|
+
```bash
|
|
102
|
+
docker run --rm \
|
|
103
|
+
-v "$PWD:/workspace" \
|
|
104
|
+
-w /workspace \
|
|
105
|
+
python:3.12-slim \
|
|
106
|
+
bash -lc 'python -m pip install -e ".[dev]" && pytest -q'
|
|
107
|
+
```
|
|
108
|
+
|
|
109
|
+
## Origin
|
|
110
|
+
|
|
111
|
+
The project was extracted from
|
|
112
|
+
[`luiskuhn/nuxnet-training`](https://github.com/luiskuhn/nuxnet-training), where
|
|
113
|
+
the workflow was first exercised for 3D nuclei segmentation and parent-to-child
|
|
114
|
+
fine-tuning. The standalone package is derived from that implementation while
|
|
115
|
+
removing NuxNet-specific assumptions.
|
|
@@ -0,0 +1,77 @@
|
|
|
1
|
+
# Nidavellir Tools
|
|
2
|
+
|
|
3
|
+
Nidavellir Tools packages trained PyTorch models with reproducibility metadata,
|
|
4
|
+
portable test tensors, and BioImage.IO-compatible artifacts. It also stages and
|
|
5
|
+
loads packaged models for transfer-learning runs.
|
|
6
|
+
|
|
7
|
+
The library is intentionally independent of any model architecture, training
|
|
8
|
+
framework, microscopy modality, or dataset. Consuming projects remain
|
|
9
|
+
responsible for their model, DataLoader, augmentation, model RDF, and model card.
|
|
10
|
+
|
|
11
|
+
> **Status:** the initial API may change before version 1.0.
|
|
12
|
+
|
|
13
|
+
## Installation
|
|
14
|
+
|
|
15
|
+
Install the core package from PyPI:
|
|
16
|
+
|
|
17
|
+
```bash
|
|
18
|
+
python -m pip install nidavellir-tools
|
|
19
|
+
```
|
|
20
|
+
|
|
21
|
+
Optional integrations are installed explicitly, for example:
|
|
22
|
+
|
|
23
|
+
```bash
|
|
24
|
+
python -m pip install "nidavellir-tools[bioimageio,huggingface,mlflow]"
|
|
25
|
+
```
|
|
26
|
+
|
|
27
|
+
For development from a checkout, use `python -m pip install -e ".[dev]"`.
|
|
28
|
+
|
|
29
|
+
## Command line
|
|
30
|
+
|
|
31
|
+
```bash
|
|
32
|
+
nidavellir --help
|
|
33
|
+
nidavellir build --help
|
|
34
|
+
nidavellir samples --help
|
|
35
|
+
nidavellir inspect --help
|
|
36
|
+
nidavellir validate --help
|
|
37
|
+
```
|
|
38
|
+
|
|
39
|
+
The existing command names remain available during migration:
|
|
40
|
+
|
|
41
|
+
```bash
|
|
42
|
+
nidavellir-build --help
|
|
43
|
+
nidavellir-registry --help
|
|
44
|
+
nidavellir-samples --help
|
|
45
|
+
```
|
|
46
|
+
|
|
47
|
+
## Image axes
|
|
48
|
+
|
|
49
|
+
Sample TIFF creation supports model tensors described by explicit BioImage.IO
|
|
50
|
+
axes. Standard 2D and 3D layouts include `BCYX` and `BCZYX`. The exact NPY
|
|
51
|
+
tensors retain the complete model input/output boundary, including the batch
|
|
52
|
+
dimension; TIFFs are presentation samples derived from one selected batch item.
|
|
53
|
+
|
|
54
|
+
## Containerized development
|
|
55
|
+
|
|
56
|
+
```bash
|
|
57
|
+
docker build -t nidavellir-tools:dev .
|
|
58
|
+
docker run --rm nidavellir-tools:dev --help
|
|
59
|
+
```
|
|
60
|
+
|
|
61
|
+
Run tests without modifying the host Python environment:
|
|
62
|
+
|
|
63
|
+
```bash
|
|
64
|
+
docker run --rm \
|
|
65
|
+
-v "$PWD:/workspace" \
|
|
66
|
+
-w /workspace \
|
|
67
|
+
python:3.12-slim \
|
|
68
|
+
bash -lc 'python -m pip install -e ".[dev]" && pytest -q'
|
|
69
|
+
```
|
|
70
|
+
|
|
71
|
+
## Origin
|
|
72
|
+
|
|
73
|
+
The project was extracted from
|
|
74
|
+
[`luiskuhn/nuxnet-training`](https://github.com/luiskuhn/nuxnet-training), where
|
|
75
|
+
the workflow was first exercised for 3D nuclei segmentation and parent-to-child
|
|
76
|
+
fine-tuning. The standalone package is derived from that implementation while
|
|
77
|
+
removing NuxNet-specific assumptions.
|
|
@@ -0,0 +1,80 @@
|
|
|
1
|
+
[build-system]
|
|
2
|
+
requires = ["hatchling>=1.26"]
|
|
3
|
+
build-backend = "hatchling.build"
|
|
4
|
+
|
|
5
|
+
[project]
|
|
6
|
+
name = "nidavellir-tools"
|
|
7
|
+
version = "0.1.0"
|
|
8
|
+
description = "Reusable model packaging and transfer-learning utilities"
|
|
9
|
+
readme = "README.md"
|
|
10
|
+
requires-python = ">=3.10"
|
|
11
|
+
license = "MIT"
|
|
12
|
+
license-files = ["LICENSE"]
|
|
13
|
+
authors = [
|
|
14
|
+
{ name = "Luis Kuhn Cuellar" },
|
|
15
|
+
]
|
|
16
|
+
keywords = ["bioimageio", "machine-learning", "model-packaging", "pytorch", "transfer-learning"]
|
|
17
|
+
classifiers = [
|
|
18
|
+
"Development Status :: 3 - Alpha",
|
|
19
|
+
"Intended Audience :: Developers",
|
|
20
|
+
"Intended Audience :: Science/Research",
|
|
21
|
+
"Programming Language :: Python :: 3",
|
|
22
|
+
"Programming Language :: Python :: 3.10",
|
|
23
|
+
"Programming Language :: Python :: 3.11",
|
|
24
|
+
"Programming Language :: Python :: 3.12",
|
|
25
|
+
"Topic :: Scientific/Engineering :: Artificial Intelligence",
|
|
26
|
+
]
|
|
27
|
+
dependencies = [
|
|
28
|
+
"numpy>=1.26,<3",
|
|
29
|
+
"PyYAML>=6,<7",
|
|
30
|
+
"tifffile>=2024.8",
|
|
31
|
+
"torch>=2.4,<3",
|
|
32
|
+
]
|
|
33
|
+
|
|
34
|
+
[project.optional-dependencies]
|
|
35
|
+
bioimageio = ["bioimageio.core>=0.11,<0.12"]
|
|
36
|
+
huggingface = ["huggingface-hub>=0.24,<2"]
|
|
37
|
+
mlflow = ["mlflow>=2.16,<3"]
|
|
38
|
+
dev = [
|
|
39
|
+
"build>=1.2",
|
|
40
|
+
"pytest>=8",
|
|
41
|
+
"pytest-cov>=5",
|
|
42
|
+
"ruff>=0.6",
|
|
43
|
+
"twine>=5",
|
|
44
|
+
]
|
|
45
|
+
|
|
46
|
+
[project.scripts]
|
|
47
|
+
nidavellir = "nidavellir_tools.cli:main"
|
|
48
|
+
nidavellir-build = "nidavellir_tools.build_model_package:main"
|
|
49
|
+
nidavellir-registry = "nidavellir_tools.model_package_registry:main"
|
|
50
|
+
nidavellir-samples = "nidavellir_tools.create_sample_tensors:main"
|
|
51
|
+
|
|
52
|
+
[project.urls]
|
|
53
|
+
Homepage = "https://github.com/luiskuhn/nidavellir-tools"
|
|
54
|
+
Issues = "https://github.com/luiskuhn/nidavellir-tools/issues"
|
|
55
|
+
Repository = "https://github.com/luiskuhn/nidavellir-tools"
|
|
56
|
+
|
|
57
|
+
[tool.hatch.build.targets.wheel]
|
|
58
|
+
packages = ["src/nidavellir_tools"]
|
|
59
|
+
|
|
60
|
+
[tool.hatch.build.targets.sdist]
|
|
61
|
+
include = [
|
|
62
|
+
"/src",
|
|
63
|
+
"/tests",
|
|
64
|
+
"/README.md",
|
|
65
|
+
"/LICENSE",
|
|
66
|
+
"/CHANGELOG.md",
|
|
67
|
+
"/Dockerfile",
|
|
68
|
+
"/pyproject.toml",
|
|
69
|
+
]
|
|
70
|
+
|
|
71
|
+
[tool.pytest.ini_options]
|
|
72
|
+
addopts = "-ra"
|
|
73
|
+
testpaths = ["tests"]
|
|
74
|
+
|
|
75
|
+
[tool.ruff]
|
|
76
|
+
line-length = 100
|
|
77
|
+
target-version = "py310"
|
|
78
|
+
|
|
79
|
+
[tool.ruff.lint]
|
|
80
|
+
select = ["E", "F", "I", "UP"]
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
"""Reusable model-package and transfer-learning utilities."""
|
|
2
|
+
|
|
3
|
+
from importlib.metadata import PackageNotFoundError, version
|
|
4
|
+
|
|
5
|
+
try:
|
|
6
|
+
__version__ = version("nidavellir-tools")
|
|
7
|
+
except PackageNotFoundError: # Source checkout before installation.
|
|
8
|
+
__version__ = "0.1.0"
|
|
9
|
+
|
|
10
|
+
__all__ = ["__version__"]
|
|
@@ -0,0 +1,293 @@
|
|
|
1
|
+
#!/usr/bin/env python3
|
|
2
|
+
"""Build a FAIR BioImage.IO/Hugging Face package from a declarative RDF template."""
|
|
3
|
+
|
|
4
|
+
from __future__ import annotations
|
|
5
|
+
|
|
6
|
+
import argparse
|
|
7
|
+
import json
|
|
8
|
+
import platform
|
|
9
|
+
import shutil
|
|
10
|
+
from collections.abc import Sequence
|
|
11
|
+
from datetime import datetime, timezone
|
|
12
|
+
from pathlib import Path
|
|
13
|
+
from typing import Any
|
|
14
|
+
|
|
15
|
+
import numpy as np
|
|
16
|
+
import torch
|
|
17
|
+
import yaml
|
|
18
|
+
|
|
19
|
+
from nidavellir_tools.model_package_registry import (
|
|
20
|
+
_checkpoint_state,
|
|
21
|
+
_digest,
|
|
22
|
+
_resolve_callable,
|
|
23
|
+
_write_zip,
|
|
24
|
+
verify,
|
|
25
|
+
)
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
def _descriptors(value: Any):
|
|
29
|
+
if isinstance(value, dict):
|
|
30
|
+
if isinstance(value.get("source"), str):
|
|
31
|
+
yield value
|
|
32
|
+
for nested in value.values():
|
|
33
|
+
yield from _descriptors(nested)
|
|
34
|
+
elif isinstance(value, list):
|
|
35
|
+
for nested in value:
|
|
36
|
+
yield from _descriptors(nested)
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
def _copy_declared_artifacts(rdf: dict[str, Any], base: Path, output: Path) -> None:
|
|
40
|
+
"""Copy local template artifacts, preserving their RDF-relative locations."""
|
|
41
|
+
state_descriptor = rdf.get("weights", {}).get("pytorch_state_dict", {})
|
|
42
|
+
descriptors = [
|
|
43
|
+
state_descriptor.get("architecture"),
|
|
44
|
+
state_descriptor.get("dependencies"),
|
|
45
|
+
*rdf.get("covers", []),
|
|
46
|
+
]
|
|
47
|
+
for descriptor in descriptors:
|
|
48
|
+
if not isinstance(descriptor, dict) or not isinstance(descriptor.get("source"), str):
|
|
49
|
+
continue
|
|
50
|
+
relative = Path(descriptor["source"])
|
|
51
|
+
if relative.is_absolute() or ".." in relative.parts:
|
|
52
|
+
raise ValueError(f"RDF artifact source must be a safe relative path: {relative}")
|
|
53
|
+
source = base / relative
|
|
54
|
+
destination = output / relative
|
|
55
|
+
if source.is_file():
|
|
56
|
+
destination.parent.mkdir(parents=True, exist_ok=True)
|
|
57
|
+
shutil.copy2(source, destination)
|
|
58
|
+
sample_descriptors = (
|
|
59
|
+
tensor.get("sample_tensor")
|
|
60
|
+
for field in ("inputs", "outputs")
|
|
61
|
+
for tensor in rdf.get(field, [])
|
|
62
|
+
if isinstance(tensor, dict)
|
|
63
|
+
)
|
|
64
|
+
for descriptor in sample_descriptors:
|
|
65
|
+
if not isinstance(descriptor, dict) or not isinstance(descriptor.get("source"), str):
|
|
66
|
+
raise ValueError("every RDF tensor requires a local sample_tensor source")
|
|
67
|
+
relative = Path(descriptor["source"])
|
|
68
|
+
if relative.is_absolute() or ".." in relative.parts:
|
|
69
|
+
raise ValueError(f"RDF artifact source must be a safe relative path: {relative}")
|
|
70
|
+
source = base / relative
|
|
71
|
+
if not source.is_file():
|
|
72
|
+
raise FileNotFoundError(f"declared sample_tensor artifact not found: {source}")
|
|
73
|
+
destination = output / relative
|
|
74
|
+
destination.parent.mkdir(parents=True, exist_ok=True)
|
|
75
|
+
shutil.copy2(source, destination)
|
|
76
|
+
|
|
77
|
+
|
|
78
|
+
def _refresh_hashes(rdf: dict[str, Any], output: Path) -> None:
|
|
79
|
+
for descriptor in _descriptors(rdf):
|
|
80
|
+
artifact = output / descriptor["source"]
|
|
81
|
+
if artifact.is_file():
|
|
82
|
+
descriptor["sha256"] = _digest(artifact)
|
|
83
|
+
|
|
84
|
+
|
|
85
|
+
def _tensor_descriptors(rdf: dict[str, Any], field: str) -> list[dict[str, Any]]:
|
|
86
|
+
tensors = rdf.get(field)
|
|
87
|
+
if not isinstance(tensors, list) or not tensors:
|
|
88
|
+
raise ValueError(f"specification requires at least one RDF {field} tensor")
|
|
89
|
+
descriptors = [tensor.get("test_tensor") for tensor in tensors]
|
|
90
|
+
if not all(
|
|
91
|
+
isinstance(descriptor, dict) and isinstance(descriptor.get("source"), str)
|
|
92
|
+
for descriptor in descriptors
|
|
93
|
+
):
|
|
94
|
+
raise ValueError(f"every RDF {field} tensor requires a local test_tensor source")
|
|
95
|
+
return descriptors
|
|
96
|
+
|
|
97
|
+
|
|
98
|
+
def _as_paths(value: Path | list[Path]) -> list[Path]:
|
|
99
|
+
return value if isinstance(value, list) else [value]
|
|
100
|
+
|
|
101
|
+
|
|
102
|
+
def build_model_package(
|
|
103
|
+
specification: Path,
|
|
104
|
+
checkpoint: Path,
|
|
105
|
+
test_input: Path | list[Path],
|
|
106
|
+
test_output: Path | list[Path],
|
|
107
|
+
model_card: Path,
|
|
108
|
+
output: Path,
|
|
109
|
+
*,
|
|
110
|
+
provenance: Path | None = None,
|
|
111
|
+
state_dict_key: str | None = None,
|
|
112
|
+
strip_prefix: str = "",
|
|
113
|
+
trace_input: Path | None = None,
|
|
114
|
+
extra_files: list[Path] | None = None,
|
|
115
|
+
overwrite: bool = False,
|
|
116
|
+
) -> tuple[Path, Path]:
|
|
117
|
+
"""Build and verify a package without assuming a domain, task, or architecture."""
|
|
118
|
+
if output.exists() and any(output.iterdir()):
|
|
119
|
+
if not overwrite:
|
|
120
|
+
raise FileExistsError(f"output directory is not empty: {output}")
|
|
121
|
+
shutil.rmtree(output)
|
|
122
|
+
rdf = yaml.safe_load(specification.read_text(encoding="utf-8"))
|
|
123
|
+
if not isinstance(rdf, dict) or rdf.get("type") != "model":
|
|
124
|
+
raise ValueError("specification must be a BioImage.IO model RDF mapping")
|
|
125
|
+
output.mkdir(parents=True, exist_ok=True)
|
|
126
|
+
_copy_declared_artifacts(rdf, specification.parent, output)
|
|
127
|
+
|
|
128
|
+
weights = rdf.get("weights", {})
|
|
129
|
+
if set(weights) != {"pytorch_state_dict"}:
|
|
130
|
+
raise ValueError("prototype supports only pytorch_state_dict weights")
|
|
131
|
+
state_descriptor = weights.get("pytorch_state_dict")
|
|
132
|
+
if not isinstance(state_descriptor, dict):
|
|
133
|
+
raise ValueError("specification requires weights.pytorch_state_dict")
|
|
134
|
+
architecture = state_descriptor.get("architecture")
|
|
135
|
+
if not isinstance(architecture, dict):
|
|
136
|
+
raise ValueError("pytorch_state_dict requires an architecture descriptor")
|
|
137
|
+
architecture_source = architecture.get("source")
|
|
138
|
+
constructor = _resolve_callable(
|
|
139
|
+
architecture["callable"], output / architecture_source if architecture_source else None
|
|
140
|
+
)
|
|
141
|
+
model = constructor(**architecture.get("kwargs", {}))
|
|
142
|
+
model.load_state_dict(_checkpoint_state(checkpoint, state_dict_key, strip_prefix), strict=True)
|
|
143
|
+
model.eval()
|
|
144
|
+
input_paths, expected_paths = _as_paths(test_input), _as_paths(test_output)
|
|
145
|
+
if len(input_paths) != 1 or len(expected_paths) != 1:
|
|
146
|
+
raise ValueError("prototype inference verification supports exactly one input and output")
|
|
147
|
+
inference_input = torch.from_numpy(np.load(input_paths[0], allow_pickle=False))
|
|
148
|
+
expected_output = np.load(expected_paths[0], allow_pickle=False)
|
|
149
|
+
with torch.inference_mode():
|
|
150
|
+
actual_output = model(inference_input).detach().cpu().numpy()
|
|
151
|
+
if actual_output.shape != expected_output.shape or not np.allclose(
|
|
152
|
+
actual_output, expected_output, rtol=1e-4, atol=1e-5
|
|
153
|
+
):
|
|
154
|
+
raise ValueError("strictly reloaded state dict does not reproduce the supplied test output")
|
|
155
|
+
weight_path = output / state_descriptor["source"]
|
|
156
|
+
weight_path.parent.mkdir(parents=True, exist_ok=True)
|
|
157
|
+
torch.save(model.state_dict(), weight_path) # nosec B614: tensors only
|
|
158
|
+
|
|
159
|
+
for field, supplied in (("inputs", test_input), ("outputs", test_output)):
|
|
160
|
+
descriptors, paths = _tensor_descriptors(rdf, field), _as_paths(supplied)
|
|
161
|
+
if len(descriptors) != len(paths):
|
|
162
|
+
raise ValueError(
|
|
163
|
+
f"received {len(paths)} --test-{field[:-1]} values for "
|
|
164
|
+
f"{len(descriptors)} RDF {field}"
|
|
165
|
+
)
|
|
166
|
+
for path, descriptor in zip(paths, descriptors):
|
|
167
|
+
destination = output / descriptor["source"]
|
|
168
|
+
destination.parent.mkdir(parents=True, exist_ok=True)
|
|
169
|
+
shutil.copy2(path, destination)
|
|
170
|
+
|
|
171
|
+
documentation = rdf.get("documentation")
|
|
172
|
+
if not isinstance(documentation, dict) or not documentation.get("source"):
|
|
173
|
+
raise ValueError("specification requires a local documentation source")
|
|
174
|
+
documentation_path = output / documentation["source"]
|
|
175
|
+
documentation_path.parent.mkdir(parents=True, exist_ok=True)
|
|
176
|
+
shutil.copy2(model_card, documentation_path)
|
|
177
|
+
for extra in extra_files or []:
|
|
178
|
+
if not extra.is_file():
|
|
179
|
+
raise FileNotFoundError(f"extra package file not found: {extra}")
|
|
180
|
+
shutil.copy2(extra, output / extra.name)
|
|
181
|
+
|
|
182
|
+
rdf["timestamp"] = datetime.now(timezone.utc).replace(microsecond=0).isoformat()
|
|
183
|
+
rdf_path = output / "rdf.yaml"
|
|
184
|
+
_refresh_hashes(rdf, output)
|
|
185
|
+
rdf_path.write_text(yaml.safe_dump(rdf, sort_keys=False, allow_unicode=True), encoding="utf-8")
|
|
186
|
+
|
|
187
|
+
provenance_record = json.loads(provenance.read_text(encoding="utf-8")) if provenance else {}
|
|
188
|
+
provenance_record.update(
|
|
189
|
+
{
|
|
190
|
+
"schema": "https://w3id.org/ro/crate/1.1",
|
|
191
|
+
"created_utc": rdf["timestamp"],
|
|
192
|
+
"model": {
|
|
193
|
+
**provenance_record.get("model", {}),
|
|
194
|
+
"name": rdf.get("name"),
|
|
195
|
+
"version": rdf.get("version"),
|
|
196
|
+
},
|
|
197
|
+
"training": {
|
|
198
|
+
**provenance_record.get("training", {}),
|
|
199
|
+
"checkpoint_sha256": _digest(checkpoint),
|
|
200
|
+
},
|
|
201
|
+
"software": {
|
|
202
|
+
**provenance_record.get("software", {}),
|
|
203
|
+
"python": platform.python_version(),
|
|
204
|
+
"torch": str(torch.__version__),
|
|
205
|
+
"numpy": np.__version__,
|
|
206
|
+
},
|
|
207
|
+
}
|
|
208
|
+
)
|
|
209
|
+
(output / "provenance.json").write_text(
|
|
210
|
+
json.dumps(provenance_record, indent=2) + "\n", encoding="utf-8"
|
|
211
|
+
)
|
|
212
|
+
checksums = [
|
|
213
|
+
f"{_digest(path)} {path.relative_to(output)}"
|
|
214
|
+
for path in sorted(output.rglob("*"))
|
|
215
|
+
if path.is_file() and path.name != "SHA256SUMS"
|
|
216
|
+
]
|
|
217
|
+
(output / "SHA256SUMS").write_text("\n".join(checksums) + "\n", encoding="utf-8")
|
|
218
|
+
verify(output)
|
|
219
|
+
archive = output.with_suffix(".zip")
|
|
220
|
+
_write_zip(output, archive)
|
|
221
|
+
return output, archive
|
|
222
|
+
|
|
223
|
+
|
|
224
|
+
def build_parser() -> argparse.ArgumentParser:
|
|
225
|
+
parser = argparse.ArgumentParser(description=__doc__)
|
|
226
|
+
parser.add_argument("--run-artifacts-dir", type=Path)
|
|
227
|
+
parser.add_argument("--specification", type=Path)
|
|
228
|
+
parser.add_argument("--checkpoint", type=Path)
|
|
229
|
+
parser.add_argument("--test-input", type=Path, action="append")
|
|
230
|
+
parser.add_argument("--test-output", type=Path, action="append")
|
|
231
|
+
parser.add_argument("--model-card", type=Path)
|
|
232
|
+
parser.add_argument("--output-dir", type=Path, required=True)
|
|
233
|
+
parser.add_argument("--provenance", type=Path)
|
|
234
|
+
parser.add_argument("--state-dict-key")
|
|
235
|
+
parser.add_argument("--strip-prefix", default="")
|
|
236
|
+
parser.add_argument("--trace-input", type=Path)
|
|
237
|
+
parser.add_argument(
|
|
238
|
+
"--extra-file",
|
|
239
|
+
type=Path,
|
|
240
|
+
action="append",
|
|
241
|
+
default=[],
|
|
242
|
+
help="Additional file copied to the package root; may be repeated",
|
|
243
|
+
)
|
|
244
|
+
parser.add_argument("--overwrite", action="store_true")
|
|
245
|
+
return parser
|
|
246
|
+
|
|
247
|
+
|
|
248
|
+
def main(argv: Sequence[str] | None = None) -> None:
|
|
249
|
+
args = build_parser().parse_args(argv)
|
|
250
|
+
if args.run_artifacts_dir:
|
|
251
|
+
directory = args.run_artifacts_dir
|
|
252
|
+
conventional = {
|
|
253
|
+
"specification": directory / "model-package.yaml",
|
|
254
|
+
"checkpoint": directory / "weights.pt",
|
|
255
|
+
"test_input": [directory / "test-input.npy"],
|
|
256
|
+
"test_output": [directory / "test-output.npy"],
|
|
257
|
+
"model_card": directory / "README.md",
|
|
258
|
+
"provenance": directory / "run-provenance.json",
|
|
259
|
+
}
|
|
260
|
+
for name, value in conventional.items():
|
|
261
|
+
if getattr(args, name) is not None:
|
|
262
|
+
raise SystemExit(
|
|
263
|
+
f"--run-artifacts-dir cannot be combined with --{name.replace('_', '-')}"
|
|
264
|
+
)
|
|
265
|
+
setattr(args, name, value)
|
|
266
|
+
args.extra_file.append(directory / "cli-parameters.json")
|
|
267
|
+
missing = [
|
|
268
|
+
name
|
|
269
|
+
for name in ("specification", "checkpoint", "test_input", "test_output", "model_card")
|
|
270
|
+
if getattr(args, name) is None
|
|
271
|
+
]
|
|
272
|
+
if missing:
|
|
273
|
+
raise SystemExit("missing required packaging arguments: " + ", ".join(missing))
|
|
274
|
+
output, archive = build_model_package(
|
|
275
|
+
args.specification,
|
|
276
|
+
args.checkpoint,
|
|
277
|
+
args.test_input,
|
|
278
|
+
args.test_output,
|
|
279
|
+
args.model_card,
|
|
280
|
+
args.output_dir,
|
|
281
|
+
provenance=args.provenance,
|
|
282
|
+
state_dict_key=args.state_dict_key,
|
|
283
|
+
strip_prefix=args.strip_prefix,
|
|
284
|
+
trace_input=args.trace_input,
|
|
285
|
+
extra_files=args.extra_file,
|
|
286
|
+
overwrite=args.overwrite,
|
|
287
|
+
)
|
|
288
|
+
print(f"Model package: {output}")
|
|
289
|
+
print(f"BioImage.IO archive: {archive}")
|
|
290
|
+
|
|
291
|
+
|
|
292
|
+
if __name__ == "__main__":
|
|
293
|
+
main()
|