"""Lossy 8-bit codecs: `quant8-linear/1` and `quant8-log/1`.
Both work per chunk on the values widened to float64 and store a table of at most 256 reconstruction
values in the tensor's own dtype, then the Zstandard-compressed 8-bit codes that index it.
Decoding is a table lookup on the stored bytes, with no floating-point arithmetic, so a payload decodes
to the same bytes on every machine. NaN, infinities, and a range that overflows float64 raise
`NonFiniteError`; nothing is clamped.
"""
from __future__ import annotations
import struct
from typing import Any
import numpy as np
from pydantic import BaseModel
from jabara.codecs._references import BITSNAP, EIGHT_BIT_OPTIMIZERS, PYTHON_ZSTANDARD
from jabara.codecs.base import Codec, Reference
from jabara.codecs.builtin import _zstd_compress, _zstd_decompress
from jabara.codecs.registry import register_codec
from jabara.errors import NonFiniteError, UnsupportedDtypeError
from jabara.types import FLOAT_DTYPES, TensorMeta
Array = np.ndarray[Any, Any]
_UINT = {2: "<u2", 4: "<u4", 8: "<u8"}
[docs]
def to_float64(buf: bytes | bytearray | memoryview, dtype: str) -> Array:
"""Widen little-endian float bytes to float64; bfloat16 goes through its float32 bit pattern."""
if dtype == "bfloat16":
wide = np.frombuffer(buf, dtype="<u2").astype(np.uint32) << 16
return wide.view(np.float32).astype(np.float64)
values = np.frombuffer(buf, dtype=np.dtype(dtype).newbyteorder("<"))
return values if values.dtype.kind == "c" else values.astype(np.float64)
def _narrow(values: Array, dtype: str) -> bytes:
"""Round float64 values to the nearest value of `dtype`, ties to even, once."""
if dtype != "bfloat16":
return values.astype(np.dtype(dtype).newbyteorder("<")).tobytes()
# Rounding through float32 would round twice. Round to float32 by round-to-odd instead (toward zero, then
# set the last bit if inexact); with 16 spare bits that makes the final round to bfloat16 exact.
wide = values.astype("<f4")
bits = wide.view("<u4")
bits = np.where(np.abs(wide.astype(np.float64)) > np.abs(values), bits - np.uint32(1), bits)
bits = bits | (bits.view("<f4").astype(np.float64) != values).astype(np.uint32)
rounded: Array = (bits + np.uint32(0x7FFF) + ((bits >> 16) & np.uint32(1))) >> 16
return rounded.astype("<u2").tobytes()
def _grid_step(low: float, high: float, steps: int, codec_id: str, name: str) -> float:
"""The step of `steps` equal intervals from `low` to `high`: `(high - low) / steps` in float64, raised to the
next float64 until `rint((high - low) / step)` is at most `steps`. Raising is needed only when the quotient
is subnormal and rounding shrank it (to zero, or so far that the top code would pass 255)."""
step = (high - low) / steps
if not np.isfinite(step):
raise NonFiniteError(f"{codec_id}: tensor {name!r} has a value range that overflows float64")
while high > low and (step == 0 or np.rint((high - low) / step) > steps):
step = float(np.nextafter(step, np.inf))
return float(step)
def _payload(table: Array, dtype: str, signs: bytes, codes: Array, level: int) -> bytes:
entries = _narrow(table, dtype)
# `codes` goes to Zstandard as a buffer, and the parts are joined once: a `+` chain or a `tobytes` copies the
# codes or the payload while holding the GIL, which a pool thread makes alone.
return b"".join([struct.pack("<H", len(entries)), entries, signs, _zstd_compress(codes.data, level)])
def _lookup(payload: memoryview, meta: TensorMeta, count: int, codes_at: int) -> Array:
"""The table entries, as unsigned integers of the item size, that the codes after `codes_at` select."""
(size,) = struct.unpack("<H", payload[:2])
if size > 256 * meta.itemsize or size % meta.itemsize:
raise ValueError("malformed quantization table")
table = np.frombuffer(payload[2 : 2 + size], dtype=_UINT[meta.itemsize])
codes = np.frombuffer(_zstd_decompress(payload[2 + size + codes_at :], count), dtype=np.uint8)
if len(codes) != count or (count and int(np.max(codes)) >= len(table)):
raise ValueError("malformed quantization codes")
return table[codes]
[docs]
class QuantParams(BaseModel, frozen=True, extra="forbid"):
"""`level` is the Zstandard compression level of the 8-bit codes."""
#: The Zstandard compression level of the 8-bit codes.
level: int = 3
class _Quant8(Codec):
lossless = False
Params = QuantParams
params: QuantParams
dtypes = FLOAT_DTYPES
def _values(self, data: memoryview, meta: TensorMeta) -> Array:
if meta.dtype not in self.dtypes:
raise UnsupportedDtypeError(f"{self.id} handles float dtypes only, got {meta.dtype}")
values = to_float64(data, meta.dtype)
if not np.isfinite(values).all():
raise NonFiniteError(f"{self.id}: tensor {meta.name!r} holds NaN or Inf")
return values
[docs]
@register_codec
class Quant8LinearCodec(_Quant8):
"""8-bit codes for 255 equal steps from the chunk minimum to its maximum.
Code ``c`` stands for ``lo + c * scale``.
Per chunk, ``scale = (max - min) / 255`` (the exact quotient). With ``tiny`` the smallest positive subnormal of
the dtype, ``abs(x - x_hat) <= m * scale / 2 + 2**-48 * max(abs(x)) + tiny``, where ``m`` is 1 for float64 and
2 for float16, bfloat16, and float32. No decoded value leaves ``[min, max]``. A chunk whose items all have the
same bits decodes exactly, ``-0.0`` included.
Zeros keep no sign of their own. Entry 0 is ``lo``, the chunk minimum, and no other entry is ``-0.0``. When the
minimum is zero, every zero gets code 0 and decodes to ``-0.0`` if the chunk holds a ``-0.0``, else to ``+0.0``,
so a chunk that mixes ``0.0`` and ``-0.0`` decodes all its zeros to ``-0.0``. When the minimum is negative, a zero
decodes to ``+0.0`` or to a nonzero value within the bound, so no zero decodes to ``-0.0``.
Payload: the table size in bytes (uint16), the table (entry ``c`` is ``lo + c * scale`` kept inside
``[min, max]`` and rounded to the dtype, for ``c`` up to the largest code used), then the
Zstandard-compressed codes.
"""
id = "quant8-linear/1"
references = (Reference(relation="related", work=BITSNAP), Reference(relation="wraps", work=PYTHON_ZSTANDARD))
[docs]
def encode(self, data: memoryview, meta: TensorMeta, ref: memoryview | None = None) -> bytes:
"""Return the table followed by the Zstandard-compressed codes. Raises `UnsupportedDtypeError` for a
dtype that is not a float, and `NonFiniteError` for NaN, an infinity, or a range that overflows float64.
"""
values = self._values(data, meta)
codes: Array = np.zeros(values.size, dtype=np.uint8)
table: Array = np.zeros(0)
if values.size:
low, high = float(values.min()), float(values.max())
# numpy's min returns either zero when a chunk holds both; fix the sign so the documented rule holds on
# every CPU.
if low == 0:
low = -0.0 if np.signbit(values).any() else 0.0
scale = _grid_step(low, high, 255, self.id, meta.name)
if scale:
codes = np.rint((values - low) / scale).astype(np.uint8)
with np.errstate(over="ignore"): # c * scale can pass the largest float64 when the range nearly does
grid = low + np.arange(int(np.max(codes)) + 1) * scale
# The exact grid lies in [low, high]; keeping rounded entries there never moves one away from an input.
table = np.clip(grid, low, high)
# An entry just below zero, or clipped to a -0.0 maximum, is -0.0 in the dtype; only entry 0 may be.
table[to_float64(_narrow(table, meta.dtype), meta.dtype) == 0] = 0.0
table[0] = low # low + 0 * scale is +0.0 when low is -0.0
return _payload(table, meta.dtype, b"", codes, self.params.level)
[docs]
def decode(
self, payload: memoryview, meta: TensorMeta, raw_length: int, ref: memoryview | None = None
) -> memoryview:
"""Return the chunk: the table entry of every code, as a memoryview of the new array that holds them."""
return _lookup(payload, meta, raw_length // meta.itemsize, 0).view(np.uint8).data
[docs]
@register_codec
class Quant8LogCodec(_Quant8):
"""Logarithmic steps on the magnitude; the sign of every item is a separate packed bit plane.
Code 0 is the zero code: the item decodes to a signed zero. Codes 1 to 255 are 255 levels of ``ln(abs(x))``
from the chunk's smallest to its largest nonzero magnitude, with ``step = (ln(max) - ln(min)) / 254``;
code ``c`` stands for ``exp(ln_min + (c - 1) * step)``. With ``step`` the exact quotient and ``m`` and ``tiny``
as for the linear codec, ``abs(x - x_hat) <= m * abs(x) * (exp(step / 2) - 1) + 2**-40 * abs(x) + tiny``.
No decoded magnitude leaves ``[min, max]`` of the nonzero magnitudes. Exact zeros, including ``-0.0``, and every sign are kept
exactly. Payload: the table size in bytes (uint16), the table of magnitudes in the dtype (entry 0 is zero),
the packed sign plane (``ceil(n / 8)`` bytes), then the Zstandard-compressed codes.
"""
id = "quant8-log/1"
references = (
Reference(relation="related", work=EIGHT_BIT_OPTIMIZERS),
Reference(relation="wraps", work=PYTHON_ZSTANDARD),
)
[docs]
def encode(self, data: memoryview, meta: TensorMeta, ref: memoryview | None = None) -> bytes:
"""Return the table, the sign plane, and the Zstandard-compressed codes. Raises
`UnsupportedDtypeError` for a dtype that is not a float, and `NonFiniteError` for NaN, an infinity, or a
range that overflows float64.
"""
values = self._values(data, meta)
signs = np.packbits(np.signbit(values)).tobytes()
mags = np.abs(values)
nonzero = mags != 0
codes: Array = np.zeros(values.size, dtype=np.uint8)
table: Array = np.zeros(1 if values.size else 0)
if nonzero.any():
logs = np.log(mags[nonzero])
ln_min, ln_max = float(logs.min()), float(logs.max())
step = _grid_step(ln_min, ln_max, 254, self.id, meta.name)
codes[nonzero] = 1 if step == 0 else 1 + np.rint((logs - ln_min) / step).astype(np.uint8)
with np.errstate(over="ignore"): # exp of a rounded exponent can pass the largest float64
grid = np.exp(ln_min + np.arange(int(np.max(codes))) * step)
# The exact grid lies in [min, max]; keeping rounded entries there never moves one away from an input.
lo, hi = float(mags[nonzero].min()), float(mags[nonzero].max())
table = np.concatenate([[0.0], np.clip(grid, lo, hi)])
return _payload(table, meta.dtype, signs, codes, self.params.level)
[docs]
def decode(
self, payload: memoryview, meta: TensorMeta, raw_length: int, ref: memoryview | None = None
) -> memoryview:
"""Return the chunk: the magnitude of every code from the table, with the sign bit from the plane, as a
memoryview of the new array that holds them.
"""
count = raw_length // meta.itemsize
bits = _lookup(payload, meta, count, (count + 7) // 8)
(size,) = struct.unpack("<H", payload[:2])
plane = np.frombuffer(payload[2 + size : 2 + size + (count + 7) // 8], dtype=np.uint8)
negative = np.unpackbits(plane, count=count).astype(bits.dtype)
out: Array = (bits | (negative << (8 * meta.itemsize - 1))).view(np.uint8)
return out.data