Skip to content

Reference

Model artifacts

Start with save, load and diagrams. The common Model.save / ESN.save methods select complete checkpoints or image formats by suffix. save_model also accepts supported raw graph families.

Portable artifacts use registered declarative configuration and tensor state. Loading defaults to Torch's restricted loader (weights_only=True) and does not import Python paths selected by the file. register_component and custom_objects supply application-trusted ComponentCodec constructors; register custom component types explicitly before portable loading.

An optional Python bundle requires trusted=True at both save and load. It can execute Python when loaded and needs compatible Python/package versions. Restricted loading reduces code-execution exposure but does not provide a resource sandbox for malformed or oversized files.

include_state=True retains recurrent memory. Setting it to False resets ordinary recurrent memory on reload while retaining fitted preprocessing and observed forecast history. Artifacts do not retain an autonomous forecast cursor, optimizer or autograd graph. return_metadata=True returns (model, metadata) from load; ordinary state_dict files still require a matching model and load_state_dict.

artifacts

Complete model artifacts using standard Torch serialization.

Portable artifacts reconstruct registered components without loading embedded Python code. trusted=True explicitly enables an optional cloudpickle bundle. Ordinary state_dict remains the standard state-only PyTorch interface.

ComponentCodec dataclass

ComponentCodec(
    name: str,
    cls: type,
    encode: Callable[[Any], Mapping[str, Any]],
    decode: Callable[[Mapping[str, Any]], Any],
    version: int = 1,
)

A versioned component constructor installed by the application.

encode(component) returns configuration, not its learned tensor state. decode(config) constructs that component. Nested registered modules and ordinary tensor/primitive configuration values are encoded automatically. Registering a codec trusts its Python functions; a model file cannot install or import a codec by itself.

ArtifactError

Bases: ValueError

An artifact cannot be represented or reconstructed as requested.

load

load(
    path: str | Path,
    *,
    trusted: bool = False,
    map_location: Any = "cpu",
    custom_objects: Mapping[str, ComponentCodec] | None = None,
    return_metadata: bool = False
) -> Any

Reconstruct a saved model without knowing its original DAG.

The default uses Torch's restricted tensor/primitive loader and never imports artifact-selected Python paths. trusted=True permits Python unpickling; use it only for a file whose producer and contents you trust. Restricted loading reduces code execution exposure but does not prevent malformed-file memory/resource exhaustion. Device remapping follows standard torch.load.

Source code in src/resdag/artifacts/_api.py
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
def load(
    path: str | Path,
    *,
    trusted: bool = False,
    map_location: Any = "cpu",
    custom_objects: Mapping[str, ComponentCodec] | None = None,
    return_metadata: bool = False,
) -> Any:
    """Reconstruct a saved model without knowing its original DAG.

    The default uses Torch's restricted tensor/primitive loader and never imports
    artifact-selected Python paths. `trusted=True` permits Python unpickling;
    use it only for a file whose producer and contents you trust. Restricted
    loading reduces code execution exposure but does not prevent malformed-file
    memory/resource exhaustion. Device remapping follows standard `torch.load`.
    """
    if type(trusted) is not bool:
        raise TypeError("trusted must be a bool")
    _initialize()
    try:
        with torch.inference_mode(False):
            payload = torch.load(path, map_location=map_location, weights_only=True)
    except pickle.UnpicklingError as error:
        raise ArtifactError(
            "Restricted loading rejected Python objects. For a trusted Python bundle only, explicitly pass trusted=True; never enable this for an unknown file."
        ) from error
    if not isinstance(payload, dict) or payload.get("format") != _FORMAT:
        raise ArtifactError(
            "This is not a complete ResDAG artifact; state_dict files require a matching model and load_state_dict"
        )
    if type(payload.get("version")) is not int or payload["version"] != _VERSION:
        raise ArtifactError(
            f"Unsupported ResDAG artifact version {payload.get('version')!r}; this installation supports version {_VERSION}"
        )
    if payload.get("trusted") and not trusted:
        raise ArtifactError(
            "This artifact contains executable Python; explicitly pass trusted=True only if its producer is trusted"
        )
    with torch.inference_mode(False), torch.random.fork_rng(devices=[]):
        if payload.get("trusted"):
            model = _trusted_decode(payload["python"], payload["tensors"], payload["generators"])
            if not isinstance(model, nn.Module):
                raise ArtifactError("Trusted artifact root is not a Torch module")
            for name, module in model.named_modules():
                _restore_live(module, payload["live"].get(name, {}))
        else:
            decoder = _Decoder(payload["components"], custom_objects)
            model = decoder.decode(payload["root"])
            if not isinstance(model, nn.Module):
                raise ArtifactError("Artifact root is not a Torch module")
            # Functional construction runs trace placeholders. Restore final
            # persistent and live state again after all parent graphs are built.
            for key, module in decoder.objects.items():
                if isinstance(module, nn.Module):
                    module.load_state_dict(
                        decoder.records[key]["state_dict"], strict=True, assign=True
                    )
                    _restore_live(module, decoder.records[key]["live"])
        _restore_behavior(model, payload["behavior"])
    meta = payload["metadata"]
    _plain(meta)
    return (model, meta) if return_metadata else model

save_model

save_model(
    model: Module,
    path: str | Path,
    *,
    trusted: bool = False,
    include_state: bool = True,
    metadata: Mapping[str, Any] | None = None
) -> Path

Save a complete model, preserving recurrent memory by default.

Portable files contain declarative registered configuration and tensor state. trusted=True uses the optional cloudpickle package to include Python components such as notebook-local classes and lambdas. Loading those files requires explicit trust and compatible Python/package versions.

include_state=False resets ordinary recurrent memory on reload. Fitted preprocessing and the observed history used by forecast are retained. Neither option saves an autonomous forecast cursor, optimizer or autograd graph.

Source code in src/resdag/artifacts/_api.py
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
def save_model(
    model: nn.Module,
    path: str | Path,
    *,
    trusted: bool = False,
    include_state: bool = True,
    metadata: Mapping[str, Any] | None = None,
) -> Path:
    """Save a complete model, preserving recurrent memory by default.

    Portable files contain declarative registered configuration and tensor state.
    `trusted=True` uses the optional cloudpickle package to include Python
    components such as notebook-local classes and lambdas. Loading those files
    requires explicit trust and compatible Python/package versions.

    `include_state=False` resets ordinary recurrent memory on reload. Fitted
    preprocessing and the observed history used by `forecast` are retained.
    Neither option saves an autonomous forecast cursor, optimizer or autograd graph.
    """
    if not isinstance(model, nn.Module):
        raise TypeError("model must be a torch.nn.Module")
    if type(trusted) is not bool or type(include_state) is not bool:
        raise TypeError("trusted and include_state must be bool values")
    path = Path(path)
    if path.suffix.lower() not in (".pt", ".pth"):
        raise ArtifactError(
            "Complete model artifacts use .pt or .pth; diagram formats are .svg/.png/.pdf/.dot"
        )
    meta = dict(metadata or {})
    _plain(meta)
    _initialize()
    from resdag.core._execution import validate_fitting_forward
    from resdag.core.model import ESNModel

    for module in model.modules():
        if isinstance(module, ESNModel):
            try:
                validate_fitting_forward(module)
            except ValueError as error:
                raise ArtifactError(
                    "Saving a customized outer ESNModel.forward is unsupported; put the behavior inside a declared graph module."
                ) from error
    payload: dict[str, Any] = {
        "format": _FORMAT,
        "version": _VERSION,
        "producer": {
            "resdag": version("resdag"),
            "torch": str(torch.__version__),
            "python": platform.python_version(),
        },
        "metadata": meta,
        "behavior": _behavior(model),
        "trusted": trusted,
    }
    with torch.random.fork_rng(devices=[]):
        if trusted:
            cloudpickle = _cloudpickle()
            live = {
                name: _live_state(module, include_state) for name, module in model.named_modules()
            }
            code, tensors, generators = _trusted_encode(model, cloudpickle, include_state)
            payload.update(python=code, tensors=tensors, generators=generators, live=live)
        else:
            encoder = _Encoder(include_state)
            payload.update(root=encoder.encode(model), components=encoder.records)
        _atomic_save(payload, path)
    return path

register_component

register_component(
    name: str,
    cls: type,
    *,
    encode: Callable[[Any], Mapping[str, Any]],
    decode: Callable[[Mapping[str, Any]], Any],
    version: int = 1
) -> type

Register an exact custom type for portable save/load.

Example:

rd.register_component(
    "my-project.Scale", Scale,
    encode=lambda layer: {"factor": layer.factor},
    decode=lambda config: Scale(**config),
)

Import the registration in a new process before loading. Subclasses need their own registration, so their custom behavior cannot disappear silently. Use a new version when the component's configuration contract changes.

Source code in src/resdag/artifacts/_registry.py
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
def register_component(
    name: str,
    cls: type,
    *,
    encode: Callable[[Any], Mapping[str, Any]],
    decode: Callable[[Mapping[str, Any]], Any],
    version: int = 1,
) -> type:
    """Register an exact custom type for portable save/load.

    Example:

    ```text
    rd.register_component(
        "my-project.Scale", Scale,
        encode=lambda layer: {"factor": layer.factor},
        decode=lambda config: Scale(**config),
    )
    ```

    Import the registration in a new process before loading. Subclasses need
    their own registration, so their custom behavior cannot disappear silently.
    Use a new version when the component's configuration contract changes.
    """
    from ._api import _initialize

    _initialize()
    if not isinstance(name, str) or not name or name.startswith("resdag."):
        raise ValueError("Custom component name must be nonempty and not start with 'resdag.'")
    return _register(ComponentCodec(name, cls, encode, decode, version))