jabara.torch のソースコード

"""Save a nested torch state to a Jabara archive and load it back.

Imports torch lazily. See DESIGN.md, "Torch layer".
"""

from __future__ import annotations

import os
import tempfile
from collections.abc import Callable, Iterator, Sequence
from contextlib import closing
from pathlib import Path
from typing import TYPE_CHECKING, Any, cast

from pydantic import JsonValue

from jabara.assign import Assigner
from jabara.container import Archive, ArchiveInfo, write_archive
from jabara.errors import ArchiveFormatError, UnsupportedDtypeError, UnsupportedStateError
from jabara.formats.torch_zip import TorchZip
from jabara.schemas import OptimizerSchema, StateSchema
from jabara.skeleton import flatten, unflatten
from jabara.types import DTYPE_ITEMSIZE, TensorMeta, TensorRecord

if TYPE_CHECKING:
    import torch

SOURCE: JsonValue = {"kind": "torch"}


def _is_tensor(x: object) -> bool:
    # Exact types only: a subclass would come back as its base class, so `flatten` refuses it like any other value.
    import torch

    return type(x) in (torch.Tensor, torch.nn.Parameter)


def _attrs(tensor: torch.Tensor) -> dict[str, JsonValue]:
    # torch.save keeps a Parameter's type and every tensor's requires_grad; so does the skeleton.
    import torch

    attrs: dict[str, JsonValue] = {}
    if isinstance(tensor, torch.nn.Parameter):
        attrs["parameter"] = True
    if tensor.requires_grad:
        attrs["requires_grad"] = True
    return attrs


def _rebuild(tensor: torch.Tensor, attrs: dict[str, JsonValue]) -> object:
    import torch

    if set(attrs) - {"parameter", "requires_grad"}:
        raise ArchiveFormatError(f"malformed skeleton: unknown tensor attributes {attrs!r}")
    if any(v is not True for v in attrs.values()):
        raise ArchiveFormatError(f"malformed skeleton: tensor attributes must be true, not {attrs!r}")
    requires_grad = "requires_grad" in attrs
    try:
        if "parameter" in attrs:
            return torch.nn.Parameter(tensor, requires_grad=requires_grad)
        return tensor.requires_grad_(requires_grad)
    except RuntimeError as e:  # for example requires_grad on an integer tensor
        raise ArchiveFormatError(f"malformed skeleton: tensor attributes {attrs!r} do not fit the tensor: {e}") from e


def _records(leaves: list[tuple[str, Any]], schema: StateSchema) -> Iterator[TensorRecord]:
    import torch

    for name, tensor in leaves:
        if tensor.layout != torch.strided or tensor.is_meta:
            where = "meta" if tensor.is_meta else str(tensor.layout).removeprefix("torch.")
            raise UnsupportedStateError(f"tensor {name!r}: a {where} tensor has no dense data to store")
        dtype = str(tensor.dtype).removeprefix("torch.")
        if dtype not in DTYPE_ITEMSIZE:
            raise UnsupportedDtypeError(f"tensor {name!r}: dtype {tensor.dtype} is not supported")
        # A conjugate or negative view stores the values it shows; the lazy bit itself is not kept.
        flat = tensor.detach().to("cpu").resolve_conj().resolve_neg().contiguous().reshape(-1)
        if dtype == "bfloat16":
            flat = flat.view(torch.int16)  # numpy has no bfloat16; the bits are what matters
        meta = TensorMeta(name=name, dtype=dtype, shape=tuple(tensor.shape), role=schema.role(tuple(name.split("/"))))
        yield TensorRecord(meta, flat.numpy())


[ドキュメント] def tensor_records(obj: object, schema: StateSchema | None = None) -> list[TensorRecord]: """The tensor leaves of a nested state as records, named and given roles the way `save_state` does.""" _, leaves = flatten(obj, _is_tensor) return list(_records(leaves, schema or OptimizerSchema()))
[ドキュメント] def save_state( obj: object, path: str | os.PathLike[str], *, schema: StateSchema | None = None, threads: int | None = None, assign: Assigner | None = None, base: Archive | Sequence[Archive] | None = None, allow_lossy: bool = False, ) -> ArchiveInfo: """Write a nested state of tensors and plain values to an archive at `path`, with roles from `schema` (`OptimizerSchema` if None). An `nn.Parameter` leaf and a tensor's `requires_grad` are kept in the skeleton. Returns the `ArchiveInfo`. Raises `UnsupportedStateError` for a value that cannot be stored without pickle (a tensor subclass included) and for a sparse or meta tensor, `UnsupportedDtypeError` for a dtype that Jabara does not support, and the errors of `write_archive`. """ # flatten calls attrs only on a leaf _is_tensor accepted. skeleton, leaves = flatten(obj, _is_tensor, cast("Callable[[object], dict[str, JsonValue]]", _attrs)) return write_archive( path, _records(leaves, schema or OptimizerSchema()), skeleton=skeleton, source=SOURCE, assign=assign, threads=threads, base=base, allow_lossy=allow_lossy, )
def _device(map_location: object) -> torch.device: """`map_location` as a `torch.device`: None means CPU. Raises `ValueError` for anything but None, a `str`, or a `torch.device`, since `Tensor.to` would also take a dtype and cast, and for the meta device, which holds no data; PyTorch's `RuntimeError` for a bad string. """ import torch if map_location is None: return torch.device("cpu") if not isinstance(map_location, (str, torch.device)): raise ValueError( # noqa: TRY004 - DESIGN.md: a bad argument value is a ValueError, as in `jabara.lightning` f"map_location must be None, a str or a torch.device, not {type(map_location).__name__}: " "a dtype, dict or callable is not a device, and tensors are restored bit for bit" ) device = torch.device(map_location) if device.type == "meta": raise ValueError("map_location must be a device that holds data: the meta device would drop the saved bytes") return device def _load_torch_zip(archive: Archive, device: torch.device, threads: int | None) -> object: import torch from jabara.files import restore # noqa: PLC0415 - jabara.files imports this module with tempfile.TemporaryDirectory() as tmp: out = Path(tmp) / "state.pt" restore(archive, out, threads=threads) try: return torch.load(out, map_location=device, weights_only=True) except Exception as e: raise ArchiveFormatError( f"{archive.path}: the torch file in it does not load with weights_only=True ({type(e).__name__})" ) from e
[ドキュメント] def load_state( path: str | os.PathLike[str], *, map_location: str | torch.device | None = "cpu", threads: int | None = None, base: Archive | Sequence[Archive] | None = None, ) -> object: """Read an archive that `save_state` wrote, or that `compress_file` wrote from a torch file, and return the same nested state, with every tensor on the device `map_location` names (None is CPU), `nn.Parameter` leaves as `nn.Parameter`, `requires_grad` as saved, and every `OrderedDict` with the `_metadata` it had (a module `state_dict` loads with its module versions). A delta archive needs `base`, the open archive it was written against. An archive of a torch file is restored to a temporary file and read with `torch.load(weights_only=True)`, which refuses a file that holds other objects than tensors and plain values. Raises `ValueError` for a `map_location` that is not None, a `str`, or a `torch.device`, or that names the meta device, before the archive is opened, and `ArchiveFormatError` for an archive of anything else. """ import torch device = _device(map_location) with Archive.open(path, base=base) as archive: if archive.index.source != SOURCE: source = archive.index.source if isinstance(source, dict) and source.get("kind") == TorchZip.kind: return _load_torch_zip(archive, device, threads) raise ArchiveFormatError(f"{path}: not an archive written by save_state or of a torch file") metas = [archive.meta(name) for name in archive.names()] tensors = {} with closing(archive._read_many([m.name for m in metas if m.nbytes], threads=threads)) as decoded: # noqa: SLF001 - package-internal: Archive keeps its batched read out of the public API for meta in metas: dtype = getattr(torch, meta.dtype) if meta.nbytes: _, parts = next(decoded) raw = bytearray().join(parts) # one copy, into the writable buffer torch.frombuffer needs tensor = torch.frombuffer(raw, dtype=dtype).reshape(meta.shape) else: tensor = torch.empty(meta.shape, dtype=dtype) tensors[meta.name] = tensor.to(device) # unflatten calls rebuild only on a value of `tensors`. return unflatten( archive.index.skeleton, tensors, cast("Callable[[object, dict[str, JsonValue]], object]", _rebuild) )