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"})
[ドキュメント]
@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
[ドキュメント]
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"")