コーデック、Assigner、状態スキーマ、ファイル形式を追加する

コーデック、Assigner、状態スキーマ、チェックポイントのファイル形式は、Jabara のほかの部分を変えずに追加できる。どれも抽象基底クラスのサブクラスである。コーデック、Assigner、状態スキーマの四つの例は、クローンの examples/extend/ にある完全なスクリプトである。各スクリプトはクラスを定義し、一時ディレクトリにアーカイブを書き出し、読み込んだ内容を検査する。リポジトリのテストは、この四つをすべて実行する。ファイル形式は、組み込みの形式とそのテストで示す。

コーデックを追加する

コーデックは、一つのテンソルのチャンク一つをバイト列に変換し、元に戻す。Codec のサブクラスを作り、id と lossless を設定し、encode と decode を実装して、そのクラスを @register_codec で登録する。次のコーデックは、各チャンクをバイトプレーンに分け、各プレーンを標準ライブラリの lzma で圧縮する。

"""A codec: split each tensor into byte planes and compress every plane with lzma from the standard library."""

import lzma
import struct
import tempfile
from pathlib import Path

import numpy as np

from jabara.assign import CodecChoice, UniformAssigner
from jabara.codecs import Codec, register_codec
from jabara.container import Archive, write_archive
from jabara.types import TensorMeta, TensorRecord


@register_codec
class ByteGroupLzma(Codec):
    id = "bytegroup-lzma/1"
    lossless = True

    def encode(self, data: memoryview, meta: TensorMeta, ref: memoryview | None = None) -> bytes:
        planes = np.frombuffer(data, dtype=np.uint8).reshape(-1, meta.itemsize).T
        packed = [lzma.compress(plane.tobytes()) for plane in planes]
        return struct.pack(f"<{len(packed)}Q", *map(len, packed)) + b"".join(packed)

    def decode(self, payload: memoryview, meta: TensorMeta, raw_length: int, ref: memoryview | None = None) -> bytes:
        size = meta.itemsize
        lengths = struct.unpack(f"<{size}Q", payload[: 8 * size])
        out, pos = np.empty((size, raw_length // size), dtype=np.uint8), 8 * size
        for i, n in enumerate(lengths):
            out[i] = np.frombuffer(lzma.decompress(payload[pos : pos + n]), dtype=np.uint8)
            pos += n
        return np.transpose(out).tobytes()


weights = np.random.default_rng(0).standard_normal((64, 64)).astype("<f4")
record = TensorRecord(TensorMeta(name="w", dtype="float32", shape=weights.shape), weights)
with tempfile.TemporaryDirectory() as tmp:
    path = Path(tmp) / "checkpoint.jbr"
    write_archive(path, [record], assign=UniformAssigner(CodecChoice(codec_id=ByteGroupLzma.id)))
    with Archive.open(path) as archive:
        assert archive.read("w") == weights.tobytes()
  • id は <name>/<version> の形式である。アーカイブはこれを保存し、読み出し側はこれでコーデックを探す。ペイロードの形式を変えたら、バージョンを変える。register_codec は登録済みの ID に対して ValueError を発生させるので、コーデックを登録するモジュールは一度だけインポートする。

  • meta からテンソルの dtype、形状、役割が分かるので、コーデックはこれらから方式を選べる。data と payload は memoryview オブジェクトで、encode は bytes を返す。

  • decode は、bytes、新しい bytearray、または新しいバッファの上にある符号なしバイトの memoryview(形式 B、連続した 1 次元)を返す。返したバッファは呼び出し側が所有する。これ以外の型を返すと、コーデックの名前を含む TypeError が発生する。1 次元で形式が B の連続した memoryview でないもの、たとえば float32 配列の arr.data やストライド付きのビューを返したときも同じである。

  • 出力を bytearray や NumPy 配列に組み立てるコーデックは、それをコピーせずに返せる。スレッドプール上ではこの違いが大きい。チャンク全体のコピーは GIL を保持したまま行われるので、プールのスレッドはチャンクを一つずつしかコピーできないからである。

  • 可逆なコーデックでは、長さが meta.itemsize の倍数であるすべてのチャンク(長さ 0 のチャンクを含む)について、decode(encode(x)) が x と同じバイト列を返さなければならない。decode は、返すべきバイト列の長さを raw_length として受け取る。

  • Jabara はチャンクをスレッドプール上で処理し、異なるテンソルのチャンクも同時に扱うので、複数のスレッドが一つのコーデックのインスタンスを同時に呼び出すことがある。呼び出しごとの状態を self に持たせない。

  • 非可逆なコーデックは lossless = False を設定し、決定的でなければならない。つまり、同じペイロードは常に同じバイト列に復号される必要がある。このコーデックでアーカイブを書き出すには allow_lossy=True が必要になる(非可逆なコーデックを明示的に選び、記録された誤差を読む を参照)。

  • 差分コーデックは needs_ref = True を設定し、ベースのテンソルの同じチャンクを ref として受け取る(ベースとの差分としてチェックポイントを保存する を参照)。

jabara コマンドが扱えるのは組み込みのコーデックだけである。自分のモジュールで登録したコーデックは、そのモジュールをインポートする Python のコードで、write_archive、save_state、jabara.bench.compare と組み合わせて使える。

パラメータを持つコーデックを追加する

コーデックは、設定を入れ子の Params モデルとして宣言し、self.params から読む。Params は、frozen=True と extra="forbid" を指定した pydantic の BaseModel である。次のコーデックは、標準ライブラリの zlib で各チャンクを圧縮し、圧縮レベルをパラメータとして受け取る。

"""A codec with a validated parameter: zlib from the standard library, with its compression level as a `Params`."""

import tempfile
import zlib
from pathlib import Path

import numpy as np
from pydantic import BaseModel, JsonValue, ValidationError

from jabara.assign import CodecChoice, UniformAssigner
from jabara.codecs import Codec, register_codec
from jabara.container import Archive, write_archive
from jabara.types import TensorMeta, TensorRecord


@register_codec
class ZlibCodec(Codec):
    id = "zlib/1"
    lossless = True

    class Params(BaseModel, frozen=True, extra="forbid"):
        level: int = 6

    params: Params

    def encode(self, data: memoryview, meta: TensorMeta, ref: memoryview | None = None) -> bytes:
        return zlib.compress(data, self.params.level)

    def decode(self, payload: memoryview, meta: TensorMeta, raw_length: int, ref: memoryview | None = None) -> bytes:
        return zlib.decompress(payload)


weights = np.random.default_rng(0).standard_normal((64, 64)).astype("<f4")
record = TensorRecord(TensorMeta(name="w", dtype="float32", shape=weights.shape), weights)
assign = UniformAssigner(CodecChoice(codec_id="zlib/1", params={"level": 9}))
with tempfile.TemporaryDirectory() as tmp:
    path = Path(tmp) / "checkpoint.jbr"
    write_archive(path, [record], assign=assign)
    with Archive.open(path) as archive:
        assert archive.read("w") == weights.tobytes()
        # The index records the parameters, so a reader decodes without being told them.
        assert archive.index_by_name["w"].params == {"level": 9}
    # `Params` refuses an unknown or ill-typed parameter, when write_archive builds the codec for the tensor.
    bad_params: list[dict[str, JsonValue]] = [{"lvl": 9}, {"level": "high"}]
    for bad in bad_params:
        try:
            write_archive(
                Path(tmp) / "bad.jbr", [record], assign=UniformAssigner(CodecChoice(codec_id="zlib/1", params=bad))
            )
        except ValidationError:
            pass
        else:
            raise AssertionError(f"{bad} was accepted")
  • Params のフィールドには、すべて既定値を与える。CodecChoice がパラメータを省くと、既定値が使われる。

  • CodecChoice.params は JSON オブジェクトで、CodecChoice 自体はこれを検査しない。write_archive が選択からテンソルごとにコーデックを作るときに、Params モデルがオブジェクトを検査する。未知の名前や型の違う値があると、pydantic.ValidationError が発生する。スクリプトは、保存と読み込みの往復を確かめたあとで、この二つを試す。

  • アーカイブのインデックスには、テンソルごとの全パラメータが既定値を補った形で保存されるので、読み出し側はインデックスだけからコーデックを作れる。スクリプトは archive.index_by_name から params を読む。

  • クラス本体の params: Params は、self.params の型を型チェッカに伝えるだけである。

Assigner を追加する

Assigner は、各テンソルの CodecChoice を選ぶ。Assigner のサブクラスを作り、choose を実装する。次の例は、重みをビット単位で同一に保ち、Adam のモーメントをすべて 8 ビットのコードとして保存する。

"""An assigner: keep weights bit-exact and store every Adam moment as 8-bit codes."""

import tempfile
from pathlib import Path

import numpy as np

from jabara.assign import Assigner, CodecChoice
from jabara.container import Archive, write_archive
from jabara.types import TensorMeta, TensorRecord


class MomentsLossy(Assigner):
    def choose(self, meta: TensorMeta) -> CodecChoice:
        if meta.role.startswith("adam_"):
            return CodecChoice(codec_id="quant8-linear/1")  # lossy: write_archive needs allow_lossy=True
        return CodecChoice(codec_id="bytegroup-zstd/1")


rng = np.random.default_rng(0)
arrays = {
    role: (rng.standard_normal(4096) * scale).astype("<f4") for role, scale in [("weight", 0.02), ("adam_m", 1e-3)]
}
records = [TensorRecord(TensorMeta(name=r, dtype="float32", shape=a.shape, role=r), a) for r, a in arrays.items()]
with tempfile.TemporaryDirectory() as tmp:
    path = Path(tmp) / "checkpoint.jbr"
    write_archive(path, records, assign=MomentsLossy(), allow_lossy=True)
    with Archive.open(path) as archive:
        assert archive.read("weight") == arrays["weight"].tobytes()
        moment = np.frombuffer(archive.read("adam_m"), dtype="<f4")
        step = (arrays["adam_m"].max() - arrays["adam_m"].min()) / 255
        assert 0 < np.abs(moment - arrays["adam_m"]).max() <= step  # close, not bit-exact

choose はすべてのテンソルについて呼ばれ、そのテンソルの TensorMeta、つまり名前、dtype、形状、役割を参照できる。非可逆なコーデックを選ぶなら、その Assigner を使う場所で allow_lossy=True が必要になる。インスタンスは、このスクリプトのように assign= として渡すか、compress_file、save_state、jabara.hf.attach に渡す。JabaraCheckpointIO も assign= を受け取るが、非可逆なテンソルは書き出さないので、この Assigner では LossyNotAllowedError が発生する。役割だけで選ぶなら、自分でクラスを書かずに RoleAssigner を使う(役割ごとにコーデックを選ぶ を参照)。

状態スキーマを追加する

スキーマは、入れ子の状態の中での各テンソルのパスから、そのテンソルの役割を決める。StateSchema のサブクラスを作り、role を実装する。次の例は、Adam とはキーが異なる Adafactor の状態に役割を付ける。

"""A state schema: set the roles of an Adafactor state, whose keys differ from Adam's, and keep them in the archive."""

import tempfile
from pathlib import Path

import numpy as np

from jabara.container import Archive, write_archive
from jabara.schemas import StateSchema
from jabara.skeleton import flatten
from jabara.types import TensorMeta, TensorRecord

ROLES = {"exp_avg_sq_row": "adafactor_row", "exp_avg_sq_col": "adafactor_col", "step": "step"}


class AdafactorSchema(StateSchema):
    def role(self, path: tuple[object, ...]) -> str:
        return ROLES.get(str(path[-1]), "other") if path else "other"


state = {
    "state": {
        0: {"step": np.array([10], "<i8"), "exp_avg_sq_row": np.ones(8, "<f4"), "exp_avg_sq_col": np.ones(4, "<f4")}
    }
}
skeleton, leaves = flatten(state, lambda x: isinstance(x, np.ndarray))
schema = AdafactorSchema()
records = []
for name, leaf in leaves:
    array = np.asarray(leaf)
    meta = TensorMeta(name=name, dtype=str(array.dtype), shape=array.shape, role=schema.role(tuple(name.split("/"))))
    records.append(TensorRecord(meta, array))
with tempfile.TemporaryDirectory() as tmp:
    path = Path(tmp) / "checkpoint.jbr"
    write_archive(path, records, skeleton=skeleton)
    with Archive.open(path) as archive:
        roles = {name: archive.meta(name).role for name in archive.names()}
assert roles == {
    "state/0/step": "step",
    "state/0/exp_avg_sq_row": "adafactor_row",
    "state/0/exp_avg_sq_col": "adafactor_col",
}

path は、テンソルに至るキーとインデックスのタプルなので、path[-1] はテンソル自身のキーである。このスクリプトは、NumPy 配列の入れ子の状態を平坦化し、write_archive でアーカイブを書き出す。PyTorch の状態では、素の PyTorch のループで状態を保存して読み込む と同じように、スキーマのインスタンスを schema= として save_state に渡す。役割は任意の文字列なので、スキーマで adafactor_row のような役割を追加でき、RoleAssigner でそれらの役割にコーデックを選べる。

チェックポイントのファイル形式を追加する

形式は、チェックポイントのファイルをテンソルに分解し、元のファイルに組み立て直す。形式を追加すると、compress_file、decompress_file、load_records がそのファイルを受け取るようになる。CheckpointFormat のサブクラスを作り、kind、names、in_directory、frameworks を設定し、split と join を実装して、@register_format で登録する。NumPy の .npy ファイルの組み込みの形式が、エントリ一つの全体である。.npy ファイルは、テキストのヘッダのあとに一つの配列のバイト列が続く。Npy クラスは空行を除いて 17 行で、ヘッダを読むために呼ぶ二つの関数がさらに 33 行である(テストが両方の行数を確かめる)。

def dtype_name(dtype: np.dtype[np.generic]) -> str | None:
    """The Jabara dtype name of a little-endian (or single-byte) NumPy dtype, or None for any other dtype."""
    if dtype.byteorder == ">" or dtype.hasobject or dtype.fields is not None or dtype.subdtype is not None:
        return None
    name = dtype.name
    return name if name in DTYPE_ITEMSIZE and np.dtype(name).itemsize == dtype.itemsize else None


def array_span(raw: mmap.mmap, start: int, end: int, name: str, bad: Callable[[str], ArchiveFormatError]) -> Span:
    """The array of the `.npy` bytes `raw[start:end]`, named `name`: role `weight` for a float array, and `uint8`
    with role `other` for a dtype Jabara does not carry (its bytes are kept as they are)."""
    if raw[start : start + 6] != _MAGIC or end - start < 10:  # noqa: PLR2004 - the magic, version, and length
        raise bad(f"{name} is not a .npy array")
    version = raw[start + 6]
    if version not in _VERSIONS:
        raise bad(f"{name} is a .npy array of version {version}, which Jabara does not know")
    size = 2 if version == 1 else 4  # the header length is a uint16 in version 1, a uint32 later
    begin = start + 8 + size + int.from_bytes(raw[start + 8 : start + 8 + size], "little")
    if begin > end:
        raise bad(f"{name} has a .npy header longer than the array")
    try:
        header = ast.literal_eval(raw[start + 8 + size : begin].decode("latin1"))
        dtype, shape = np.dtype(header["descr"]), tuple(int(n) for n in header["shape"])
        fortran = bool(header.get("fortran_order"))
    except (ValueError, TypeError, KeyError, SyntaxError, MemoryError, RecursionError, OverflowError) as e:
        raise bad(f"{name} has a .npy header that does not parse ({type(e).__name__})") from e
    known = dtype_name(dtype)
    if known is None or any(n < 0 for n in shape) or int(np.prod(shape)) * dtype.itemsize != end - begin:
        meta = TensorMeta(name=name, dtype="uint8", shape=(end - begin,), role="other")
    else:
        # A Fortran-order array is recorded with its shape but its bytes in column order: no role invites a lossy
        # codec that would read them in row order.
        role = "weight" if known in FLOAT_DTYPES and not fortran else "other"
        meta = TensorMeta(name=name, dtype=known, shape=shape, role=role)
    return Span(begin, end, meta)


@register_format
class Npy(CheckpointFormat):
    """A NumPy `.npy` file: one array."""

    kind = "npy"
    names = ("*.npy",)
    in_directory = ()
    frameworks = (("NumPy", "*.npy"),)

    def split(self, path: Path) -> Split:
        raw = splice.open_map(path, "a .npy file")

        def bad(msg: str) -> ArchiveFormatError:
            return ArchiveFormatError(f"{path}: {msg}")

        span = array_span(raw, 0, len(raw), "array", bad)
        return Split(*splice.cut(path, raw, [span]))

    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)

テストは np.save でファイルを書き、圧縮して復元し、バイト列を比べる。

@pytest.mark.parametrize(
    "array",
    [
        rng.standard_normal((16, 8)).astype("<f4"),
        np.arange(12, dtype="<i8").reshape(3, 4),
        np.asfortranarray(rng.standard_normal((4, 6))),
        np.float16(1.5) * np.ones(()),
        np.arange(5, dtype=">f4"),  # big-endian: kept as bytes
        np.zeros(0, dtype="<f4"),
    ],
    ids=["float32", "int64", "fortran", "scalar", "big-endian", "empty"],
)
def test_a_npy_file_comes_back_byte_for_byte(array: NDArray[Any], tmp_path: Path) -> None:
    path = tmp_path / "array.npy"
    np.save(path, array)
    ((dtype, shape, role),) = round_trip(path).values()
    if array.dtype.byteorder == ">":
        assert (dtype, role) == ("uint8", "other")
    else:
        fortran = array.ndim > 1 and array.flags.f_contiguous and not array.flags.c_contiguous
        assert (shape, role) == (array.shape, "weight" if array.dtype.kind == "f" and not fortran else "other")
  • kind はアーカイブのインデックスに保存され、decompress_file はそれで形式を見つける。そのため、一度決めたら変えないこと。登録済みの kind や名前のパターンを登録すると、register_format は ValueError を発生させる。

  • names は、単独で指定されたファイルの fnmatch パターンである。in_directory は、compress_dir と jabara compress DIR がチェックポイントのディレクトリから取るファイルのパターンである。スケジューラの状態のように、チェックポイントがテンソルと並べて保存するファイルは含めないこと。ディレクトリはチェックポイントではなくデータとして .npy ファイルを持つこともあるので、Npy は何も挙げない。

  • split は、各テンソルがファイルのどこにあるかを Span として求め、それを jabara.formats.splice.cut に渡す。cut は、レコード、アーカイブのインデックスに保存する source、ファイルのそれ以外のバイト列である remainder を返す。Jabara は remainder をもう一つのテンソル (remainder) として常に可逆に保存する。join はそれらを splice.join に渡し、splice.join がファイルを書き戻す。形式が Split を自分で組み立ててもよい。

  • split は、ファイルが持つコードを実行してはならない。Npy は、Python のリテラルであるヘッダを、コードを実行しない ast.literal_eval で読む。Python オブジェクトの配列は pickle なので、そのバイト列は uint8 として保持し、オブジェクトとして読むことはない。

  • テンソルがビット単位で同一に戻るとき、join(split(f)) は f をバイト単位で同一に組み立て直さなければならない。同一に戻ったかどうかは exact が join に伝える。非可逆なコーデックがどれかのテンソルを保存したときは偽になる。zip のように独自のチェックサムを持つファイルは、それを記録する位置を cut に渡し(Span.crc_at、Checksum)、非可逆に復元したあと splice.join が書き直す。

  • jabara コマンドが知っているのは組み込みの形式だけで、チェックポイントのファイル形式 に各エントリの大きさとともに一覧がある。自分のモジュールで登録した形式は、そのモジュールを import する Python のコードで、compress_file、decompress_file、compress_dir、load_records とともに使える。