modelbinder 0.2.0__tar.gz → 0.3.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.
Files changed (43) hide show
  1. {modelbinder-0.2.0 → modelbinder-0.3.0}/CHANGELOG.md +57 -0
  2. {modelbinder-0.2.0 → modelbinder-0.3.0}/PKG-INFO +5 -2
  3. {modelbinder-0.2.0 → modelbinder-0.3.0}/README.md +4 -1
  4. {modelbinder-0.2.0 → modelbinder-0.3.0}/docs/index.md +1 -1
  5. modelbinder-0.3.0/docs/notebooks/tutorial.ipynb +502 -0
  6. {modelbinder-0.2.0 → modelbinder-0.3.0}/pyproject.toml +2 -1
  7. modelbinder-0.3.0/src/modelbinder/pretrained.py +166 -0
  8. modelbinder-0.3.0/src/modelbinder/py.typed +0 -0
  9. modelbinder-0.3.0/src/modelbinder/registry.py +192 -0
  10. modelbinder-0.3.0/tests/test_pretrained.py +254 -0
  11. modelbinder-0.3.0/tests/test_registry.py +369 -0
  12. modelbinder-0.2.0/docs/notebooks/example.ipynb +0 -174
  13. modelbinder-0.2.0/src/modelbinder/pretrained.py +0 -97
  14. modelbinder-0.2.0/src/modelbinder/registry.py +0 -109
  15. modelbinder-0.2.0/tests/test_pretrained.py +0 -84
  16. modelbinder-0.2.0/tests/test_registry.py +0 -151
  17. {modelbinder-0.2.0 → modelbinder-0.3.0}/.codecov.yaml +0 -0
  18. {modelbinder-0.2.0 → modelbinder-0.3.0}/.editorconfig +0 -0
  19. {modelbinder-0.2.0 → modelbinder-0.3.0}/.github/ISSUE_TEMPLATE/bug_report.yml +0 -0
  20. {modelbinder-0.2.0 → modelbinder-0.3.0}/.github/ISSUE_TEMPLATE/config.yml +0 -0
  21. {modelbinder-0.2.0 → modelbinder-0.3.0}/.github/ISSUE_TEMPLATE/feature_request.yml +0 -0
  22. {modelbinder-0.2.0 → modelbinder-0.3.0}/.github/dependabot.yml +0 -0
  23. {modelbinder-0.2.0 → modelbinder-0.3.0}/.github/workflows/build.yaml +0 -0
  24. {modelbinder-0.2.0 → modelbinder-0.3.0}/.github/workflows/release.yaml +0 -0
  25. {modelbinder-0.2.0 → modelbinder-0.3.0}/.github/workflows/test.yaml +0 -0
  26. {modelbinder-0.2.0 → modelbinder-0.3.0}/.gitignore +0 -0
  27. {modelbinder-0.2.0 → modelbinder-0.3.0}/.pre-commit-config.yaml +0 -0
  28. {modelbinder-0.2.0 → modelbinder-0.3.0}/.readthedocs.yaml +0 -0
  29. {modelbinder-0.2.0 → modelbinder-0.3.0}/.vscode/extensions.json +0 -0
  30. {modelbinder-0.2.0 → modelbinder-0.3.0}/.vscode/launch.json +0 -0
  31. {modelbinder-0.2.0 → modelbinder-0.3.0}/.vscode/settings.json +0 -0
  32. {modelbinder-0.2.0 → modelbinder-0.3.0}/LICENSE +0 -0
  33. {modelbinder-0.2.0 → modelbinder-0.3.0}/biome.jsonc +0 -0
  34. {modelbinder-0.2.0 → modelbinder-0.3.0}/docs/_static/.gitkeep +0 -0
  35. {modelbinder-0.2.0 → modelbinder-0.3.0}/docs/_static/css/custom.css +0 -0
  36. {modelbinder-0.2.0 → modelbinder-0.3.0}/docs/_templates/.gitkeep +0 -0
  37. {modelbinder-0.2.0 → modelbinder-0.3.0}/docs/api.md +0 -0
  38. {modelbinder-0.2.0 → modelbinder-0.3.0}/docs/changelog.md +0 -0
  39. {modelbinder-0.2.0 → modelbinder-0.3.0}/docs/conf.py +0 -0
  40. {modelbinder-0.2.0 → modelbinder-0.3.0}/docs/contributing.md +0 -0
  41. {modelbinder-0.2.0 → modelbinder-0.3.0}/docs/references.bib +0 -0
  42. {modelbinder-0.2.0 → modelbinder-0.3.0}/docs/references.md +0 -0
  43. {modelbinder-0.2.0 → modelbinder-0.3.0}/src/modelbinder/__init__.py +0 -0
@@ -10,6 +10,63 @@ and this project adheres to [Semantic Versioning][].
10
10
 
11
11
  ## [Unreleased]
12
12
 
13
+ ## [0.3.0] - 2026-12-04
14
+
15
+ ### Added
16
+
17
+ - A spec whose type is not registered yet loads the module that the ``modelbinder.components`` entry point of its
18
+ namespace names, e.g. `[project.entry-points."modelbinder.components"] sckitflow = "sckitflow"`. Only modules
19
+ installed packages register there are imported, never a path read from a spec. An entry point that fails to
20
+ import raises its `ImportError`. An unknown type lists the types its namespace registers, if any
21
+ - `ComponentConfig.migrate_spec(fields, from_version=...)` converts an older spec's fields before validation. The
22
+ default reads no older version, so bumping `version` means overriding it. Nested configs migrate independently
23
+ - `pretrained.PretrainedConfig`, the base for a config saved with its modules' weights. Its family base reads any
24
+ saved folder; the configs nested in it stay plain `ComponentConfig`
25
+ - `PretrainedConfig.load_folder(path_or_repo_id, *, revision=None)` returns `(config, folder)`. Called on a config
26
+ family, it requires that family and is typed as it. From the Hub it downloads only `config.json` and the weights.
27
+ A string that is neither a local folder nor a Hub repo raises `FileNotFoundError` naming both, and a `revision`
28
+ given for a local folder raises `ValueError`
29
+ - `PretrainedConfig.generate_model_card()` returns the `README.md` text that `save_folder` writes, or `None` for no
30
+ card; override it to give a family's models a card with its library name and loading instructions
31
+ - `load_modules(folder, modules, *, strict=True)` loads the weights into each module of a `{name: module}` mapping,
32
+ the one `save_folder` takes, through `safetensors.torch.load_model`. It checks the names before loading any
33
+ weights: a name with no saved weights raises `FileNotFoundError`, and with `strict`, saved weights not in the
34
+ mapping raise `ValueError`. `strict=False` loads a subset. It returns the `(missing, unexpected)` keys, prefixed
35
+ with each module's name, as `load_state_dict` does
36
+ - The package ships `py.typed`
37
+ - Tutorial notebook: a linear regression saved and loaded, wrapped into `save_pretrained` / `from_pretrained`
38
+ methods for a package's users, and renaming a field with and without reading older specs
39
+
40
+ ### Changed
41
+
42
+ - Breaking: the base class `Component` is renamed `ComponentConfig`, with no alias
43
+ - Breaking: specs require a `"version"`, written from `@component(type_id, version=n)`; a spec without one, or from a
44
+ newer version, raises. `version` is reserved like `type`. modelbinder 0.2 rejects the `version` key, so it
45
+ cannot read exports written by 0.3
46
+ - Breaking: the module-level `pretrained.load_pretrained` is removed; use `PretrainedConfig.load_folder`, which
47
+ returns `(config, folder)` instead of `(spec, states)`. Build the modules from the config and fill them with
48
+ `load_modules`
49
+ - Breaking: the function `pretrained.save_pretrained(path, spec, states)` is replaced by the method
50
+ `config.save_folder(path, modules)` of a `PretrainedConfig`, leaving the `*_pretrained` names to the methods
51
+ packages write for their users. It takes modules (`{"module": model.module}`) instead of state dicts and writes
52
+ each with `safetensors.torch.save_model`, so tied weights are written once instead of refused
53
+ - A save writes its files to a temporary folder inside the export and moves them into place at the end, so a save
54
+ that fails while writing keeps the earlier one. The next save removes the temporary folder a killed save leaves
55
+ - Breaking: modelbinder no longer writes a `README.md` model card of its own; the one `generate_model_card` returns
56
+ is written only if the folder has none
57
+ - Breaking: module names are lowercase letters, digits, `_` and `-`, so each name is one folder on every
58
+ filesystem, the case-insensitive ones of macOS and Windows included. Exports saved with other names still load
59
+ - `to_spec` raises `PortabilityError` when its spec does not validate back, e.g. a field written under an alias it
60
+ is not read by; it raised pydantic's `ValidationError`
61
+ - `model_copy(update=..., deep=True)` copies deeply; with an `update`, it ignored `deep`
62
+ - `Cls(**spec)` raises `TypeError` when the spec's type is not `Cls`'s own; it returned an empty instance with a
63
+ warning. Build from a spec with `from_spec`
64
+ - `from_spec` raises pydantic's `ValidationError` for a mapping without a `type`, a `ValueError` as before
65
+ - Registering a class again under its type id, e.g. a notebook cell run twice, replaces the earlier registration
66
+ when both have the same module and name. A type id and version set in the class body are refused; give them to
67
+ `@component`
68
+ - `modelbinder.registry` no longer imports torch, safetensors or huggingface_hub
69
+
13
70
  ## [0.2.0] - 2026-11-26
14
71
 
15
72
  ### Removed
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.5
2
2
  Name: modelbinder
3
- Version: 0.2.0
3
+ Version: 0.3.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
@@ -50,7 +50,9 @@ Description-Content-Type: text/markdown
50
50
  [badge-tests]: https://img.shields.io/github/actions/workflow/status/theislab/modelbinder/test.yaml?branch=main
51
51
  [badge-docs]: https://app.readthedocs.org/projects/modelbinder/badge/
52
52
 
53
- Portable component specs (`@component`, on pydantic) and `save_pretrained` / `load_pretrained` in the Hugging Face Hub layout.
53
+ Portable component configs with `ComponentConfig` and `@component`, plus pretrained weights in the Hugging Face Hub layout.
54
+ A model's top-level config subclasses `PretrainedConfig`: `config.save_folder(path, modules)` writes it with its modules' weights, and `PretrainedConfig.load_folder` reads the config back; call `load_folder` on your own config family to require that type.
55
+ A package wraps these into `save_pretrained` and `from_pretrained` methods for its users; the [tutorial][] shows how.
54
56
 
55
57
  ## Getting started
56
58
 
@@ -107,6 +109,7 @@ If you found a bug, please use the [issue tracker][].
107
109
  [tests]: https://github.com/theislab/modelbinder/actions/workflows/test.yaml
108
110
  [documentation]: https://modelbinder.readthedocs.io
109
111
  [changelog]: https://modelbinder.readthedocs.io/page/changelog.html
112
+ [tutorial]: https://modelbinder.readthedocs.io/page/notebooks/tutorial.html
110
113
  [api documentation]: https://modelbinder.readthedocs.io/page/api.html
111
114
  [pypi]: https://pypi.org/project/modelbinder
112
115
  [venv]: https://docs.python.org/3/tutorial/venv.html
@@ -6,7 +6,9 @@
6
6
  [badge-tests]: https://img.shields.io/github/actions/workflow/status/theislab/modelbinder/test.yaml?branch=main
7
7
  [badge-docs]: https://app.readthedocs.org/projects/modelbinder/badge/
8
8
 
9
- Portable component specs (`@component`, on pydantic) and `save_pretrained` / `load_pretrained` in the Hugging Face Hub layout.
9
+ Portable component configs with `ComponentConfig` and `@component`, plus pretrained weights in the Hugging Face Hub layout.
10
+ A model's top-level config subclasses `PretrainedConfig`: `config.save_folder(path, modules)` writes it with its modules' weights, and `PretrainedConfig.load_folder` reads the config back; call `load_folder` on your own config family to require that type.
11
+ A package wraps these into `save_pretrained` and `from_pretrained` methods for its users; the [tutorial][] shows how.
10
12
 
11
13
  ## Getting started
12
14
 
@@ -63,6 +65,7 @@ If you found a bug, please use the [issue tracker][].
63
65
  [tests]: https://github.com/theislab/modelbinder/actions/workflows/test.yaml
64
66
  [documentation]: https://modelbinder.readthedocs.io
65
67
  [changelog]: https://modelbinder.readthedocs.io/page/changelog.html
68
+ [tutorial]: https://modelbinder.readthedocs.io/page/notebooks/tutorial.html
66
69
  [api documentation]: https://modelbinder.readthedocs.io/page/api.html
67
70
  [pypi]: https://pypi.org/project/modelbinder
68
71
  [venv]: https://docs.python.org/3/tutorial/venv.html
@@ -11,5 +11,5 @@ changelog.md
11
11
  contributing.md
12
12
  references.md
13
13
 
14
- notebooks/example
14
+ notebooks/tutorial
15
15
  ```
@@ -0,0 +1,502 @@
1
+ {
2
+ "cells": [
3
+ {
4
+ "cell_type": "markdown",
5
+ "id": "250b143d",
6
+ "metadata": {},
7
+ "source": [
8
+ "# Tutorial: a linear regression\n",
9
+ "\n",
10
+ "This notebook defines a linear regression config with modelbinder, fits it, saves it with its weights, and loads it\n",
11
+ "back, then wraps saving and loading into the two methods a package gives its users. The last part shows how to change a config's fields in a later release, with and without reading the specs\n",
12
+ "the older release wrote."
13
+ ]
14
+ },
15
+ {
16
+ "cell_type": "code",
17
+ "execution_count": 1,
18
+ "id": "b90aebd7",
19
+ "metadata": {
20
+ "execution": {
21
+ "iopub.execute_input": "2026-12-03T20:13:23.144576Z",
22
+ "iopub.status.busy": "2026-12-03T20:13:23.144295Z",
23
+ "iopub.status.idle": "2026-12-03T20:13:24.492886Z",
24
+ "shell.execute_reply": "2026-12-03T20:13:24.492440Z"
25
+ }
26
+ },
27
+ "outputs": [],
28
+ "source": [
29
+ "import tempfile\n",
30
+ "import warnings\n",
31
+ "from pathlib import Path\n",
32
+ "\n",
33
+ "import torch\n",
34
+ "from pydantic import ValidationError\n",
35
+ "from torch import nn\n",
36
+ "\n",
37
+ "from modelbinder.pretrained import PretrainedConfig, load_modules\n",
38
+ "from modelbinder.registry import ComponentConfig, component"
39
+ ]
40
+ },
41
+ {
42
+ "cell_type": "markdown",
43
+ "id": "2b9a8e5f",
44
+ "metadata": {},
45
+ "source": [
46
+ "## Define the config\n",
47
+ "\n",
48
+ "A config is a frozen pydantic model registered under a type id with {func}`~modelbinder.registry.component`. The\n",
49
+ "config holds the hyperparameters and builds the module; the weights are saved separately.\n",
50
+ "\n",
51
+ "Name a type id `\"<package>.<name>\"`; here it is `tutorial.linear_regression`. In a package `mypkg`, the id would be\n",
52
+ "`mypkg.linear_regression`, and an entry point lets modelbinder import `mypkg` when it reads such a spec:\n",
53
+ "\n",
54
+ "```toml\n",
55
+ "[project.entry-points.\"modelbinder.components\"]\n",
56
+ "mypkg = \"mypkg\"\n",
57
+ "```"
58
+ ]
59
+ },
60
+ {
61
+ "cell_type": "code",
62
+ "execution_count": 2,
63
+ "id": "44a312ee",
64
+ "metadata": {
65
+ "execution": {
66
+ "iopub.execute_input": "2026-12-03T20:13:24.494100Z",
67
+ "iopub.status.busy": "2026-12-03T20:13:24.493983Z",
68
+ "iopub.status.idle": "2026-12-03T20:13:24.498659Z",
69
+ "shell.execute_reply": "2026-12-03T20:13:24.498168Z"
70
+ }
71
+ },
72
+ "outputs": [
73
+ {
74
+ "data": {
75
+ "text/plain": [
76
+ "{'type': 'tutorial.linear_regression',\n",
77
+ " 'version': 1,\n",
78
+ " 'n_features': 3,\n",
79
+ " 'l2': 0.001}"
80
+ ]
81
+ },
82
+ "execution_count": 2,
83
+ "metadata": {},
84
+ "output_type": "execute_result"
85
+ }
86
+ ],
87
+ "source": [
88
+ "@component(\"tutorial.linear_regression\")\n",
89
+ "class LinearRegressionConfig(PretrainedConfig):\n",
90
+ " n_features: int\n",
91
+ " l2: float = 0.0\n",
92
+ "\n",
93
+ " def build(self) -> nn.Linear:\n",
94
+ " return nn.Linear(self.n_features, 1)\n",
95
+ "\n",
96
+ "\n",
97
+ "config = LinearRegressionConfig(n_features=3, l2=1e-3)\n",
98
+ "config.to_spec()"
99
+ ]
100
+ },
101
+ {
102
+ "cell_type": "markdown",
103
+ "id": "c87080e7",
104
+ "metadata": {},
105
+ "source": [
106
+ "The spec is plain JSON: the type id, the version it was written at (1 unless `@component` says otherwise),\n",
107
+ "and the fields.\n",
108
+ "\n",
109
+ "## Fit it\n",
110
+ "\n",
111
+ "Data from $y = 2x_1 - x_2 + 0.5x_3 + 0.3$ plus noise, fit with gradient descent; `l2` is the weight decay."
112
+ ]
113
+ },
114
+ {
115
+ "cell_type": "code",
116
+ "execution_count": 3,
117
+ "id": "ed034817",
118
+ "metadata": {
119
+ "execution": {
120
+ "iopub.execute_input": "2026-12-03T20:13:24.499839Z",
121
+ "iopub.status.busy": "2026-12-03T20:13:24.499756Z",
122
+ "iopub.status.idle": "2026-12-03T20:13:27.364286Z",
123
+ "shell.execute_reply": "2026-12-03T20:13:27.363811Z"
124
+ }
125
+ },
126
+ "outputs": [
127
+ {
128
+ "name": "stdout",
129
+ "output_type": "stream",
130
+ "text": [
131
+ "loss 0.0114, weight [ 1.993 -1.002 0.495], bias 0.300\n"
132
+ ]
133
+ }
134
+ ],
135
+ "source": [
136
+ "torch.manual_seed(0)\n",
137
+ "X = torch.randn(200, 3)\n",
138
+ "y = X @ torch.tensor([2.0, -1.0, 0.5]) + 0.3 + 0.1 * torch.randn(200)\n",
139
+ "\n",
140
+ "model = config.build()\n",
141
+ "optimizer = torch.optim.SGD(model.parameters(), lr=0.1, weight_decay=config.l2)\n",
142
+ "for _ in range(200):\n",
143
+ " optimizer.zero_grad()\n",
144
+ " loss = nn.functional.mse_loss(model(X).squeeze(-1), y)\n",
145
+ " loss.backward()\n",
146
+ " optimizer.step()\n",
147
+ "\n",
148
+ "print(f\"loss {loss.item():.4f}, weight {model.weight.data.squeeze().numpy().round(3)}, bias {model.bias.item():.3f}\")"
149
+ ]
150
+ },
151
+ {
152
+ "cell_type": "markdown",
153
+ "id": "6d022080",
154
+ "metadata": {},
155
+ "source": [
156
+ "## Save and load\n",
157
+ "\n",
158
+ "The config subclasses {class}`~modelbinder.pretrained.PretrainedConfig` because it is saved with weights; configs\n",
159
+ "nested in it subclass {class}`~modelbinder.registry.ComponentConfig`.\n",
160
+ "{meth}`~modelbinder.pretrained.PretrainedConfig.save_folder` writes the config to `config.json` and each named module's weights to\n",
161
+ "`<name>/model.safetensors`. The folder can be uploaded to the Hugging Face Hub as is."
162
+ ]
163
+ },
164
+ {
165
+ "cell_type": "code",
166
+ "execution_count": 4,
167
+ "id": "e23b4f14",
168
+ "metadata": {
169
+ "execution": {
170
+ "iopub.execute_input": "2026-12-03T20:13:27.365590Z",
171
+ "iopub.status.busy": "2026-12-03T20:13:27.365449Z",
172
+ "iopub.status.idle": "2026-12-03T20:13:27.373078Z",
173
+ "shell.execute_reply": "2026-12-03T20:13:27.372714Z"
174
+ }
175
+ },
176
+ "outputs": [
177
+ {
178
+ "data": {
179
+ "text/plain": [
180
+ "['config.json', 'module/model.safetensors']"
181
+ ]
182
+ },
183
+ "execution_count": 4,
184
+ "metadata": {},
185
+ "output_type": "execute_result"
186
+ }
187
+ ],
188
+ "source": [
189
+ "folder = Path(tempfile.mkdtemp()) / \"linear_regression\"\n",
190
+ "config.save_folder(folder, {\"module\": model})\n",
191
+ "sorted(str(p.relative_to(folder)) for p in folder.rglob(\"*\") if p.is_file())"
192
+ ]
193
+ },
194
+ {
195
+ "cell_type": "markdown",
196
+ "id": "3a2c285d",
197
+ "metadata": {},
198
+ "source": [
199
+ "{meth}`~modelbinder.pretrained.PretrainedConfig.load_folder` takes a folder or a Hub repo id and returns a config\n",
200
+ "with its local folder. Call it on the config class you expect, then build the module and fill it with\n",
201
+ "{func}`~modelbinder.pretrained.load_modules`, which takes the same `{name: module}` mapping as `save_folder`."
202
+ ]
203
+ },
204
+ {
205
+ "cell_type": "code",
206
+ "execution_count": 5,
207
+ "id": "8b804265",
208
+ "metadata": {
209
+ "execution": {
210
+ "iopub.execute_input": "2026-12-03T20:13:27.374178Z",
211
+ "iopub.status.busy": "2026-12-03T20:13:27.374110Z",
212
+ "iopub.status.idle": "2026-12-03T20:13:27.390114Z",
213
+ "shell.execute_reply": "2026-12-03T20:13:27.389747Z"
214
+ }
215
+ },
216
+ "outputs": [
217
+ {
218
+ "data": {
219
+ "text/plain": [
220
+ "LinearRegressionConfig(n_features=3, l2=0.001)"
221
+ ]
222
+ },
223
+ "execution_count": 5,
224
+ "metadata": {},
225
+ "output_type": "execute_result"
226
+ }
227
+ ],
228
+ "source": [
229
+ "loaded_config, loaded_folder = LinearRegressionConfig.load_folder(folder)\n",
230
+ "loaded = loaded_config.build()\n",
231
+ "load_modules(loaded_folder, {\"module\": loaded})\n",
232
+ "\n",
233
+ "assert loaded_config == config\n",
234
+ "assert torch.equal(loaded(X), model(X))\n",
235
+ "loaded_config"
236
+ ]
237
+ },
238
+ {
239
+ "cell_type": "markdown",
240
+ "id": "a41176e7",
241
+ "metadata": {},
242
+ "source": [
243
+ "## Give your users one call\n",
244
+ "\n",
245
+ "`save_folder`, `load_folder` and `load_modules` are building blocks. A package hides them behind two methods on an\n",
246
+ "object that holds the config next to the module it built, so its users save with `model.save_pretrained(path)` and\n",
247
+ "load with `Model.from_pretrained(path)`. The names follow Hugging Face; nothing in modelbinder requires them."
248
+ ]
249
+ },
250
+ {
251
+ "cell_type": "code",
252
+ "execution_count": 6,
253
+ "id": "3b80a6ec",
254
+ "metadata": {
255
+ "execution": {
256
+ "iopub.execute_input": "2026-12-03T20:13:27.391147Z",
257
+ "iopub.status.busy": "2026-12-03T20:13:27.391081Z",
258
+ "iopub.status.idle": "2026-12-03T20:13:27.407230Z",
259
+ "shell.execute_reply": "2026-12-03T20:13:27.406877Z"
260
+ }
261
+ },
262
+ "outputs": [],
263
+ "source": [
264
+ "from typing import NamedTuple\n",
265
+ "\n",
266
+ "\n",
267
+ "class LinearRegression(NamedTuple):\n",
268
+ " config: LinearRegressionConfig\n",
269
+ " module: nn.Linear\n",
270
+ "\n",
271
+ " def save_pretrained(self, path, *, overwrite=False):\n",
272
+ " self.config.save_folder(path, {\"module\": self.module}, overwrite=overwrite)\n",
273
+ "\n",
274
+ " @classmethod\n",
275
+ " def from_pretrained(cls, path_or_repo_id, *, revision=None):\n",
276
+ " config, folder = LinearRegressionConfig.load_folder(path_or_repo_id, revision=revision)\n",
277
+ " module = config.build()\n",
278
+ " load_modules(folder, {\"module\": module})\n",
279
+ " return cls(config, module)\n",
280
+ "\n",
281
+ "\n",
282
+ "LinearRegression(config, model).save_pretrained(folder, overwrite=True)\n",
283
+ "reloaded = LinearRegression.from_pretrained(folder)\n",
284
+ "assert torch.equal(reloaded.module(X), model(X))"
285
+ ]
286
+ },
287
+ {
288
+ "cell_type": "markdown",
289
+ "id": "c55b80e4",
290
+ "metadata": {},
291
+ "source": [
292
+ "When writing these two methods:\n",
293
+ "\n",
294
+ "- The module names (`\"module\"` here) and the type ids are part of the saved format. Renaming either breaks folders\n",
295
+ " saved before. Module names are lowercase letters, digits, `_` or `-`.\n",
296
+ "- Save one entry per module that learns. `{\"module\": ..., \"ema\": ...}` writes `module/` and `ema/`, and\n",
297
+ " `from_pretrained` loads each by its name.\n",
298
+ "- Only the module's `state_dict()` is saved: parameters, submodules and persistent buffers. A plain tensor attribute\n",
299
+ " comes from `build()`, not from the folder.\n",
300
+ "- In a package, add the entry point shown above, so `from_pretrained` works before the package is imported.\n",
301
+ "- modelbinder writes no `README.md`. Override `generate_model_card` on the config to return one that names your\n",
302
+ " package and says how to load the model with it.\n",
303
+ "- When the config's fields change, bump `version` and override `migrate_spec`, as below."
304
+ ]
305
+ },
306
+ {
307
+ "cell_type": "markdown",
308
+ "id": "b3b4e21f",
309
+ "metadata": {},
310
+ "source": [
311
+ "## Changing a config in a later release\n",
312
+ "\n",
313
+ "Say the next release renames `l2` to `alpha`. Specs saved with the current release still say `l2`, so the new\n",
314
+ "release either refuses them or keeps reading them. Both options are below, each under its own type id so they fit in\n",
315
+ "one notebook; in a real package they would keep the id `tutorial.linear_regression`.\n",
316
+ "\n",
317
+ "In both, `version=2` marks specs that the current release cannot read. A user still on the current release then gets\n",
318
+ "an error asking them to upgrade, instead of a complaint about an unknown field `alpha`:"
319
+ ]
320
+ },
321
+ {
322
+ "cell_type": "code",
323
+ "execution_count": 7,
324
+ "id": "0e6d4775",
325
+ "metadata": {
326
+ "execution": {
327
+ "iopub.execute_input": "2026-12-03T20:13:27.408342Z",
328
+ "iopub.status.busy": "2026-12-03T20:13:27.408276Z",
329
+ "iopub.status.idle": "2026-12-03T20:13:27.410283Z",
330
+ "shell.execute_reply": "2026-12-03T20:13:27.409991Z"
331
+ }
332
+ },
333
+ "outputs": [
334
+ {
335
+ "name": "stdout",
336
+ "output_type": "stream",
337
+ "text": [
338
+ "1 validation error for ComponentConfig\n",
339
+ " Value error, 'tutorial.linear_regression' spec has version 2, newer than the 1 this install reads; upgrade the package that registers it. [type=value_error, input_value={'type': 'tutorial.linear...res': 3, 'alpha': 0.001}, input_type=dict]\n",
340
+ " For further information visit https://errors.pydantic.dev/2.14/v/value_error\n"
341
+ ]
342
+ }
343
+ ],
344
+ "source": [
345
+ "newer = {\"type\": \"tutorial.linear_regression\", \"version\": 2, \"n_features\": 3, \"alpha\": 1e-3}\n",
346
+ "try:\n",
347
+ " ComponentConfig.from_spec(newer)\n",
348
+ "except ValidationError as e:\n",
349
+ " print(e)"
350
+ ]
351
+ },
352
+ {
353
+ "cell_type": "markdown",
354
+ "id": "4ecb6062",
355
+ "metadata": {},
356
+ "source": [
357
+ "### Without backward compatibility\n",
358
+ "\n",
359
+ "The new release only has `alpha` and no `migrate_spec`, so a spec written by the current release fails to load.\n",
360
+ "Its folders cannot be read by the new release: the model is trained again, or its `config.json` edited by hand."
361
+ ]
362
+ },
363
+ {
364
+ "cell_type": "code",
365
+ "execution_count": 8,
366
+ "id": "535eba0e",
367
+ "metadata": {
368
+ "execution": {
369
+ "iopub.execute_input": "2026-12-03T20:13:27.411245Z",
370
+ "iopub.status.busy": "2026-12-03T20:13:27.411179Z",
371
+ "iopub.status.idle": "2026-12-03T20:13:27.413579Z",
372
+ "shell.execute_reply": "2026-12-03T20:13:27.413289Z"
373
+ }
374
+ },
375
+ "outputs": [
376
+ {
377
+ "name": "stdout",
378
+ "output_type": "stream",
379
+ "text": [
380
+ "1 validation error for ComponentConfig\n",
381
+ " Value error, StrictConfig reads version 2 specs and has no migrate_spec for version 1. [type=value_error, input_value={'type': 'tutorial.linear...atures': 3, 'l2': 0.001}, input_type=dict]\n",
382
+ " For further information visit https://errors.pydantic.dev/2.14/v/value_error\n"
383
+ ]
384
+ }
385
+ ],
386
+ "source": [
387
+ "@component(\"tutorial.linear_regression_strict\", version=2)\n",
388
+ "class StrictConfig(ComponentConfig):\n",
389
+ " n_features: int\n",
390
+ " alpha: float = 0.0\n",
391
+ "\n",
392
+ "\n",
393
+ "old = {\"type\": \"tutorial.linear_regression_strict\", \"version\": 1, \"n_features\": 3, \"l2\": 1e-3}\n",
394
+ "try:\n",
395
+ " ComponentConfig.from_spec(old)\n",
396
+ "except ValidationError as e:\n",
397
+ " print(e)"
398
+ ]
399
+ },
400
+ {
401
+ "cell_type": "markdown",
402
+ "id": "ad55d73d",
403
+ "metadata": {},
404
+ "source": [
405
+ "### With backward compatibility\n",
406
+ "\n",
407
+ "The new release uses `migrate_spec` to read `l2` from version 1 specs as `alpha` and warn that those specs\n",
408
+ "are deprecated. The hook receives the version the spec was saved at and its fields, before validation. Each nested config\n",
409
+ "uses its own version. The plain constructor still expects `alpha`, so `CompatConfig(l2=...)` fails."
410
+ ]
411
+ },
412
+ {
413
+ "cell_type": "code",
414
+ "execution_count": 9,
415
+ "id": "a3e2af34",
416
+ "metadata": {
417
+ "execution": {
418
+ "iopub.execute_input": "2026-12-03T20:13:27.414534Z",
419
+ "iopub.status.busy": "2026-12-03T20:13:27.414477Z",
420
+ "iopub.status.idle": "2026-12-03T20:13:27.417589Z",
421
+ "shell.execute_reply": "2026-12-03T20:13:27.417236Z"
422
+ }
423
+ },
424
+ "outputs": [
425
+ {
426
+ "name": "stdout",
427
+ "output_type": "stream",
428
+ "text": [
429
+ "Version 1 specs are deprecated; save the config again to write `alpha`.\n"
430
+ ]
431
+ },
432
+ {
433
+ "data": {
434
+ "text/plain": [
435
+ "{'type': 'tutorial.linear_regression_compat',\n",
436
+ " 'version': 2,\n",
437
+ " 'n_features': 3,\n",
438
+ " 'alpha': 0.001}"
439
+ ]
440
+ },
441
+ "execution_count": 9,
442
+ "metadata": {},
443
+ "output_type": "execute_result"
444
+ }
445
+ ],
446
+ "source": [
447
+ "@component(\"tutorial.linear_regression_compat\", version=2)\n",
448
+ "class CompatConfig(ComponentConfig):\n",
449
+ " n_features: int\n",
450
+ " alpha: float = 0.0\n",
451
+ "\n",
452
+ " @classmethod\n",
453
+ " def migrate_spec(cls, fields, *, from_version):\n",
454
+ " if from_version == 1:\n",
455
+ " # stacklevel=1 points here: the caller is modelbinder's validator, not the user's code\n",
456
+ " warnings.warn(\n",
457
+ " \"Version 1 specs are deprecated; save the config again to write `alpha`.\", FutureWarning, stacklevel=1\n",
458
+ " )\n",
459
+ " fields = {(\"alpha\" if k == \"l2\" else k): v for k, v in fields.items()}\n",
460
+ " return fields\n",
461
+ "\n",
462
+ "\n",
463
+ "old = {\"type\": \"tutorial.linear_regression_compat\", \"version\": 1, \"n_features\": 3, \"l2\": 1e-3}\n",
464
+ "with warnings.catch_warnings(record=True) as caught:\n",
465
+ " warnings.simplefilter(\"always\")\n",
466
+ " upgraded = ComponentConfig.from_spec(old)\n",
467
+ "print(caught[0].message)\n",
468
+ "upgraded.to_spec()"
469
+ ]
470
+ },
471
+ {
472
+ "cell_type": "markdown",
473
+ "id": "d7c1f052",
474
+ "metadata": {},
475
+ "source": [
476
+ "Saving the loaded config writes it at version 2 with `alpha`, so re-saving a folder once migrates it. Once old\n",
477
+ "specs no longer need to load, drop the migration hook; a spec with `l2` then fails as in the strict case."
478
+ ]
479
+ }
480
+ ],
481
+ "metadata": {
482
+ "kernelspec": {
483
+ "display_name": "Python 3",
484
+ "language": "python",
485
+ "name": "python3"
486
+ },
487
+ "language_info": {
488
+ "codemirror_mode": {
489
+ "name": "ipython",
490
+ "version": 3
491
+ },
492
+ "file_extension": ".py",
493
+ "mimetype": "text/x-python",
494
+ "name": "python",
495
+ "nbconvert_exporter": "python",
496
+ "pygments_lexer": "ipython3",
497
+ "version": "3.12.9"
498
+ }
499
+ },
500
+ "nbformat": 4,
501
+ "nbformat_minor": 5
502
+ }
@@ -119,7 +119,7 @@ lint.ignore = [
119
119
  "E741", # allow I, O, l as variable names -> I is the identity matrix
120
120
  ]
121
121
  lint.per-file-ignores."*/__init__.py" = [ "F401" ]
122
- lint.per-file-ignores."docs/*" = [ "I" ]
122
+ lint.per-file-ignores."docs/*" = [ "D", "I" ]
123
123
  lint.per-file-ignores."tests/*" = [ "D" ]
124
124
  lint.pydocstyle.convention = "numpy"
125
125
 
@@ -133,6 +133,7 @@ ini_options.addopts = [
133
133
  "--strict-markers",
134
134
  "--strict-config",
135
135
  ]
136
+ ini_options.filterwarnings = [ "error" ]
136
137
 
137
138
  [tool.coverage]
138
139
  run.omit = [