modelbinder 0.1.0__tar.gz → 0.2.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.
- {modelbinder-0.1.0 → modelbinder-0.2.0}/CHANGELOG.md +7 -0
- {modelbinder-0.1.0 → modelbinder-0.2.0}/PKG-INFO +1 -1
- modelbinder-0.2.0/docs/api.md +9 -0
- {modelbinder-0.1.0 → modelbinder-0.2.0}/docs/conf.py +3 -1
- {modelbinder-0.1.0 → modelbinder-0.2.0}/src/modelbinder/pretrained.py +2 -2
- {modelbinder-0.1.0 → modelbinder-0.2.0}/src/modelbinder/registry.py +10 -42
- {modelbinder-0.1.0 → modelbinder-0.2.0}/tests/test_pretrained.py +0 -2
- {modelbinder-0.1.0 → modelbinder-0.2.0}/tests/test_registry.py +7 -59
- modelbinder-0.1.0/docs/api.md +0 -11
- {modelbinder-0.1.0 → modelbinder-0.2.0}/.codecov.yaml +0 -0
- {modelbinder-0.1.0 → modelbinder-0.2.0}/.editorconfig +0 -0
- {modelbinder-0.1.0 → modelbinder-0.2.0}/.github/ISSUE_TEMPLATE/bug_report.yml +0 -0
- {modelbinder-0.1.0 → modelbinder-0.2.0}/.github/ISSUE_TEMPLATE/config.yml +0 -0
- {modelbinder-0.1.0 → modelbinder-0.2.0}/.github/ISSUE_TEMPLATE/feature_request.yml +0 -0
- {modelbinder-0.1.0 → modelbinder-0.2.0}/.github/dependabot.yml +0 -0
- {modelbinder-0.1.0 → modelbinder-0.2.0}/.github/workflows/build.yaml +0 -0
- {modelbinder-0.1.0 → modelbinder-0.2.0}/.github/workflows/release.yaml +0 -0
- {modelbinder-0.1.0 → modelbinder-0.2.0}/.github/workflows/test.yaml +0 -0
- {modelbinder-0.1.0 → modelbinder-0.2.0}/.gitignore +0 -0
- {modelbinder-0.1.0 → modelbinder-0.2.0}/.pre-commit-config.yaml +0 -0
- {modelbinder-0.1.0 → modelbinder-0.2.0}/.readthedocs.yaml +0 -0
- {modelbinder-0.1.0 → modelbinder-0.2.0}/.vscode/extensions.json +0 -0
- {modelbinder-0.1.0 → modelbinder-0.2.0}/.vscode/launch.json +0 -0
- {modelbinder-0.1.0 → modelbinder-0.2.0}/.vscode/settings.json +0 -0
- {modelbinder-0.1.0 → modelbinder-0.2.0}/LICENSE +0 -0
- {modelbinder-0.1.0 → modelbinder-0.2.0}/README.md +0 -0
- {modelbinder-0.1.0 → modelbinder-0.2.0}/biome.jsonc +0 -0
- {modelbinder-0.1.0 → modelbinder-0.2.0}/docs/_static/.gitkeep +0 -0
- {modelbinder-0.1.0 → modelbinder-0.2.0}/docs/_static/css/custom.css +0 -0
- {modelbinder-0.1.0 → modelbinder-0.2.0}/docs/_templates/.gitkeep +0 -0
- {modelbinder-0.1.0 → modelbinder-0.2.0}/docs/changelog.md +0 -0
- {modelbinder-0.1.0 → modelbinder-0.2.0}/docs/contributing.md +0 -0
- {modelbinder-0.1.0 → modelbinder-0.2.0}/docs/index.md +0 -0
- {modelbinder-0.1.0 → modelbinder-0.2.0}/docs/notebooks/example.ipynb +0 -0
- {modelbinder-0.1.0 → modelbinder-0.2.0}/docs/references.bib +0 -0
- {modelbinder-0.1.0 → modelbinder-0.2.0}/docs/references.md +0 -0
- {modelbinder-0.1.0 → modelbinder-0.2.0}/pyproject.toml +0 -0
- {modelbinder-0.1.0 → modelbinder-0.2.0}/src/modelbinder/__init__.py +0 -0
|
@@ -10,6 +10,13 @@ and this project adheres to [Semantic Versioning][].
|
|
|
10
10
|
|
|
11
11
|
## [Unreleased]
|
|
12
12
|
|
|
13
|
+
## [0.2.0] - 2026-11-26
|
|
14
|
+
|
|
15
|
+
### Removed
|
|
16
|
+
|
|
17
|
+
- Breaking: the module-level `registry.to_spec(config)` and `registry.parse(spec)`; use `config.to_spec()` and `Component.from_spec(spec)` (or `Family.from_spec(spec)`, which also checks the family)
|
|
18
|
+
- Breaking: `@component(..., builds=Impl)` and `registry.config_of`; what a config builds is typed by its `build` return annotation
|
|
19
|
+
|
|
13
20
|
## [0.1.0] - 2026-11-25
|
|
14
21
|
|
|
15
22
|
### Changed
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.5
|
|
2
2
|
Name: modelbinder
|
|
3
|
-
Version: 0.
|
|
3
|
+
Version: 0.2.0
|
|
4
4
|
Summary: Portable component specs and pretrained weights in the Hugging Face Hub layout
|
|
5
5
|
Project-URL: Documentation, https://modelbinder.readthedocs.io/
|
|
6
6
|
Project-URL: Homepage, https://github.com/theislab/modelbinder
|
|
@@ -39,7 +39,7 @@ needs_sphinx = "4.0"
|
|
|
39
39
|
|
|
40
40
|
html_context = {
|
|
41
41
|
"display_github": True, # Integrate GitHub
|
|
42
|
-
"github_user": "
|
|
42
|
+
"github_user": "theislab",
|
|
43
43
|
"github_repo": project,
|
|
44
44
|
"github_version": "main",
|
|
45
45
|
"conf_py_path": "/docs/",
|
|
@@ -101,6 +101,8 @@ intersphinx_mapping = {
|
|
|
101
101
|
"anndata": ("https://anndata.scverse.org/en/stable/", None),
|
|
102
102
|
"scanpy": ("https://scanpy.scverse.org/en/stable/", None),
|
|
103
103
|
"numpy": ("https://numpy.org/doc/stable/", None),
|
|
104
|
+
"pydantic": ("https://docs.pydantic.dev/latest/", None),
|
|
105
|
+
"torch": ("https://docs.pytorch.org/docs/stable/", None),
|
|
104
106
|
}
|
|
105
107
|
|
|
106
108
|
# List of patterns, relative to source directory, that match files and
|
|
@@ -18,7 +18,7 @@ import torch
|
|
|
18
18
|
from huggingface_hub import snapshot_download
|
|
19
19
|
from safetensors.torch import load_file, save_file
|
|
20
20
|
|
|
21
|
-
from modelbinder.registry import Component
|
|
21
|
+
from modelbinder.registry import Component
|
|
22
22
|
|
|
23
23
|
__all__ = ["save_pretrained", "load_pretrained"]
|
|
24
24
|
|
|
@@ -66,7 +66,7 @@ def load_pretrained(
|
|
|
66
66
|
if isinstance(path_or_repo_id, Path) or src.exists() or str(path_or_repo_id).startswith((".", "/", "~")):
|
|
67
67
|
raise FileNotFoundError(f"No saved folder at {src}.")
|
|
68
68
|
src = Path(snapshot_download(str(path_or_repo_id), revision=revision))
|
|
69
|
-
spec =
|
|
69
|
+
spec = Component.from_spec(json.loads((src / CONFIG_NAME).read_text()))
|
|
70
70
|
return spec, {f.parent.name: load_file(f) for f in src.glob(f"*/{WEIGHTS_NAME}")}
|
|
71
71
|
|
|
72
72
|
|
|
@@ -13,10 +13,9 @@ from typing import Any, ClassVar, Self
|
|
|
13
13
|
from pydantic import BaseModel, ConfigDict, ValidationInfo, model_serializer, model_validator
|
|
14
14
|
from pydantic_core import PydanticSerializationError
|
|
15
15
|
|
|
16
|
-
__all__ = ["Component", "PortabilityError", "component"
|
|
16
|
+
__all__ = ["Component", "PortabilityError", "component"]
|
|
17
17
|
|
|
18
18
|
_REGISTRY: dict[str, type[Component]] = {}
|
|
19
|
-
_CONFIGS: dict[type, type[Component]] = {} # implementation -> the config that builds it
|
|
20
19
|
|
|
21
20
|
|
|
22
21
|
class PortabilityError(Exception):
|
|
@@ -74,7 +73,13 @@ class Component(BaseModel):
|
|
|
74
73
|
|
|
75
74
|
def to_spec(self) -> dict[str, Any]:
|
|
76
75
|
"""Return the portable JSON spec; raises :class:`PortabilityError` on anything that is not JSON."""
|
|
77
|
-
|
|
76
|
+
try:
|
|
77
|
+
spec = self.model_dump(mode="json")
|
|
78
|
+
except PydanticSerializationError as e:
|
|
79
|
+
raise PortabilityError(f"{type(self).__name__} holds something a spec cannot: {e}") from None
|
|
80
|
+
if type(self).model_validate(spec) != self: # pydantic coerces e.g. NaN, sets, enums in `Any` fields
|
|
81
|
+
raise PortabilityError(f"{type(self).__name__} does not read back from its spec; it holds non-JSON values.")
|
|
82
|
+
return spec
|
|
78
83
|
|
|
79
84
|
@classmethod
|
|
80
85
|
def from_spec(cls, spec: Mapping[str, object]) -> Self:
|
|
@@ -84,16 +89,8 @@ class Component(BaseModel):
|
|
|
84
89
|
return cls.model_validate(spec)
|
|
85
90
|
|
|
86
91
|
|
|
87
|
-
def component[C: Component](
|
|
88
|
-
type_id
|
|
89
|
-
*,
|
|
90
|
-
builds: type | None = None,
|
|
91
|
-
) -> Callable[[type[C]], type[C]]:
|
|
92
|
-
"""Register a `Component` subclass under ``type_id``, the stable name its specs carry.
|
|
93
|
-
|
|
94
|
-
``builds`` names the implementation the config's ``build`` returns, so :func:`config_of` finds the
|
|
95
|
-
config for it. One config per implementation.
|
|
96
|
-
"""
|
|
92
|
+
def component[C: Component](type_id: str) -> Callable[[type[C]], type[C]]:
|
|
93
|
+
"""Register a `Component` subclass under ``type_id``, the stable name its specs carry."""
|
|
97
94
|
if not isinstance(type_id, str) or not type_id:
|
|
98
95
|
raise TypeError("type_id must be a non-empty string.")
|
|
99
96
|
|
|
@@ -105,37 +102,8 @@ def component[C: Component](
|
|
|
105
102
|
existing = _REGISTRY.get(type_id)
|
|
106
103
|
if existing is not None and existing is not cls:
|
|
107
104
|
raise ValueError(f"type_id {type_id!r} already registered to {existing.__name__}.")
|
|
108
|
-
linked = _CONFIGS.get(builds) if builds is not None else None
|
|
109
|
-
if linked is not None and linked is not cls:
|
|
110
|
-
raise ValueError(f"{builds.__name__} is already built by {linked.__name__}.") # pyright: ignore[reportOptionalMemberAccess]
|
|
111
105
|
cls.__type_id__ = type_id
|
|
112
106
|
_REGISTRY[type_id] = cls
|
|
113
|
-
if builds is not None:
|
|
114
|
-
_CONFIGS[builds] = cls
|
|
115
107
|
return cls
|
|
116
108
|
|
|
117
109
|
return register
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
def config_of(implementation: type) -> type[Component]:
|
|
121
|
-
"""The config registered as building ``implementation``."""
|
|
122
|
-
try:
|
|
123
|
-
return _CONFIGS[implementation]
|
|
124
|
-
except KeyError:
|
|
125
|
-
raise KeyError(f"no config builds {implementation.__name__}.") from None
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
def to_spec(config: Component) -> dict[str, Any]:
|
|
129
|
-
"""Config -> portable JSON spec. Typed ``Any`` like :func:`json.loads`: a spec is data to write out."""
|
|
130
|
-
try:
|
|
131
|
-
spec = config.model_dump(mode="json")
|
|
132
|
-
except PydanticSerializationError as e:
|
|
133
|
-
raise PortabilityError(f"{type(config).__name__} holds something a spec cannot: {e}") from None
|
|
134
|
-
if type(config).model_validate(spec) != config: # pydantic coerces e.g. NaN, sets, enums in `Any` fields
|
|
135
|
-
raise PortabilityError(f"{type(config).__name__} does not read back from its spec; it holds non-JSON values.")
|
|
136
|
-
return spec
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
def parse(spec: Mapping[str, object]) -> Component:
|
|
140
|
-
"""A spec -> the registered :class:`Component` its ``type`` names."""
|
|
141
|
-
return Component.from_spec(spec)
|
|
@@ -43,8 +43,6 @@ def test_refuses_to_overwrite(tmp_path):
|
|
|
43
43
|
save_pretrained(tmp_path, _Model())
|
|
44
44
|
with pytest.raises(FileExistsError):
|
|
45
45
|
save_pretrained(tmp_path, _Model())
|
|
46
|
-
save_pretrained(tmp_path, _Model(depth=2), overwrite=True)
|
|
47
|
-
assert load_pretrained(tmp_path)[0] == _Model(depth=2)
|
|
48
46
|
|
|
49
47
|
|
|
50
48
|
def test_overwrite_drops_states_of_the_earlier_save(tmp_path):
|
|
@@ -8,7 +8,7 @@ from typing import Any
|
|
|
8
8
|
import pytest
|
|
9
9
|
from pydantic import ValidationError, model_validator
|
|
10
10
|
|
|
11
|
-
from modelbinder.registry import Component, PortabilityError, component
|
|
11
|
+
from modelbinder.registry import Component, PortabilityError, component
|
|
12
12
|
|
|
13
13
|
|
|
14
14
|
@component("test.widget")
|
|
@@ -19,22 +19,20 @@ class _Widget(Component):
|
|
|
19
19
|
def test_round_trips_through_a_json_spec():
|
|
20
20
|
spec = _Widget(width=5).to_spec()
|
|
21
21
|
assert spec == {"type": "test.widget", "width": 5}
|
|
22
|
-
assert
|
|
22
|
+
assert Component.from_spec(json.loads(json.dumps(spec))) == _Widget(width=5)
|
|
23
23
|
|
|
24
24
|
|
|
25
25
|
@pytest.mark.parametrize(
|
|
26
26
|
("spec", "match"),
|
|
27
27
|
[
|
|
28
|
-
({"type": "test.widget", "nope": 1}, "Extra inputs"),
|
|
29
28
|
({"type": "test.nonexistent"}, "Unknown type"),
|
|
30
|
-
({"type": "test.widget", "width": "wide"}, "valid integer"),
|
|
31
29
|
({"type": ["test.widget"]}, "is a string"),
|
|
32
30
|
],
|
|
33
|
-
ids=["
|
|
31
|
+
ids=["unknown_type", "list_type"],
|
|
34
32
|
)
|
|
35
33
|
def test_bad_specs_are_rejected(spec, match):
|
|
36
34
|
with pytest.raises(ValidationError, match=match):
|
|
37
|
-
|
|
35
|
+
Component.from_spec(spec)
|
|
38
36
|
|
|
39
37
|
|
|
40
38
|
@component("test.positive")
|
|
@@ -56,11 +54,6 @@ def test_copies_and_construction_are_validated():
|
|
|
56
54
|
assert _Positive().model_copy(update={"n": 2}) == _Positive(n=2)
|
|
57
55
|
|
|
58
56
|
|
|
59
|
-
def test_components_are_frozen():
|
|
60
|
-
with pytest.raises(ValidationError):
|
|
61
|
-
_Widget().width = 4 # pyright: ignore[reportAttributeAccessIssue] (the point)
|
|
62
|
-
|
|
63
|
-
|
|
64
57
|
class _Enc(Component): # an open family: members register anywhere
|
|
65
58
|
pass
|
|
66
59
|
|
|
@@ -95,7 +88,7 @@ def test_a_family_field_keeps_each_members_class_and_fields():
|
|
|
95
88
|
"type": "test.one_hot",
|
|
96
89
|
"categories": ["x"],
|
|
97
90
|
} # not cut to the base's fields
|
|
98
|
-
assert
|
|
91
|
+
assert Component.from_spec(json.loads(json.dumps(spec))) == config
|
|
99
92
|
|
|
100
93
|
|
|
101
94
|
def test_a_family_field_needs_a_type():
|
|
@@ -115,7 +108,7 @@ class _Node(Component):
|
|
|
115
108
|
|
|
116
109
|
def test_a_component_may_name_itself():
|
|
117
110
|
tree = _Node(children=[_Node(), _Node(children=[_Node()])])
|
|
118
|
-
assert
|
|
111
|
+
assert Component.from_spec(tree.to_spec()) == tree
|
|
119
112
|
|
|
120
113
|
|
|
121
114
|
@component("test.holder")
|
|
@@ -130,16 +123,7 @@ class _Holder(Component):
|
|
|
130
123
|
)
|
|
131
124
|
def test_live_objects_have_no_spec(live):
|
|
132
125
|
with pytest.raises(PortabilityError):
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
def test_non_finite_floats_are_rejected():
|
|
137
|
-
@component("test.finite")
|
|
138
|
-
class _Finite(Component):
|
|
139
|
-
x: float = 0.0
|
|
140
|
-
|
|
141
|
-
with pytest.raises(ValidationError):
|
|
142
|
-
_Finite(x=float("nan"))
|
|
126
|
+
_Holder(obj=live).to_spec()
|
|
143
127
|
|
|
144
128
|
|
|
145
129
|
def test_an_unregistered_subclass_has_no_spec():
|
|
@@ -151,17 +135,6 @@ def test_an_unregistered_subclass_has_no_spec():
|
|
|
151
135
|
config.to_spec()
|
|
152
136
|
|
|
153
137
|
|
|
154
|
-
def test_a_member_keeps_its_fields_under_any_pydantic_entry_point():
|
|
155
|
-
from pydantic import BaseModel, TypeAdapter
|
|
156
|
-
|
|
157
|
-
class _Plain(BaseModel):
|
|
158
|
-
enc: _Enc
|
|
159
|
-
|
|
160
|
-
member = _OneHot(categories=("x",))
|
|
161
|
-
assert _Plain.model_validate_json(_Plain(enc=member).model_dump_json()).enc == member
|
|
162
|
-
assert TypeAdapter(list[_Enc]).dump_python([member])[0]["categories"] == ("x",)
|
|
163
|
-
|
|
164
|
-
|
|
165
138
|
def test_type_is_reserved():
|
|
166
139
|
with pytest.raises(TypeError, match="reserved"):
|
|
167
140
|
|
|
@@ -176,28 +149,3 @@ def test_type_ids_are_unique():
|
|
|
176
149
|
@component("test.widget")
|
|
177
150
|
class _Again(Component):
|
|
178
151
|
pass
|
|
179
|
-
|
|
180
|
-
|
|
181
|
-
class _Thing:
|
|
182
|
-
pass
|
|
183
|
-
|
|
184
|
-
|
|
185
|
-
@component("test.thing", builds=_Thing)
|
|
186
|
-
class _ThingConfig(Component):
|
|
187
|
-
size: int = 1
|
|
188
|
-
|
|
189
|
-
def build(self) -> _Thing:
|
|
190
|
-
return _Thing()
|
|
191
|
-
|
|
192
|
-
|
|
193
|
-
def test_builds_links_config_and_implementation():
|
|
194
|
-
assert config_of(_Thing) is _ThingConfig
|
|
195
|
-
|
|
196
|
-
|
|
197
|
-
def test_one_config_per_implementation():
|
|
198
|
-
with pytest.raises(ValueError, match="already built by"):
|
|
199
|
-
|
|
200
|
-
@component("test.second", builds=_Thing)
|
|
201
|
-
class _Second(Component):
|
|
202
|
-
def build(self) -> _Thing:
|
|
203
|
-
return _Thing()
|
modelbinder-0.1.0/docs/api.md
DELETED
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|