"""Built-in lossless codecs: `raw/1`, `zstd/1`, and `bytegroup-zstd/1`."""
from __future__ import annotations
import struct
import numpy as np
import zstandard
from pydantic import BaseModel
from jabara.codecs._references import LMC, PYTHON_ZSTANDARD, RFC_8878, ZIPNN_PAPER, ZSTD
from jabara.codecs.base import Codec, Reference
from jabara.codecs.registry import register_codec
from jabara.types import TensorMeta
def _zstd_compress(data: bytes | memoryview, level: int) -> bytes:
# A compressor object is not thread-safe, so build one per call.
return zstandard.ZstdCompressor(level=level).compress(data)
def _zstd_decompress(payload: bytes | memoryview, raw_length: int) -> bytes:
# python-zstandard allocates the content size a frame header declares and ignores `max_output_size`, which
# bounds only frames that declare no size, so a crafted header must be refused before decompressing.
if zstandard.frame_content_size(payload) > raw_length:
raise ValueError(f"zstd frame declares more than {raw_length} bytes")
return zstandard.ZstdDecompressor().decompress(payload, max_output_size=max(raw_length, 1))
[docs]
@register_codec
class RawCodec(Codec):
"""Stores the bytes unchanged."""
id = "raw/1"
lossless = True
[docs]
def encode(self, data: memoryview, meta: TensorMeta, ref: memoryview | None = None) -> bytes:
"""Return a copy of the chunk."""
return bytes(data)
[docs]
def decode(self, payload: memoryview, meta: TensorMeta, raw_length: int, ref: memoryview | None = None) -> bytes:
"""Return a copy of the payload. Raises `ValueError` if its length is not `raw_length`."""
if len(payload) != raw_length:
raise ValueError(f"raw payload has {len(payload)} bytes, expected {raw_length}")
return bytes(payload)
[docs]
@register_codec
class ZstdCodec(Codec):
"""Compresses the whole chunk with Zstandard."""
id = "zstd/1"
lossless = True
references = (
Reference(relation="wraps", work=PYTHON_ZSTANDARD),
Reference(relation="wraps", work=ZSTD),
Reference(relation="describes", work=RFC_8878),
)
[docs]
class Params(BaseModel, frozen=True, extra="forbid"):
"""`level` is the Zstandard compression level."""
level: int = 3
params: Params
[docs]
def encode(self, data: memoryview, meta: TensorMeta, ref: memoryview | None = None) -> bytes:
"""Return the chunk compressed with Zstandard."""
return _zstd_compress(data, self.params.level)
[docs]
def decode(self, payload: memoryview, meta: TensorMeta, raw_length: int, ref: memoryview | None = None) -> bytes:
"""Return the decompressed chunk. Raises `ValueError` if the frame declares more than `raw_length` bytes
or its size is not `raw_length`.
"""
out = _zstd_decompress(payload, raw_length)
if len(out) != raw_length:
raise ValueError(f"zstd payload decoded to {len(out)} bytes, expected {raw_length}")
return out
[docs]
@register_codec
class ByteGroupZstdCodec(Codec):
"""Splits the chunk into one byte plane per item byte and compresses each plane with Zstandard. For one-byte
items it is the same as `zstd/1`.
"""
id = "bytegroup-zstd/1"
lossless = True
references = (
Reference(relation="related", work=ZIPNN_PAPER),
Reference(relation="related", work=LMC),
Reference(relation="wraps", work=PYTHON_ZSTANDARD),
)
[docs]
class Params(BaseModel, frozen=True, extra="forbid"):
"""`level` is the Zstandard compression level of every plane."""
level: int = 3
params: Params
[docs]
def encode(self, data: memoryview, meta: TensorMeta, ref: memoryview | None = None) -> bytes:
"""Return the plane lengths followed by the compressed planes. Raises `ValueError` if the chunk is not a
multiple of the item size.
"""
size = meta.itemsize
if size == 1:
return _zstd_compress(data, self.params.level)
if len(data) % size:
raise ValueError(f"chunk of {len(data)} bytes is not a multiple of itemsize {size}")
items = np.frombuffer(data, dtype=np.uint8).reshape(-1, size)
planes = [_zstd_compress(items[:, i].tobytes(), self.params.level) for i in range(size)]
# CPython copies a large join of bytes objects without holding the GIL; `header + b"".join(planes)` would copy
# the payload a second time, holding it, and pool threads would take turns at that copy.
return b"".join([struct.pack(f"<{size}Q", *(len(p) for p in planes)), *planes])
[docs]
def decode(
self, payload: memoryview, meta: TensorMeta, raw_length: int, ref: memoryview | None = None
) -> bytes | memoryview:
"""Rebuild the chunk from its planes, as a memoryview of a new array. Raises `ValueError` for a malformed
payload.
"""
size = meta.itemsize
if size == 1:
return ZstdCodec(self.params).decode(payload, meta, raw_length)
header = 8 * size
if len(payload) < header or raw_length % size:
raise ValueError("malformed bytegroup-zstd payload")
lengths = struct.unpack(f"<{size}Q", payload[:header])
count = raw_length // size
out = np.empty((count, size), dtype=np.uint8)
pos = header
for i, n in enumerate(lengths):
plane = _zstd_decompress(payload[pos : pos + n], count)
if len(plane) != count:
raise ValueError("malformed bytegroup-zstd payload")
out[:, i] = np.frombuffer(plane, dtype=np.uint8)
pos += n
if pos != len(payload):
raise ValueError("malformed bytegroup-zstd payload")
# Not `out.tobytes()`: that copy holds the GIL and faults in a fresh block, so pool threads would take
# turns at it.
return out.reshape(-1).data