modelbinder 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,7 @@
1
+ """modelbinder: the component registry and saving specs with their weights."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from . import pretrained, registry
6
+
7
+ __all__ = ["registry", "pretrained"]
@@ -0,0 +1,97 @@
1
+ """Save and load a spec with its weights, in the Hugging Face Hub layout.
2
+
3
+ A folder holds ``config.json`` (the spec), one ``<name>/model.safetensors`` per state and a ``README.md``
4
+ model card. A folder reads back under the package versions that wrote it.
5
+
6
+ Share one with ``huggingface_hub.HfApi``: ``create_repo(repo_id, exist_ok=True)``, then
7
+ ``upload_folder(repo_id=repo_id, folder_path=path)``; :func:`load_pretrained` takes the repo id.
8
+ """
9
+
10
+ from __future__ import annotations
11
+
12
+ import json
13
+ from collections.abc import Mapping
14
+ from pathlib import Path
15
+ from typing import Any
16
+
17
+ import torch
18
+ from huggingface_hub import snapshot_download
19
+ from safetensors.torch import load_file, save_file
20
+
21
+ from modelbinder.registry import Component, parse
22
+
23
+ __all__ = ["save_pretrained", "load_pretrained"]
24
+
25
+ CONFIG_NAME = "config.json"
26
+ WEIGHTS_NAME = "model.safetensors"
27
+
28
+
29
+ def save_pretrained(
30
+ path: str | Path,
31
+ spec: Component,
32
+ states: Mapping[str, Mapping[str, torch.Tensor]] | None = None,
33
+ *,
34
+ overwrite: bool = False,
35
+ ) -> None:
36
+ """Writes ``spec`` and each named state (e.g. ``{"module": module.state_dict()}``) to the folder ``path``.
37
+
38
+ Everything is checked before the folder is touched. Tensors sharing memory (tied weights) are refused.
39
+
40
+ :raises FileExistsError: If ``path`` already holds a spec and ``overwrite`` is `False`.
41
+ :raises ValueError: If a state name is not a plain folder name, or a state ties tensors.
42
+ :raises modelbinder.registry.PortabilityError: If the spec holds a live object.
43
+ """
44
+ out = Path(path)
45
+ document = spec.to_spec()
46
+ tensors = {name: _checked(name, state) for name, state in (states or {}).items()}
47
+ if (out / CONFIG_NAME).exists():
48
+ if not overwrite:
49
+ raise FileExistsError(f"{out / CONFIG_NAME} already exists. Use overwrite=True.")
50
+ for stale in out.glob(f"*/{WEIGHTS_NAME}"): # a state left from the earlier save would load back with this one
51
+ stale.unlink()
52
+ out.mkdir(parents=True, exist_ok=True)
53
+ (out / CONFIG_NAME).write_text(json.dumps(document, indent=2))
54
+ for name, state in tensors.items():
55
+ (out / name).mkdir(exist_ok=True)
56
+ save_file(state, out / name / WEIGHTS_NAME)
57
+ (out / "README.md").write_text(_model_card(document))
58
+
59
+
60
+ def load_pretrained(
61
+ path_or_repo_id: str | Path, *, revision: str | None = None
62
+ ) -> tuple[Component, dict[str, dict[str, torch.Tensor]]]:
63
+ """The spec and the named states saved in a local folder, or in a Hub repo (``"org/name"``)."""
64
+ src = Path(path_or_repo_id)
65
+ if not src.is_dir():
66
+ if isinstance(path_or_repo_id, Path) or src.exists() or str(path_or_repo_id).startswith((".", "/", "~")):
67
+ raise FileNotFoundError(f"No saved folder at {src}.")
68
+ src = Path(snapshot_download(str(path_or_repo_id), revision=revision))
69
+ spec = parse(json.loads((src / CONFIG_NAME).read_text()))
70
+ return spec, {f.parent.name: load_file(f) for f in src.glob(f"*/{WEIGHTS_NAME}")}
71
+
72
+
73
+ def _checked(name: str, state: Mapping[str, torch.Tensor]) -> dict[str, torch.Tensor]:
74
+ """``state`` as contiguous tensors, after checking it can be written under ``name``."""
75
+ if name in ("", ".", "..") or Path(name).name != name:
76
+ raise ValueError(f"State name {name!r} is not a plain folder name.")
77
+ if not all(isinstance(v, torch.Tensor) for v in state.values()):
78
+ raise TypeError(f"State {name!r} holds values that are not tensors.")
79
+ storages = [v.untyped_storage().data_ptr() for v in state.values() if v.numel()]
80
+ if len(storages) != len(set(storages)):
81
+ raise ValueError(f"State {name!r} ties tensors (shared memory), which safetensors cannot store.")
82
+ return {k: v.contiguous() for k, v in state.items()}
83
+
84
+
85
+ def _model_card(document: Mapping[str, Any]) -> str:
86
+ tags = "\n".join(f"- {json.dumps(tag)}" for tag in ["modelbinder", *sorted(_types(document))])
87
+ return f"---\nlibrary_name: modelbinder\ntags:\n{tags}\n---\n\nLoad with `modelbinder.pretrained.load_pretrained(repo_id)`.\n"
88
+
89
+
90
+ def _types(value: Any) -> set[str]:
91
+ """Every component type a spec names, nested ones included."""
92
+ if isinstance(value, Mapping):
93
+ own = {value["type"]} if isinstance(value.get("type"), str) else set()
94
+ return own.union(*(_types(v) for v in value.values()))
95
+ if isinstance(value, list):
96
+ return set().union(*(_types(v) for v in value))
97
+ return set()
@@ -0,0 +1,141 @@
1
+ """The component registry and portable specs for modelbinder, on pydantic.
2
+
3
+ A :class:`Component` is a frozen pydantic model, registered under a stable ``type_id`` with :func:`component`.
4
+ A spec is ``{"type": type_id, **fields}``, plain JSON. Packages built on modelbinder subclass it, so a family stays
5
+ open: a spec's ``type`` picks the registered class, wherever a field names the family base.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ from collections.abc import Callable, Mapping
11
+ from typing import Any, ClassVar, Self
12
+
13
+ from pydantic import BaseModel, ConfigDict, ValidationInfo, model_serializer, model_validator
14
+ from pydantic_core import PydanticSerializationError
15
+
16
+ __all__ = ["Component", "PortabilityError", "component", "config_of", "to_spec", "parse"]
17
+
18
+ _REGISTRY: dict[str, type[Component]] = {}
19
+ _CONFIGS: dict[type, type[Component]] = {} # implementation -> the config that builds it
20
+
21
+
22
+ class PortabilityError(Exception):
23
+ """Raised when a config holds something a spec cannot, e.g. a live object."""
24
+
25
+
26
+ class Component(BaseModel):
27
+ """Base for every portable config. Register a concrete one with :func:`component`.
28
+
29
+ A subclass left unregistered is a family base, usable as the expected family in :meth:`from_spec` and as
30
+ a field type; it is never built itself. How a config turns into a runtime object is up to its family,
31
+ which declares its own typed ``build``.
32
+ """
33
+
34
+ # polymorphic: a member is written with its own fields, not those of the field's declared base
35
+ model_config = ConfigDict(frozen=True, extra="forbid", allow_inf_nan=False, polymorphic_serialization=True)
36
+
37
+ __type_id__: ClassVar[str | None] = None
38
+
39
+ @model_validator(mode="wrap")
40
+ @classmethod
41
+ def _dispatch(cls, value: Any, handler: Callable[[Any], Self], info: ValidationInfo) -> Self:
42
+ """A spec's ``type`` picks the registered class, so a field typed as a family base stays open."""
43
+ if isinstance(value, Mapping) and "type" not in value and cls.__type_id__ is None:
44
+ raise ValueError(f"{cls.__name__} is a family base; give a spec with a 'type', or a member.")
45
+ if not (isinstance(value, Mapping) and "type" in value):
46
+ return handler(value)
47
+ type_id = value["type"]
48
+ fields = {k: v for k, v in value.items() if k != "type"}
49
+ if not isinstance(type_id, str):
50
+ raise ValueError(f"A spec's type is a string, got {type_id!r}.")
51
+ target = _REGISTRY.get(type_id)
52
+ if target is None:
53
+ raise ValueError(f"Unknown type {type_id!r}; registered: {sorted(_REGISTRY)}.")
54
+ if not issubclass(target, cls):
55
+ raise ValueError(f"type {type_id!r} ({target.__name__}) is not a {cls.__name__}.")
56
+ return handler(fields) if target is cls else target.model_validate(fields, context=info.context) # pyright: ignore[reportReturnType]
57
+
58
+ @model_serializer(mode="wrap")
59
+ def _tag(self, handler: Callable[[Self], dict[str, Any]]) -> dict[str, Any]:
60
+ if _REGISTRY.get(self.__type_id__ or "") is not type(self): # e.g. a subclass of a registered config
61
+ raise TypeError(f"{type(self).__name__} is not registered; decorate it with @component(type_id).")
62
+ return {"type": self.__type_id__, **handler(self)}
63
+
64
+ def model_copy(self, *, update: Mapping[str, Any] | None = None, deep: bool = False) -> Self:
65
+ """As pydantic's, but ``update`` is validated; pydantic's skips validation."""
66
+ if update is None:
67
+ return super().model_copy(deep=deep)
68
+ return type(self).model_validate({**dict(self), **update})
69
+
70
+ @classmethod
71
+ def model_construct(cls, _fields_set: set[str] | None = None, **values: Any) -> Self:
72
+ """Validates like the constructor; pydantic's skips validation."""
73
+ return cls.model_validate(values)
74
+
75
+ def to_spec(self) -> dict[str, Any]:
76
+ """Return the portable JSON spec; raises :class:`PortabilityError` on anything that is not JSON."""
77
+ return to_spec(self)
78
+
79
+ @classmethod
80
+ def from_spec(cls, spec: Mapping[str, object]) -> Self:
81
+ """Parse a spec into a config, rejecting one whose type is not a ``cls``."""
82
+ if not (isinstance(spec, Mapping) and "type" in spec):
83
+ raise ValueError("A spec is a mapping with a 'type'.")
84
+ return cls.model_validate(spec)
85
+
86
+
87
+ def component[C: Component](
88
+ type_id: str,
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
+ """
97
+ if not isinstance(type_id, str) or not type_id:
98
+ raise TypeError("type_id must be a non-empty string.")
99
+
100
+ def register(cls: type[C]) -> type[C]:
101
+ if not (isinstance(cls, type) and issubclass(cls, Component)):
102
+ raise TypeError(f"@component needs a Component subclass, got {cls!r}.")
103
+ if "type" in cls.model_fields:
104
+ raise TypeError(f"{cls.__name__}: 'type' is reserved for the spec.")
105
+ existing = _REGISTRY.get(type_id)
106
+ if existing is not None and existing is not cls:
107
+ 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
+ cls.__type_id__ = type_id
112
+ _REGISTRY[type_id] = cls
113
+ if builds is not None:
114
+ _CONFIGS[builds] = cls
115
+ return cls
116
+
117
+ 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)
@@ -0,0 +1,112 @@
1
+ Metadata-Version: 2.5
2
+ Name: modelbinder
3
+ Version: 0.1.0
4
+ Summary: Portable component specs and pretrained weights in the Hugging Face Hub layout
5
+ Project-URL: Documentation, https://modelbinder.readthedocs.io/
6
+ Project-URL: Homepage, https://github.com/theislab/modelbinder
7
+ Project-URL: Source, https://github.com/theislab/modelbinder
8
+ Author: Selman Ozleyen
9
+ Maintainer-email: Selman Ozleyen <syozleyen@gmail.com>
10
+ License: MIT License
11
+
12
+ Copyright (c) 2026, Selman Ozleyen
13
+
14
+ Permission is hereby granted, free of charge, to any person obtaining a copy
15
+ of this software and associated documentation files (the "Software"), to deal
16
+ in the Software without restriction, including without limitation the rights
17
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
18
+ copies of the Software, and to permit persons to whom the Software is
19
+ furnished to do so, subject to the following conditions:
20
+
21
+ The above copyright notice and this permission notice shall be included in all
22
+ copies or substantial portions of the Software.
23
+
24
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
25
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
26
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
27
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
28
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
29
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
30
+ SOFTWARE.
31
+ License-File: LICENSE
32
+ Classifier: Programming Language :: Python :: 3 :: Only
33
+ Classifier: Programming Language :: Python :: 3.12
34
+ Classifier: Programming Language :: Python :: 3.13
35
+ Classifier: Programming Language :: Python :: 3.14
36
+ Requires-Python: >=3.12
37
+ Requires-Dist: huggingface-hub>=0.23
38
+ Requires-Dist: numpy
39
+ Requires-Dist: pydantic>=2.13
40
+ Requires-Dist: safetensors>=0.4
41
+ Requires-Dist: session-info2
42
+ Requires-Dist: torch>=2
43
+ Description-Content-Type: text/markdown
44
+
45
+ # modelbinder
46
+
47
+ [![Tests][badge-tests]][tests]
48
+ [![Documentation][badge-docs]][documentation]
49
+
50
+ [badge-tests]: https://img.shields.io/github/actions/workflow/status/theislab/modelbinder/test.yaml?branch=main
51
+ [badge-docs]: https://app.readthedocs.org/projects/modelbinder/badge/
52
+
53
+ Portable component specs (`@component`, on pydantic) and `save_pretrained` / `load_pretrained` in the Hugging Face Hub layout.
54
+
55
+ ## Getting started
56
+
57
+ Please refer to the [documentation][],
58
+ in particular, the [API documentation][].
59
+
60
+ ## Installation
61
+
62
+ You need to have Python 3.12 or newer installed on your system.
63
+ If you don't have Python installed, we recommend installing [uv][].
64
+
65
+ We recommend managing dependencies in project-specific virtual environments to avoid dependency conflicts.
66
+ This is most convenient using package managers such as [uv][].
67
+ Choose from the options below to install modelbinder:
68
+
69
+ <!--
70
+ 1. Add the latest release of `modelbinder` from [PyPI][] to your `uv` project:
71
+
72
+ ```bash
73
+ uv add modelbinder
74
+ ```
75
+
76
+ 1. Install the latest release into a [standard virtual environment][venv]:
77
+
78
+ ```bash
79
+ (after activating your venv)
80
+ pip install modelbinder
81
+ ```
82
+
83
+ -->
84
+
85
+ 1. Install the latest development version:
86
+
87
+ ```bash
88
+ pip install git+https://github.com/theislab/modelbinder.git # (or `uv add`)
89
+ ```
90
+
91
+ ## Release notes
92
+
93
+ See the [changelog][].
94
+
95
+ ## Contact
96
+
97
+ For questions and help requests, you can reach out in the [scverse discourse][].
98
+ If you found a bug, please use the [issue tracker][].
99
+
100
+ ## Citation
101
+
102
+ > t.b.a
103
+
104
+ [uv]: https://github.com/astral-sh/uv
105
+ [scverse discourse]: https://discourse.scverse.org/
106
+ [issue tracker]: https://github.com/theislab/modelbinder/issues
107
+ [tests]: https://github.com/theislab/modelbinder/actions/workflows/test.yaml
108
+ [documentation]: https://modelbinder.readthedocs.io
109
+ [changelog]: https://modelbinder.readthedocs.io/page/changelog.html
110
+ [api documentation]: https://modelbinder.readthedocs.io/page/api.html
111
+ [pypi]: https://pypi.org/project/modelbinder
112
+ [venv]: https://docs.python.org/3/tutorial/venv.html
@@ -0,0 +1,7 @@
1
+ modelbinder/__init__.py,sha256=a8m6C7GgemgWN9TzPwtppVyRlx3dieBQh0gscGunCVY,189
2
+ modelbinder/pretrained.py,sha256=2Su1VNxQ23s6VV6KJMHNVja-loaGdK8PflcOLvuJ18c,4413
3
+ modelbinder/registry.py,sha256=VBG7peI7pkeoDfeD9qeOc_edStm6FDS99B9SFVHg634,6806
4
+ modelbinder-0.1.0.dist-info/METADATA,sha256=5heoMvCcijqQo95uO1-VXy5E2S9mhrD1MrbL8KD5L0A,4159
5
+ modelbinder-0.1.0.dist-info/WHEEL,sha256=2iZrJkDIkeDh0k9SikKMqFuRP-ua6mb4Ir1AsER4BEw,87
6
+ modelbinder-0.1.0.dist-info/licenses/LICENSE,sha256=UAPufOD-BMJOA7U8W7QkCMdQ7iM6jN0_cOAwSDM05uY,1072
7
+ modelbinder-0.1.0.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: hatchling 1.33.0
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026, Selman Ozleyen
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.