Source code for jabara.types

"""Core data shapes shared by every layer. See DESIGN.md."""

from __future__ import annotations

from dataclasses import dataclass
from math import prod
from typing import Any

import numpy as np
from numpy.typing import NDArray
from pydantic import BaseModel, NonNegativeInt, field_validator

Role = str
JSON = Any
Buffer = bytes | bytearray | memoryview | NDArray[Any]

#: Bytes per element for every dtype name an archive may carry. numpy has no bfloat16, so the
#: core treats tensors as raw bytes and only ever needs the item size.
DTYPE_ITEMSIZE: dict[str, int] = {
    "bool": 1,
    "uint8": 1,
    "int8": 1,
    "uint16": 2,
    "int16": 2,
    "float16": 2,
    "bfloat16": 2,
    "uint32": 4,
    "int32": 4,
    "float32": 4,
    "uint64": 8,
    "int64": 8,
    "float64": 8,
    "complex64": 8,
    "complex128": 16,
}

#: The float dtypes: the ones `DefaultAssigner` sends to `bytegroup-zstd/1` and the quantizers accept.
FLOAT_DTYPES: frozenset[str] = frozenset({"float16", "bfloat16", "float32", "float64"})


[docs] class TensorMeta(BaseModel, frozen=True, extra="forbid"): """The name, dtype, shape, and role of a tensor. `dtype` must be a name in `DTYPE_ITEMSIZE`, and `shape` holds non-negative sizes. """ #: The tensor's name, such as `state/0/exp_avg`. name: str #: The dtype name, a key of `DTYPE_ITEMSIZE`. dtype: str #: The size of each dimension. shape: tuple[NonNegativeInt, ...] #: What the tensor is for, such as `weight` or `adam_m`; `other` when no schema names it. role: Role = "other" @field_validator("dtype") @classmethod def _known_dtype(cls, dtype: str) -> str: if dtype not in DTYPE_ITEMSIZE: raise ValueError(f"unsupported dtype {dtype!r}") return dtype @property def itemsize(self) -> int: """Bytes per element.""" return DTYPE_ITEMSIZE[self.dtype] @property def nbytes(self) -> int: """Bytes in the whole tensor.""" return prod(self.shape) * self.itemsize
[docs] @dataclass(frozen=True) class TensorRecord: """A tensor as raw little-endian bytes (`data`) with its `meta`. `len(data)` equals `meta.nbytes`. `data` is read in place, without a copy, so it must not change while a call that was given the record runs. """ #: The name, dtype, shape, and role. meta: TensorMeta #: The tensor's bytes, little-endian. data: Buffer
[docs] def as_memoryview(data: Buffer) -> memoryview: """View any supported buffer as flat unsigned bytes without copying.""" if isinstance(data, np.ndarray): if not data.flags.c_contiguous: raise ValueError("ndarray buffers must be C-contiguous") if data.size == 0: return memoryview(b"") # memoryview.cast rejects zero-size shapes return data.data.cast("B") view = memoryview(data) return view.cast("B") if view.nbytes else memoryview(b"")