jabara.files のソースコード

"""Compress and restore checkpoint files and directories. See DESIGN.md."""

from __future__ import annotations

import json
import os
import re
from collections.abc import Iterator, Sequence
from contextlib import ExitStack, closing, contextmanager
from pathlib import Path
from typing import NamedTuple

from jabara import _durable
from jabara.assign import Assigner, CodecChoice, DefaultAssigner, UniformAssigner
from jabara.container import MAGIC, Archive, ArchiveInfo, BaseRef, write_archive
from jabara.errors import ArchiveFormatError, BaseMismatchError, JabaraError, UnsupportedDtypeError
from jabara.formats import CheckpointFormat, format_in_directory, format_of_file, format_of_kind, formats
from jabara.formats.safetensors import _DTYPES, write_safetensors
from jabara.torch import load_state
from jabara.types import TensorMeta, TensorRecord

#: The suffix an archive adds to the name of the file it restores.
SUFFIX = ".jbr"
#: The name of the tensor that holds the bytes of a file that are not tensor data (see `Split.remainder`).
REMAINDER = "(remainder)"
_SAFETENSORS_DTYPES = {name: code for code, name in _DTYPES.items()}
BASE_FALLBACK = CodecChoice(codec_id="bytegroup-zstd/1")
DELTA_CODEC = CodecChoice(codec_id="xor-delta/1", fallback=BASE_FALLBACK)


def _archive_files(directory: Path) -> list[Path]:
    return [p for p in sorted(directory.glob(f"*{SUFFIX}")) if p.is_file()]


[ドキュメント] @contextmanager def open_bases( base: str | os.PathLike[str] | Sequence[str | os.PathLike[str]] | None, *, to_write: bool = False ) -> Iterator[list[Archive]]: """The base archives `base` names, open: none for None, the archive itself for a file, and every `*.jbr` file of a directory, in name order. A sequence of paths stands for each of them in turn. To write against a directory, it must hold an archive, and every checkpoint file in it must have its archive beside it, so that no tensor silently loses its reference. A base that is itself a delta archive (a chain, `--delta previous`) is opened with its own bases, which are the archives with the recorded index CRC-32 among those beside it: in its directory, in the other subdirectories of its parent, and in the parent. `BaseMismatchError` names the one that is missing.""" if base is None: yield [] return if not isinstance(base, (str, os.PathLike)): with ExitStack() as stack: yield [a for item in base for a in stack.enter_context(open_bases(item, to_write=to_write))] return b = Path(base) if not b.is_dir(): with ExitStack() as stack: yield [_Chain(stack).open(b)] return dangling = [p.name for p in sorted(b.glob(f"*{SUFFIX}")) if p.is_symlink() and not p.exists()] if dangling: raise FileNotFoundError(f"{b}: base archive {', '.join(dangling)} is a symbolic link to nothing") paths = _archive_files(b) if not paths: raise FileNotFoundError(f"{b}: no *{SUFFIX} archives in this base directory; compress it first") if to_write: bare = [p.name for p in checkpoint_files(b) if not p.with_name(p.name + SUFFIX).exists()] if bare: raise ValueError(f"{b}: base directory holds {', '.join(bare)} without an archive; compress it first") with ExitStack() as stack: chain = _Chain(stack) yield [chain.open(p) for p in paths]
#: The longest chain of bases that is read or written; decoding recurses once per link. MAX_CHAIN = 100 class _Chain: """Opens archives together with the archives they are written against, found beside them, and closes all of them with `stack`. An archive is opened once, however many others are written against it.""" def __init__(self, stack: ExitStack) -> None: self.stack = stack self._opened: dict[str, Archive] = {} self._beside: dict[Path, dict[int, list[Path]]] = {} def open(self, path: Path, trail: tuple[str, ...] = ()) -> Archive: key = os.path.realpath(path) if key in self._opened: return self._opened[key] if key in trail: raise BaseMismatchError(f"{path}: is, through its bases, written against itself") if len(trail) >= MAX_CHAIN: raise BaseMismatchError( f"{path}: is more than {MAX_CHAIN} archives down a chain of bases; keep a long run as several parents" ) bases = [self.open(self._find(path, ref), (*trail, key)) for ref in _index_of(path).refs] archive = self.stack.enter_context(Archive.open(path, base=bases)) self._opened[key] = archive return archive def _find(self, path: Path, ref: BaseRef) -> Path: # Every directory of one parent sees the same archives beside it, so one scan serves the whole chain. directory = Path(os.path.abspath(path.parent)).parent if directory not in self._beside: by_crc: dict[int, list[Path]] = {} for a in _scanned_archives(path.parent): try: by_crc.setdefault(_index_of(a).crc, []).append(a) except (JabaraError, OSError): continue self._beside[directory] = by_crc found = [a for a in self._beside[directory].get(ref.index_crc, []) if not a.samefile(path)] if not found: raise BaseMismatchError( f"{path}: written against base {ref.name!r} (index crc {ref.index_crc}), " "which is not among the archives beside it" ) return next((a for a in found if a.name == ref.name), found[0]) def _kind(archive: Archive) -> object: source = archive.index.source return source.get("kind") if isinstance(source, dict) else None
[ドキュメント] def check_source(src: Path) -> CheckpointFormat: """The format of `src`, a file `compress_file` takes. Raises `FileNotFoundError` or `ValueError` otherwise.""" if not src.is_file(): raise FileNotFoundError(f"{src}: no such file") return format_of_file(src)
class _KeepRemainder(Assigner): """`assign`, except that the remainder of a file is always stored losslessly and never as a delta: it holds the structure of the file, which no tensor codec understands.""" def __init__(self, assign: Assigner | None) -> None: self.assign = assign or DefaultAssigner() def choose(self, meta: TensorMeta) -> CodecChoice: return BASE_FALLBACK if meta.name == REMAINDER else self.assign.choose(meta)
[ドキュメント] def compress_file( path: str | os.PathLike[str], *, keep: bool = False, threads: int | None = None, assign: Assigner | None = None, allow_lossy: bool = False, base: str | os.PathLike[str] | None = None, ) -> ArchiveInfo: """Compress one file next to itself. With `base`, an archive of an earlier checkpoint or a directory of such archives, float tensors are stored as `xor-delta/1` against the tensor of the same name, dtype, and shape in them unless `assign` says otherwise; tensors without one are stored whole. The archive is written and verified under a temporary name and only then renamed to its own, so an archive under the final name has always been verified.""" src = Path(path) fmt = check_source(src) out = src.with_name(src.name + SUFFIX) if out.exists() and (needing := dependants(src.parent, [out])): raise ValueError(f"{out}: is the base of {_names(needing)}; replacing it would make them unreadable") with open_bases(base, to_write=True) as bases: if bases and assign is None: assign = UniformAssigner(DELTA_CODEC) _refuse_base_as_output(out, bases) split = fmt.split(src) if reserved := {"kind", "remainder"} & set(split.source): raise ValueError(f"format {fmt.kind!r}: its source uses the reserved key {min(reserved)!r}") records, source = split.records, {"kind": fmt.kind, **split.source} if split.remainder: if any(r.meta.name == REMAINDER for r in records): raise ArchiveFormatError(f"{src}: a tensor is named {REMAINDER!r}, the name of the file's remainder") meta = TensorMeta(name=REMAINDER, dtype="uint8", shape=(len(split.remainder),), role="other") records = [*records, TensorRecord(meta, split.remainder)] source["remainder"] = REMAINDER assign = _KeepRemainder(assign) with _durable.writing(out) as tmp: info = write_archive( tmp, records, source=source, assign=assign, threads=threads, allow_lossy=allow_lossy, base=bases ) with Archive.open(tmp, base=bases) as archive: archive.verify(threads=threads) if not keep: src.unlink() return info.model_copy(update={"path": os.fspath(out)})
def _refuse_base_as_output(out: Path, bases: list[Archive]) -> None: # write_archive refuses to replace its base, but it writes to the temporary name; the check is on `out`. for b in bases: if out.exists() and out.samefile(b.path): raise ValueError(f"{out}: is the base archive {b.path}; the new archive would replace the base it needs")
[ドキュメント] def restore(archive: Archive, out: Path, *, threads: int | None = None) -> None: """Write the file that `archive`, an open archive of a file in a registered format, was made from, at `out`. Raises `ArchiveFormatError` for an archive of no registered format.""" source = archive.index.source fmt = format_of_kind(source.get("kind") if isinstance(source, dict) else None) if fmt is None or not isinstance(source, dict): raise ArchiveFormatError(f"{archive.path}: not an archive of a file in a registered format") remainder_name = source.get("remainder") names = [n for n in archive.names() if n != remainder_name] remainder = b"" if isinstance(remainder_name, str): with closing(archive._read_many([remainder_name], threads=threads)) as decoded: # noqa: SLF001 - package-internal: Archive keeps its batched read out of the public API remainder = b"".join(next(decoded)[1]) exact = all(t.max_abs_err is None for t in archive.stats()) with closing(archive._read_many(names, threads=threads)) as decoded: # noqa: SLF001 - package-internal: Archive keeps its batched read out of the public API fmt.join(source, remainder, (b"".join(parts) for _, parts in decoded), out, exact=exact)
[ドキュメント] def decompress_file( path: str | os.PathLike[str], *, keep: bool = False, threads: int | None = None, base: str | os.PathLike[str] | Sequence[str | os.PathLike[str]] | None = None, ) -> Path: """Restore the file an archive was made from. A delta archive needs `base`, the archive it was written against or a directory that holds the archives it was written against.""" src = Path(path) if src.suffix != SUFFIX: raise ValueError(f"{src}: not a {SUFFIX} archive") out = src.with_suffix("") if out.exists(): raise FileExistsError(f"{out}: already exists") with open_bases(base) as bases, Archive.open(src, base=bases) as archive: kind = _kind(archive) if format_of_kind(kind) is not None: restore(archive, out, threads=threads) elif kind == "torch": # an archive that 0.1.0 wrote from a torch file through save_state import torch with _durable.writing(out) as tmp: torch.save(load_state(src, threads=threads, base=bases), tmp) else: raise ArchiveFormatError(f"{src}: source kind {kind!r} has no file to restore; use export-weights") if not keep: src.unlink() return out
[ドキュメント] def checkpoint_files(path: str | os.PathLike[str]) -> list[Path]: """The files `compress_dir` takes from the directory `path`, in name order: the regular files whose names a format takes in a directory (`jabara.formats`), except a file that already is a Jabara archive, such as a `.ckpt` that the Lightning plugin writes.""" found = [] for p in sorted(Path(path).iterdir()): if p.is_file() and format_in_directory(p) is not None: with p.open("rb") as f: if f.read(len(MAGIC)) != MAGIC: found.append(p) return found
def _natural_key(name: str) -> tuple[list[int | str], str]: """Digit runs compare as numbers, so `checkpoint-200` comes before `checkpoint-1000`. The name itself breaks ties (`a1` and `a01`).""" return [int(t) if i % 2 else t for i, t in enumerate(re.split(r"([0-9]+)", name))], name def _is_checkpoint_dir(directory: Path) -> bool: return any(checkpoint_files(directory)) or bool(_archive_files(directory))
[ドキュメント] def checkpoint_dirs(path: str | os.PathLike[str]) -> list[Path]: """The checkpoint directories of the parent `path`: its immediate subdirectories that hold a file `compress_dir` takes or a `*.jbr` archive, in natural order of name, then `path` itself last if it holds such a file. A Hugging Face `output_dir` keeps the final model beside its `checkpoint-*` directories, hence the last place. One level only: a PEFT checkpoint keeps adapter subdirectories that its loader reads by name, so nothing deeper is a checkpoint. A hidden directory (name starts with `.`) and a symbolic link to a directory are skipped, so the walk never leaves the tree. Raises `FileNotFoundError` or `NotADirectoryError` for a `path` that is no directory. """ root = Path(path) if not root.exists(): raise FileNotFoundError(f"{root}: no such file or directory") if not root.is_dir(): raise NotADirectoryError(f"{root}: not a directory") kids = [d for d in root.iterdir() if not d.name.startswith(".") and not d.is_symlink() and d.is_dir()] found = [d for d in sorted(kids, key=lambda d: _natural_key(d.name)) if _is_checkpoint_dir(d)] return [*found, root] if _is_checkpoint_dir(root) else found
class _Index(NamedTuple): crc: int refs: list[BaseRef] raw: int stored: int def _index_of(archive: Path) -> _Index: with Archive.open(archive) as a: chunks = [c for t in a.index.tensors for c in t.chunks] return _Index( a.index_crc, a.index.base_refs(), sum(c.raw_length for c in chunks), sum(c.length for c in chunks) ) def _names(paths: Sequence[Path]) -> str: shown = ", ".join(str(p) for p in paths[:3]) return shown if len(paths) <= 3 else f"{shown} and {len(paths) - 3} more" # noqa: PLR2004 - how many to name def _scanned_archives(directory: Path) -> list[Path]: """The archives of `directory`, of the other subdirectories of its parent, and of the parent itself. Skips hidden and linked subdirectories, and what it may not read: the parent can be any directory. A `directory` reached through a link has two parents, the one its path names and the one it is in, and both are read.""" seen = {_file_id(directory)} dirs = [directory] # abspath normalises `..` without resolving links; resolve() finds where the directory really is. for parent in [Path(os.path.abspath(directory)).parent, directory.resolve().parent]: try: beside = sorted( d for d in parent.iterdir() if not d.name.startswith(".") and not d.is_symlink() and d.is_dir() ) except OSError: beside = [] for d in [*beside, parent]: if (key := _file_id(d)) not in seen: seen.add(key) dirs.append(d) found = [] for d in dirs: try: found += _archive_files(d) except OSError: continue return found
[ドキュメント] def dependants(directory: Path, archives: Sequence[Path]) -> list[Path]: """The delta archives that cannot be read once `archives`, which are in `directory`, are gone: those written against one of them, among the archives of `directory`, of the other subdirectories of its parent, and of the parent. Bases match by index CRC-32 alone, as `Archive.open` matches (a renamed base still decodes), so an archive with the same index CRC-32 that stays among them is a copy that serves, and no archive depends on that CRC. An archive that cannot be read names no base and is nobody's.""" doomed = set() for a in archives: try: doomed.add(_index_of(a).crc) except (JabaraError, OSError): continue if not doomed: return [] gone = {_file_id(a) for a in archives} staying: list[tuple[Path, _Index]] = [] for a in _scanned_archives(directory): if _file_id(a) in gone: continue try: staying.append((a, _index_of(a))) except (JabaraError, OSError): continue lost = doomed - {index.crc for _, index in staying} return [a for a, index in staying if any(r.index_crc in lost for r in index.refs)]
[ドキュメント] def refuse_to_orphan(directory: Path, archives: Sequence[Path]) -> None: """Raise `ValueError` when deleting `archives`, which `decompress` does unless told to keep them, would leave a delta archive of a sibling checkpoint directory without its base. Decompress those first, or keep the archives.""" if found := dependants(directory, archives): raise ValueError( f"{directory}: {_names(found)} are delta archives written against archives that this would delete; " "decompress those first, or pass --keep" )
[ドキュメント] class ParentScan: """The indexes of the archives in the checkpoint directories `dirs` of one parent, read once and closed: which archive each delta archive is written against, and so in which order the directories can be restored. A base is found by the file name and index CRC-32 that the delta archive records, among the archives of the other directories. An archive whose index cannot be read names no base and is nobody's; reading it fails where it is used. """ def __init__(self, dirs: Sequence[Path]) -> None: self.dirs = list(dirs) self._archives = {d: _archive_files(d) for d in self.dirs} self._index: dict[Path, _Index] = {} self._by_key: dict[tuple[str, int], list[Path]] = {} for a in (a for found in self._archives.values() for a in found): try: index = _index_of(a) except (JabaraError, OSError): continue self._index[a] = index self._by_key.setdefault((a.name, index.crc), []).append(a)
[ドキュメント] def archives(self, directory: Path) -> list[Path]: return self._archives[directory]
[ドキュメント] def sizes(self, directory: Path) -> tuple[int, int]: """The raw and the stored tensor bytes of the readable archives in `directory`.""" found = [self._index[a] for a in self._archives[directory] if a in self._index] return sum(i.raw for i in found), sum(i.stored for i in found)
[ドキュメント] def resolve(self, archive: Path) -> tuple[list[Path], list[BaseRef]]: """The archives of the other directories that `archive` is written against, and the recorded bases that none holds.""" found, missing = [], [] index = self._index.get(archive) for ref in index.refs if index else []: hit = next( (b for b in self._by_key.get((ref.name, ref.index_crc), []) if b.parent != archive.parent), None ) if hit is None: missing.append(ref) else: found.append(hit) return found, missing
[ドキュメント] def chain(self, archive: Path) -> tuple[list[Path], tuple[Path, BaseRef] | None]: """The archives that `archive` needs, its bases and theirs in turn, nearest first, and the first base that no other directory holds with the archive that is written against it, or None when none is missing. A base that a chain reaches twice is listed once.""" found: list[Path] = [] pending = [archive] while pending: current = pending.pop(0) bases, missing = self.resolve(current) if missing: return found, (current, missing[0]) for b in bases: if b not in found and b != archive: found.append(b) pending.append(b) return found, None
[ドキュメント] def bases(self, directory: Path) -> list[Path]: """The base archives that the archives of `directory` need, those they are written against directly. A base of theirs that no other directory holds is as much a failure: the restore would stop at it. `ValueError` for a base that is missing, naming the archive written against it.""" out: list[Path] = [] for a in self._archives[directory]: _, missing = self.chain(a) if missing: owner, ref = missing raise ValueError(f"{a}: {missing_base(ref)}" if owner == a else f"{a}: {owner}: {missing_base(ref)}") out += [b for b in self.resolve(a)[0] if b not in out] return out
[ドキュメント] def restore_order(self) -> list[Path]: """The directories, dependants first: a directory is restored before any directory that holds an archive it needs, because restoring deletes its archives. Natural order otherwise. `ValueError` for a cycle.""" needs = {d: {b.parent for a in self._archives[d] for b in self.resolve(a)[0]} for d in self.dirs} left, order = list(self.dirs), [] while left: free = next((d for d in left if not any(d in needs[o] for o in left)), None) if free is None: raise ValueError(f"{_names(left)}: their archives are each other's bases; cannot order the restore") left.remove(free) order.append(free) return order
[ドキュメント] def missing_base(ref: BaseRef) -> str: return f"base {ref.name} (index crc {ref.index_crc}) is missing or changed"
def _file_id(path: Path) -> tuple[int, int] | None: try: st = path.stat() except FileNotFoundError: return None return st.st_dev, st.st_ino
[ドキュメント] def compress_dir( path: str | os.PathLike[str], *, keep: bool = False, threads: int | None = None, assign: Assigner | None = None, allow_lossy: bool = False, base: str | os.PathLike[str] | None = None, ) -> list[ArchiveInfo]: """Compress each file in the directory that a format takes there (`*.safetensors`, `optimizer.pt`, and the others that `jabara.formats` lists), in name order, and return one `ArchiveInfo` per file. Other files stay. With `base`, the directory of an earlier compressed checkpoint (or one archive of it), each file is delta-coded as `compress_file` codes it: every tensor against the tensor of the same name in any archive of the base, so the two checkpoints may split their tensors over files differently. All or nothing, so the directory stays loadable without Jabara when anything fails: every archive is written and verified next to its original first, and the originals are deleted (unless `keep`) only once all are. A failure deletes the archives this call put in place, an existing archive it replaced included, and re-raises; every original is still in place, and an archive this call did not replace stays. """ if base is not None and Path(base).is_dir() and Path(base).samefile(path): raise ValueError(f"{base}: is the directory being compressed; a base must be an earlier checkpoint") sources = list(checkpoint_files(path)) infos: list[ArchiveInfo] = [] written: list[Path] = [] try: with open_bases(base, to_write=True) as bases: # Checked for every file before the first is written, so that a refusal replaces no archive. for p in sources: _refuse_base_as_output(p.with_name(p.name + SUFFIX), bases) for p in sources: out = p.with_name(p.name + SUFFIX) before = _file_id(out) try: infos.append( compress_file(p, keep=True, threads=threads, assign=assign, allow_lossy=allow_lossy, base=base) ) finally: # Not from `infos`: compress_file can raise after the rename. A new inode means this call put the # archive there, since its temporary file was created while any older archive still existed. if _file_id(out) != before: written.append(out) except BaseException: for out in written: out.unlink(missing_ok=True) raise if not keep: for p in sources: p.unlink() return infos
[ドキュメント] def decompress_dir( path: str | os.PathLike[str], *, keep: bool = False, threads: int | None = None, base: str | os.PathLike[str] | Sequence[str | os.PathLike[str]] | None = None, ) -> list[Path]: """Restore every `*.jbr` file in the directory, in name order, and return the restored paths. Delta archives need `base`, as `decompress_file` does. All or nothing, as `compress_dir`: every file is restored and checked first, and the archives are deleted (unless `keep`) only once all are. A failure deletes the files this call restored and re-raises; every archive stays. """ archives = _archive_files(Path(path)) restored: list[Path] = [] try: for p in archives: out = p.with_suffix("") if not out.exists(): # decompress_file refuses an existing file, which is then not this call's to delete restored.append(out) decompress_file(p, keep=True, threads=threads, base=base) except BaseException: for out in restored: out.unlink(missing_ok=True) raise if not keep: for p in archives: p.unlink() return [p.with_suffix("") for p in archives]
[ドキュメント] def export_weights(archive_path: str | os.PathLike[str], out: str | os.PathLike[str]) -> None: """Write the tensors with role "weight" as a safetensors file.""" out = Path(out) with Archive.open(archive_path) as archive: if _kind(archive) == "safetensors": restore(archive, out) return names = [n for n in archive.names() if archive.meta(n).role == "weight"] if not names: raise ArchiveFormatError(f"{archive_path}: no tensors with role 'weight'") header: dict[str, object] = {} offset = 0 for name in names: meta = archive.meta(name) if meta.dtype not in _SAFETENSORS_DTYPES: raise UnsupportedDtypeError(f"tensor {name!r}: {meta.dtype} cannot be stored in safetensors") header[name] = { "dtype": _SAFETENSORS_DTYPES[meta.dtype], "shape": list(meta.shape), "data_offsets": [offset, offset + meta.nbytes], } offset += meta.nbytes blob = json.dumps(header, separators=(",", ":")).encode("utf-8") with closing(archive._read_many(names, threads=None)) as decoded: # noqa: SLF001 - package-internal: Archive keeps its batched read out of the public API write_safetensors(out, blob + b" " * (-len(blob) % 8), (b"".join(parts) for _, parts in decoded))
def _file_records(p: Path, threads: int | None) -> list[TensorRecord]: if p.suffix == SUFFIX: with Archive.open(p) as archive: source = archive.index.source skip = source.get("remainder") if isinstance(source, dict) else None names = [n for n in archive.names() if n != skip] with closing(archive._read_many(names, threads=threads)) as decoded: # noqa: SLF001 - package-internal: Archive keeps its batched read out of the public API return [TensorRecord(archive.meta(n), b"".join(parts)) for n, parts in decoded] try: fmt = format_of_file(p) except ValueError: patterns = ", ".join(n for f in formats() for n in f.names) raise ValueError(f"{p}: not a checkpoint file Jabara recognises (*{SUFFIX}, {patterns})") from None return fmt.split(p).records
[ドキュメント] def load_records(path: str | os.PathLike[str], *, threads: int | None = None) -> list[TensorRecord]: """The tensors of an archive, a safetensors file, a torch file, or a checkpoint directory, as raw records. A directory yields the files `compress` would take plus its archives, with each tensor name prefixed by the name of the checkpoint file and `/`; an archive counts under the name of the file it restores (`model.safetensors.jbr` as `model.safetensors`), so names match between a compressed and an uncompressed checkpoint directory. A directory that holds both a file and its archive raises `ValueError`. """ p = Path(path) if not p.is_dir(): if not p.exists(): raise FileNotFoundError(f"{p}: no such file or directory") return _file_records(p, threads) records = [] seen: set[str] = set() for f in sorted([*checkpoint_files(p), *_archive_files(p)]): name = f.name.removesuffix(SUFFIX) if name in seen: raise ValueError(f"{p}: holds both {name} and {name}{SUFFIX}; remove one") seen.add(name) records += [ TensorRecord(TensorMeta(**{**r.meta.model_dump(), "name": f"{name}/{r.meta.name}"}), r.data) for r in _file_records(f, threads) ] if not records: raise ValueError(f"{p}: no checkpoint files Jabara recognises") return records