Skip to content

chuchichaestli.models.spec

Recording how an object was constructed, so it can be rebuilt exactly.

Classes:

Name Description
C3liSpecError

Raised when a spec names something it may not load.

ModelSpec

What it takes to rebuild a model.

ModelSpecMixin

Records every constructor argument, so .spec can rebuild the object.

Functions:

Name Description
load_model

Rebuild a model from a file and load its weights.

read_model_state

Read a state dict and the spec stored beside it, None if there is none.

read_spec

Return the spec a file carries, or None if it carries none.

write_model_state

Write a state dict with the spec that rebuilds its model, if any.

C3liSpecError

Bases: ValueError

Raised when a spec names something it may not load.

ModelSpec dataclass

ModelSpec(cls: str, kwargs: Mapping[str, Any] = dict())

What it takes to rebuild a model.

Attributes:

Name Type Description
cls str

Importable name of the class, as "module:QualName".

kwargs Mapping[str, Any]

Every constructor argument, defaults included.

json_limit int

Most characters a spec is written as or read from.

Methods:

Name Description
allow

Let a spec from an untrusted file name obj, and return it.

build

Construct the object this spec describes.

decode_arg

Rebuild whatever encode_arg reduced, nested specs included.

encode_arg

Reduce a constructor argument to something JSON can hold.

from_dict

Rebuild a spec from its mapping form.

from_json

Rebuild a spec from its JSON form.

import_class

Import the class an importable name points at.

import_name

Return a "module:QualName" that import_class resolves to obj itself.

qualname

Return an importable "module:QualName" for a class.

resolve

Return the object an import name refers to, if a spec may name it.

to_dict

Return a JSON-serializable mapping of the spec.

to_json

Return the spec as one JSON string, for file metadata.

allow classmethod

allow(obj: Any) -> Any

Let a spec from an untrusted file name obj, and return it.

Parameters:

Name Type Description Default
obj Any

Class, function or enum to allow.

required
Source code in src/chuchichaestli/models/spec.py
149
150
151
152
153
154
155
156
157
@classmethod
def allow(cls, obj: Any) -> Any:
    """Let a spec from an untrusted file name `obj`, and return it.

    Args:
        obj: Class, function or enum to allow.
    """
    cls._allowed.add(obj)
    return obj

build

build(*, trusted: bool = False, **overrides: Any) -> Any

Construct the object this spec describes.

Parameters:

Name Type Description Default
trusted bool

Import any name, as for a file from a trusted source.

False
overrides Any

Arguments to replace, for rebuilding a variant.

{}
Source code in src/chuchichaestli/models/spec.py
335
336
337
338
339
340
341
342
343
344
def build(self, *, trusted: bool = False, **overrides: Any) -> Any:
    """Construct the object this spec describes.

    Args:
        trusted: Import any name, as for a file from a trusted source.
        overrides: Arguments to replace, for rebuilding a variant.
    """
    target = self.resolve(self.cls, trusted)
    kwargs = {k: self.decode_arg(v, trusted) for k, v in self.kwargs.items()}
    return target(**{**kwargs, **overrides})

decode_arg classmethod

decode_arg(value: Any, trusted: bool = False) -> Any

Rebuild whatever encode_arg reduced, nested specs included.

Parameters:

Name Type Description Default
value Any

Encoded argument to restore.

required
trusted bool

Import any name, as for a file from a trusted source.

False
Source code in src/chuchichaestli/models/spec.py
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
@classmethod
def decode_arg(cls, value: Any, trusted: bool = False) -> Any:
    """Rebuild whatever `encode_arg` reduced, nested specs included.

    Args:
        value: Encoded argument to restore.
        trusted: Import any name, as for a file from a trusted source.
    """
    if isinstance(value, Mapping):
        if _TAG in value:
            return cls._decode_tagged(value, trusted)
        if set(value) == {"cls", "kwargs"}:
            return cls.from_dict(value).build(trusted=trusted)
        return {k: cls.decode_arg(v, trusted) for k, v in value.items()}
    if isinstance(value, Sequence) and not isinstance(value, (str, bytes)):
        return [cls.decode_arg(v, trusted) for v in value]
    return value

encode_arg classmethod

encode_arg(value: Any) -> Any

Reduce a constructor argument to something JSON can hold.

Parameters:

Name Type Description Default
value Any

Argument to reduce.

required

Raises:

Type Description
TypeError

If value is a module that records no arguments, or anything else decode_arg could not restore.

Source code in src/chuchichaestli/models/spec.py
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
@classmethod
def encode_arg(cls, value: Any) -> Any:
    """Reduce a constructor argument to something JSON can hold.

    Args:
        value: Argument to reduce.

    Raises:
        TypeError: If `value` is a module that records no arguments, or
            anything else `decode_arg` could not restore.
    """
    if isinstance(value, ModelSpecMixin):
        return value.spec.to_dict()
    if isinstance(value, torch.nn.Module):
        raise TypeError(
            f"Cannot record a {type(value).__name__} argument in a spec: it "
            "does not inherit ModelSpecMixin, so nothing says how to rebuild it."
        )
    if isinstance(value, torch.Tensor):
        return cls._encode_tensor(value)
    if isinstance(value, torch.dtype):
        return {_TAG: "dtype", "name": str(value).removeprefix("torch.")}
    if isinstance(value, torch.device):
        return {_TAG: "device", "name": str(value)}
    if isinstance(value, Enum):
        return {
            _TAG: "enum",
            "cls": cls.import_name(type(value)),
            "value": cls.encode_arg(value.value),
        }
    if isinstance(value, Path):
        return {_TAG: "path", "path": str(value)}
    if isinstance(value, Mapping):
        return cls._encode_mapping(value)
    if isinstance(value, tuple):
        return {_TAG: "tuple", "items": [cls.encode_arg(v) for v in value]}
    if isinstance(value, Sequence) and not isinstance(value, (str, bytes)):
        return [cls.encode_arg(v) for v in value]
    if isinstance(value, (bool, int, float, str)) or value is None:
        return value
    if isinstance(value, functools.partial):
        return {
            _TAG: "partial",
            "func": cls.encode_arg(value.func),
            "args": [cls.encode_arg(v) for v in value.args],
            "kwargs": cls.encode_arg(dict(value.keywords)),
        }
    if callable(value):
        return {_TAG: "import", "name": cls.import_name(value)}
    raise TypeError(
        f"Cannot record a {type(value).__name__} argument in a spec: JSON "
        "cannot hold it, so the rebuilt model would receive something else."
    )

from_dict classmethod

from_dict(state: Mapping[str, Any]) -> ModelSpec

Rebuild a spec from its mapping form.

Parameters:

Name Type Description Default
state Mapping[str, Any]

Mapping as returned by to_dict.

required
Source code in src/chuchichaestli/models/spec.py
366
367
368
369
370
371
372
373
@classmethod
def from_dict(cls, state: Mapping[str, Any]) -> ModelSpec:
    """Rebuild a spec from its mapping form.

    Args:
        state: Mapping as returned by `to_dict`.
    """
    return cls(cls=state["cls"], kwargs=dict(state.get("kwargs", {})))

from_json classmethod

from_json(text: str) -> ModelSpec

Rebuild a spec from its JSON form.

Parameters:

Name Type Description Default
text str

String as returned by to_json.

required

Raises:

Type Description
C3liSpecError

If text is longer than json_limit.

Source code in src/chuchichaestli/models/spec.py
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
@classmethod
def from_json(cls, text: str) -> ModelSpec:
    """Rebuild a spec from its JSON form.

    Args:
        text: String as returned by `to_json`.

    Raises:
        C3liSpecError: If `text` is longer than `json_limit`.
    """
    if len(text) > cls.json_limit:
        raise C3liSpecError(
            f"The spec is {len(text)} characters, above ModelSpec.json_limit "
            f"of {cls.json_limit}. Raise the limit for a file you trust."
        )
    return cls.from_dict(json.loads(text))

import_class staticmethod

import_class(path: str) -> type

Import the class an importable name points at.

Parameters:

Name Type Description Default
path str

Name of the form "module:QualName".

required

Raises:

Type Description
ValueError

If path is not of that form.

Source code in src/chuchichaestli/models/spec.py
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
@staticmethod
def import_class(path: str) -> type:
    """Import the class an importable name points at.

    Args:
        path: Name of the form `"module:QualName"`.

    Raises:
        ValueError: If `path` is not of that form.
    """
    if ":" not in path:
        raise ValueError(
            f"Not an importable name: {path!r}. Use 'module:QualName'."
        )
    module, _, name = path.partition(":")
    target: Any = importlib.import_module(module)
    for part in name.split("."):
        target = getattr(target, part)
    return target

import_name staticmethod

import_name(obj: Any) -> str

Return a "module:QualName" that import_class resolves to obj itself.

Parameters:

Name Type Description Default
obj Any

Class, function or other named object.

required

Raises:

Type Description
TypeError

If no name imports back to obj, as for a lambda.

Source code in src/chuchichaestli/models/spec.py
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
@staticmethod
def import_name(obj: Any) -> str:
    """Return a `"module:QualName"` that `import_class` resolves to `obj` itself.

    Args:
        obj: Class, function or other named object.

    Raises:
        TypeError: If no name imports back to `obj`, as for a lambda.
    """
    for path in _names_of(obj):
        try:
            if ModelSpec.import_class(path) is obj:
                return path
        except (ImportError, AttributeError):
            continue
    raise TypeError(
        f"Cannot record {obj!r} in a spec: no import name resolves to it."
    )

qualname staticmethod

qualname(obj: type) -> str

Return an importable "module:QualName" for a class.

Parameters:

Name Type Description Default
obj type

Class to name.

required
Source code in src/chuchichaestli/models/spec.py
100
101
102
103
104
105
106
107
@staticmethod
def qualname(obj: type) -> str:
    """Return an importable `"module:QualName"` for a class.

    Args:
        obj: Class to name.
    """
    return f"{obj.__module__}:{obj.__qualname__}"

resolve classmethod

resolve(path: str, trusted: bool = False) -> Any

Return the object an import name refers to, if a spec may name it.

Parameters:

Name Type Description Default
path str

Name of the form "module:QualName".

required
trusted bool

Import any name, as for a file from a trusted source.

False

Raises:

Type Description
C3liSpecError

If path is not allowed and the file is untrusted.

Source code in src/chuchichaestli/models/spec.py
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
@classmethod
def resolve(cls, path: str, trusted: bool = False) -> Any:
    """Return the object an import name refers to, if a spec may name it.

    Args:
        path: Name of the form `"module:QualName"`.
        trusted: Import any name, as for a file from a trusted source.

    Raises:
        C3liSpecError: If `path` is not allowed and the file is untrusted.
    """
    if trusted:
        return cls.import_class(path)
    module = path.partition(":")[0]
    if module.partition(".")[0] == _PACKAGE:
        importlib.import_module(module)
    for obj in (*cls._allowed, *_torch_defaults()):
        if path in _names_of(obj):
            return obj
    raise C3liSpecError(
        f"The spec names {path!r}, which is not allowed. Allow it with "
        "ModelSpec.allow(...), or pass trusted=True for a file you trust."
    )

to_dict

to_dict() -> dict[str, Any]

Return a JSON-serializable mapping of the spec.

Source code in src/chuchichaestli/models/spec.py
346
347
348
349
def to_dict(self) -> dict[str, Any]:
    """Return a JSON-serializable mapping of the spec."""
    kwargs = {key: self.encode_arg(value) for key, value in self.kwargs.items()}
    return {"cls": self.cls, "kwargs": kwargs}

to_json

to_json() -> str

Return the spec as one JSON string, for file metadata.

Raises:

Type Description
TypeError

If the string is longer than json_limit.

Source code in src/chuchichaestli/models/spec.py
351
352
353
354
355
356
357
358
359
360
361
362
363
364
def to_json(self) -> str:
    """Return the spec as one JSON string, for file metadata.

    Raises:
        TypeError: If the string is longer than `json_limit`.
    """
    text = json.dumps(self.to_dict(), sort_keys=True)
    if len(text) > self.json_limit:
        raise TypeError(
            f"Cannot record a spec of {len(text)} characters, above "
            f"ModelSpec.json_limit of {self.json_limit}. Register a large "
            "tensor argument as a buffer instead."
        )
    return text

ModelSpecMixin

Bases: InitArgMixin

Records every constructor argument, so .spec can rebuild the object.

Attributes:

Name Type Description
spec ModelSpec

Return what it takes to rebuild this object.

spec property

spec: ModelSpec

Return what it takes to rebuild this object.

Raises:

Type Description
AttributeError

If the arguments were never recorded, which means the class defines no __init__ of its own to wrap.

load_model

load_model(
    path: Path,
    strict: bool = True,
    trusted: bool = False,
    **overrides: Any,
) -> torch.nn.Module

Rebuild a model from a file and load its weights.

Parameters:

Name Type Description Default
path Path

File to read.

required
strict bool

Whether every key must match, as for load_state_dict.

True
trusted bool

Let the spec name anything, for a file you trust.

False
overrides Any

Constructor arguments to replace before building. Changing one that affects a tensor's shape makes the weights unloadable, which strict does not cover.

{}

Raises:

Type Description
ValueError

If the file carries no spec, since the architecture cannot be inferred from weights alone.

Source code in src/chuchichaestli/models/spec.py
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
def load_model(
    path: Path, strict: bool = True, trusted: bool = False, **overrides: Any
) -> torch.nn.Module:
    """Rebuild a model from a file and load its weights.

    Args:
        path: File to read.
        strict: Whether every key must match, as for `load_state_dict`.
        trusted: Let the spec name anything, for a file you trust.
        overrides: Constructor arguments to replace before building. Changing
            one that affects a tensor's shape makes the weights unloadable,
            which `strict` does not cover.

    Raises:
        ValueError: If the file carries no spec, since the architecture cannot
            be inferred from weights alone.
    """
    state, spec = read_model_state(path)
    if spec is None:
        raise ValueError(
            f"No model spec in {str(path)!r}; weights alone do not say which "
            "architecture built them. Save it with write_model_state(..., spec=...)."
        )
    model = spec.build(trusted=trusted, **overrides)
    model.load_state_dict(state, strict=strict)
    return model

read_model_state

read_model_state(
    path: Path,
) -> tuple[dict[str, torch.Tensor], ModelSpec | None]

Read a state dict and the spec stored beside it, None if there is none.

Parameters:

Name Type Description Default
path Path

File to read.

required
Source code in src/chuchichaestli/models/spec.py
432
433
434
435
436
437
438
439
def read_model_state(path: Path) -> tuple[dict[str, torch.Tensor], ModelSpec | None]:
    """Read a state dict and the spec stored beside it, `None` if there is none.

    Args:
        path: File to read.
    """
    state, stored = reader_for(path)(path)
    return state, ModelSpec.from_json(stored) if stored else None

read_spec

read_spec(path: Path) -> ModelSpec | None

Return the spec a file carries, or None if it carries none.

Parameters:

Name Type Description Default
path Path

File to read.

required
Source code in src/chuchichaestli/models/spec.py
422
423
424
425
426
427
428
429
def read_spec(path: Path) -> ModelSpec | None:
    """Return the spec a file carries, or `None` if it carries none.

    Args:
        path: File to read.
    """
    stored = reader_for(path)(path, spec_only=True)
    return ModelSpec.from_json(stored) if stored else None

write_model_state

write_model_state(
    path: Path,
    state: dict[str, torch.Tensor],
    spec: ModelSpec | None = None,
) -> None

Write a state dict with the spec that rebuilds its model, if any.

Parameters:

Name Type Description Default
path Path

File to write.

required
state dict[str, torch.Tensor]

Tensors to store.

required
spec ModelSpec | None

How to rebuild the model, stored beside the tensors.

None

Raises:

Type Description
ValueError

If the suffix names no known format.

Source code in src/chuchichaestli/models/spec.py
442
443
444
445
446
447
448
449
450
451
452
453
454
455
def write_model_state(
    path: Path, state: dict[str, torch.Tensor], spec: ModelSpec | None = None
) -> None:
    """Write a state dict with the spec that rebuilds its model, if any.

    Args:
        path: File to write.
        state: Tensors to store.
        spec: How to rebuild the model, stored beside the tensors.

    Raises:
        ValueError: If the suffix names no known format.
    """
    write_state(path, state, spec.to_json() if spec is not None else None)