Source code for jabara.formats.torch_zip

"""The zip files that `torch.save` writes, taken apart without unpickling them. See DESIGN.md.

`torch.save` writes a zip whose members are stored, not compressed: `data.pkl`, the pickle of the object, and one
member `data/<key>` per tensor storage, which holds the storage's bytes as they are in memory. The split keeps the
storage members as tensors and every other byte of the file (local headers, `data.pkl`, the central directory) as
the remainder, so the file comes back byte for byte.

The dtype and size of each storage are read from the persistent ids in `data.pkl` with `pickletools`, which only
parses opcodes: no class is imported and no code in the file runs. Tensor names and roles need the object itself,
so they come from `torch.load(weights_only=True)`, which refuses any class that is not on PyTorch's allow-list;
when it refuses, or torch is not installed, every storage keeps a name from its key and the role `other`.
"""

from __future__ import annotations

import mmap
import pickletools
import re
import warnings
import zipfile
from collections.abc import Callable, Iterable
from math import prod
from pathlib import Path
from typing import Any, NamedTuple

from pydantic import JsonValue

from jabara.errors import ArchiveFormatError, RolesUnknownWarning
from jabara.formats import splice
from jabara.formats._zip import stored_members
from jabara.formats.base import CheckpointFormat, Split
from jabara.formats.registry import register_format
from jabara.formats.splice import Span
from jabara.schemas import OptimizerSchema
from jabara.types import DTYPE_ITEMSIZE, TensorMeta

# The storage classes in a persistent id, by the dtype their bytes hold. Any other class keeps its bytes as uint8.
_STORAGE_DTYPES = {
    "FloatStorage": "float32",
    "DoubleStorage": "float64",
    "HalfStorage": "float16",
    "BFloat16Storage": "bfloat16",
    "LongStorage": "int64",
    "IntStorage": "int32",
    "ShortStorage": "int16",
    "CharStorage": "int8",
    "ByteStorage": "uint8",
    "BoolStorage": "bool",
    "ComplexFloatStorage": "complex64",
    "ComplexDoubleStorage": "complex128",
}
# The opcodes that push a string or an integer: the parts of a storage id.
_LITERALS = {
    "BINUNICODE",
    "SHORT_BINUNICODE",
    "BINUNICODE8",
    "UNICODE",
    "BININT",
    "BININT1",
    "BININT2",
    "LONG1",
    "LONG4",
}


def _storage_ids(pkl: bytes, bad: Callable[[str], ArchiveFormatError]) -> list[tuple[str, str, int]]:
    """(key, storage class, numel) of each persistent id in `data.pkl`, in the order the pickle names them first.
    Only the opcodes are parsed: a value that is not a string or an integer becomes `None`."""
    stack: list[object] = []
    marks: list[int] = []  # where each open mark sits in `stack`, so finding one costs nothing whatever the depth
    memo: dict[int, object] = {}
    found: list[tuple[str, str, int]] = []
    seen: set[str] = set()

    def to_mark() -> list[object]:
        i = marks.pop()  # IndexError on a mark that is not there, which the caller reports
        items = stack[i + 1 :]
        del stack[i:]
        return items

    def step(op: pickletools.OpcodeInfo, arg: object) -> None:
        name = op.name
        if name in _LITERALS:
            stack.append(arg)
        elif name == "GLOBAL":
            stack.append(str(arg).replace(" ", "."))
        elif name == "STACK_GLOBAL":
            attr, module = stack.pop(), stack.pop()
            stack.append(f"{module}.{attr}")
        elif name in {"PUT", "BINPUT", "LONG_BINPUT"}:
            memo[int(arg)] = stack[-1]  # type: ignore[call-overload]
        elif name == "MEMOIZE":
            memo[len(memo)] = stack[-1]
        elif name in {"GET", "BINGET", "LONG_BINGET"}:
            stack.append(memo[int(arg)])  # type: ignore[call-overload]
        elif name == "MARK":
            marks.append(len(stack))
            stack.append(None)
        elif name == "TUPLE":
            stack.append(tuple(to_mark()))
        elif name in {"TUPLE1", "TUPLE2", "TUPLE3"}:
            n = int(name[-1])
            items = stack[-n:]
            del stack[-n:]
            stack.append(tuple(items))
        elif name == "BINPERSID":
            pid = stack.pop()
            if not (isinstance(pid, tuple) and len(pid) == 5 and pid[0] == "storage"):  # noqa: PLR2004 - its shape
                raise bad(f"data.pkl has a persistent id that is not a storage ({pid!r})")
            _, cls, key, _, numel = pid
            if not (isinstance(cls, str) and isinstance(key, str) and isinstance(numel, int)):
                raise bad(f"data.pkl has a storage id of an unexpected shape ({pid!r})")
            if key not in seen:
                seen.add(key)
                found.append((key, cls.rsplit(".", 1)[-1], numel))
            stack.append(None)
        elif name == "PERSID":
            raise bad("data.pkl uses a text persistent id, which torch.save does not write")
        else:  # any other opcode: only its effect on the stack matters
            before = op.stack_before
            if pickletools.markobject in before:
                to_mark()
                pops = before.index(pickletools.markobject)  # the items below the mark that it consumes too
            else:
                pops = len(before)
            if pops:
                del stack[-pops:]
            while marks and marks[-1] >= len(stack):  # a malformed pickle popped past a mark
                marks.pop()
            stack.extend([None] * len(op.stack_after))

    try:
        for op, arg, _ in pickletools.genops(pkl):
            step(op, arg)
    except (IndexError, KeyError, ValueError, EOFError) as e:
        raise bad(f"data.pkl does not parse as a pickle ({e!r})") from e
    return found


class _Storage(NamedTuple):
    key: str
    start: int
    end: int
    crc_at: tuple[int, ...]
    dtype: str
    numel: int


def _layout(path: Path, raw: mmap.mmap) -> tuple[list[_Storage], list[str]]:
    """The storage members of a torch zip in file order, and their keys in the order `data.pkl` names them first.
    Raises `ArchiveFormatError` for a file that is not such a zip."""

    def bad(msg: str) -> ArchiveFormatError:
        return ArchiveFormatError(f"{path}: not a zip file written by torch.save: {msg}")

    if not zipfile.is_zipfile(path) and raw[:1] == b"\x80":
        raise ArchiveFormatError(
            f"{path}: a torch.save file in the legacy format (before PyTorch 1.6), which Jabara does not take; "
            "load it and save it again with a current PyTorch"
        )
    members = stored_members(path, raw, bad, "torch.save stores every member as it is")
    prefixes = {name.split("/", 1)[0] for name in members}
    if len(prefixes) != 1 or any("/" not in name for name in members):
        raise bad("its members are not all in one top-level directory")
    (prefix,) = prefixes
    pkl = members.get(f"{prefix}/data.pkl")
    if pkl is None:
        raise bad("no data.pkl")
    ids = _storage_ids(bytes(raw[pkl.start : pkl.end]), bad)
    storages = []
    for key, cls, numel in ids:
        member = members.get(f"{prefix}/data/{key}")
        if member is None:
            raise bad(f"data.pkl names storage {key!r}, which the zip does not hold")
        dtype = _STORAGE_DTYPES.get(cls, "uint8")
        size = member.end - member.start
        if numel * DTYPE_ITEMSIZE[dtype] == size:
            storages.append(_Storage(key, member.start, member.end, member.crc_at, dtype, numel))
        else:  # a class it does not know, or a size that does not fit it: the bytes as they are
            storages.append(_Storage(key, member.start, member.end, member.crc_at, "uint8", size))
    held = {n.rsplit("/", 1)[1] for n in members if n.startswith(f"{prefix}/data/")}
    if extra := held - {s.key for s in storages}:
        raise bad(f"the zip holds storages that data.pkl does not name ({', '.join(sorted(extra)[:3])})")
    return storages, [key for key, _, _ in ids]


def _names_and_roles(path: Path, sizes: dict[str, int]) -> dict[str, tuple[str, str, tuple[int, ...] | None]]:
    """`sizes` holds the byte size of each storage by key, in the order `data.pkl` names them first. For each key,
    the path of the first tensor that views it (keys joined by `/`, as `save_state` names them), its role by
    `OptimizerSchema`, and the tensor's shape when it covers the whole storage. Raises `RuntimeError` with the reason
    when `torch.load(weights_only=True)` cannot read the file."""
    try:
        import torch
    except ImportError as e:
        raise RuntimeError("torch is not installed") from e

    order = iter(sizes)
    by_ptr: dict[int, str] = {}
    misplaced: list[str] = []

    def place(storage: Any, location: str) -> Any:  # noqa: ANN401, ARG001 - map_location's signature; torch's storage type
        # torch.load calls this once per storage, in the order the pickle names them first: the order of `sizes`.
        # A size that differs means that order does not hold, and the names would go to the wrong storages.
        key = next(order, "")
        if sizes.get(key) != storage.nbytes():
            misplaced.append(key)
        elif storage.nbytes():
            by_ptr[storage.data_ptr()] = key
        return storage

    try:
        obj = torch.load(path, map_location=place, weights_only=True, mmap=True)
    except Exception as e:  # any failure to read means no names, never a failed compression
        refused = re.search(r"GLOBAL ([\w.]+)", str(e))
        hint = f"it holds {refused.group(1)}, which is not on its allow-list" if refused else type(e).__name__
        raise RuntimeError(f"torch.load(weights_only=True) does not read it ({hint})") from e
    if misplaced or next(order, None) is not None:
        raise RuntimeError("torch.load did not read the storages in the order data.pkl names them")
    schema = OptimizerSchema()
    found: dict[str, tuple[str, str, tuple[int, ...] | None]] = {}

    def walk(x: object, at: tuple[str, ...]) -> None:
        if isinstance(x, torch.Tensor):
            storage = x.untyped_storage()
            key = by_ptr.get(storage.data_ptr()) if storage.nbytes() else None
            if key is not None and key not in found:
                whole = x.storage_offset() == 0 and x.is_contiguous() and x.nbytes == storage.nbytes()
                found[key] = ("/".join(at), schema.role(at), tuple(x.shape) if whole else None)
        elif isinstance(x, dict):
            for k, v in x.items():
                walk(v, (*at, str(k)))
        elif isinstance(x, (list, tuple)):
            for i, v in enumerate(x):
                walk(v, (*at, str(i)))

    walk(obj, ())
    return found


[docs] @register_format class TorchZip(CheckpointFormat): """A file `torch.save` wrote in its zip layout (PyTorch 1.6 and later), whatever object it holds.""" kind = "torch-zip" names = ("*.pt", "*.pth", "*.bin", "*.ckpt") in_directory = ( "optimizer.pt", "optimizer.bin", "pytorch_model*.bin", "*.ckpt", "mp_rank_*_model_states.pt", "*_optim_states.pt", "model_optim_rng.pt", ) frameworks = ( ("Hugging Face Transformers", "optimizer.pt, pytorch_model*.bin"), ("Accelerate", "optimizer.bin, pytorch_model*.bin"), ("PyTorch Lightning", "*.ckpt"), ("DeepSpeed", "mp_rank_*_model_states.pt, *_optim_states.pt"), ("Megatron-LM (torch format)", "model_optim_rng.pt"), ("PyTorch", "*.pt, *.pth, *.bin, named on their own"), )
[docs] def split(self, path: Path) -> Split: raw = splice.open_map(path, "a zip file written by torch.save") storages, keys = _layout(path, raw) by_key = {s.key: s.end - s.start for s in storages} try: named = _names_and_roles(path, {k: by_key[k] for k in keys}) except RuntimeError as e: warnings.warn( RolesUnknownWarning(f"{path}: {e}; its tensors are stored with the role 'other'"), stacklevel=2 ) named = {} spans, used = [], set() for s in storages: name, role, shape = named.get(s.key, (f"storage/{s.key}", "other", None)) if name in used: name = f"{name}#{s.key}" used.add(name) if shape is None or prod(shape) != s.numel: # a view of part of a storage, or a dtype read as uint8 shape = (s.numel,) spans.append(Span(s.start, s.end, TensorMeta(name=name, dtype=s.dtype, shape=shape, role=role), s.crc_at)) records, source, remainder = splice.cut(path, raw, spans) return Split(records, source, remainder)
[docs] def join( self, source: dict[str, JsonValue], remainder: bytes, tensors: Iterable[bytes], out: Path, *, exact: bool ) -> None: splice.join(source, remainder, tensors, out, exact=exact)