"""zipnn/1: the `zipnn` package behind the codec interface."""
from __future__ import annotations
import copy
import threading
import warnings
from typing import TYPE_CHECKING, Protocol
from pydantic import BaseModel
from jabara.codecs._references import ZIPNN, ZIPNN_PAPER
from jabara.codecs.base import Codec, Reference
from jabara.codecs.registry import register_codec
from jabara.errors import MissingDependencyError, UnsupportedDtypeError
from jabara.types import TensorMeta
ZIPNN_DTYPES = frozenset({"float16", "bfloat16", "float32"})
if TYPE_CHECKING:
# zipnn ships no types; these are the parts of it the codec uses.
class _ZipNN(Protocol):
def compress(self, data: bytes | bytearray | memoryview, /) -> bytes | bytearray: ...
def decompress(self, data: bytes | bytearray | memoryview, /) -> bytearray: ...
class _ZipNNClass(Protocol):
def __call__(self, *, method: str, input_format: str, bytearray_dtype: str, threads: int) -> _ZipNN: ...
_ZIPNN: _ZipNNClass | None = None
# `warnings.catch_warnings` is not thread-safe, so two threads must not run the filtered import at once.
_IMPORT_LOCK = threading.Lock()
def _zipnn_class() -> _ZipNNClass:
"""The `ZipNN` class, imported on the first call and kept. Only that import runs under a warnings filter.
Threads that race on the first call take the lock in turn; the first imports, the others find the class.
A failed import is not kept, so the next call tries again.
"""
global _ZIPNN # noqa: PLW0603 - one cached import, set under _IMPORT_LOCK; tests reset it by this name
if _ZIPNN is None:
with _IMPORT_LOCK:
if _ZIPNN is None:
try:
# Importing zipnn imports torch, whose `torch.jit.script` FutureWarning is not the caller's to act on.
with warnings.catch_warnings():
warnings.filterwarnings("ignore", message=r".*torch\.jit\.script", category=FutureWarning)
from zipnn import ZipNN
except ImportError as e:
raise MissingDependencyError(
"codec zipnn/1 needs the zipnn package; "
'install the zipnn extra (add --extra zipnn to your "uv sync --no-dev" command, or run pip install ".[zipnn]")'
) from e
_ZIPNN = ZipNN
return _ZIPNN
def _zipnn(dtype: str, threads: int) -> _ZipNN:
# One instance per call: ZipNN keeps the header of the call in progress on the instance.
return _zipnn_class()(method="zstd", input_format="byte", bytearray_dtype=dtype, threads=threads)
[ドキュメント]
@register_codec
class ZipNNCodec(Codec):
"""The zipnn package, with Zstandard as its entropy coder.
Lossless. Handles float16, bfloat16, and float32. Any other dtype raises `UnsupportedDtypeError`.
The third-party `zipnn` package is imported on first use. It imports torch, so the first call loads torch into
the process. This import hides the `FutureWarning` about `torch.jit.script` that torch issues.
`zipnn` holds the GIL for a whole call and runs the call on threads of its own, so the container's thread pool
cannot run two chunks at once. `with_threads` hands it the caller's thread budget instead; the bytes it writes
are the same for every thread count. An instance from `get_codec` uses one thread.
"""
id = "zipnn/1"
lossless = True
dtypes = ZIPNN_DTYPES
extra = "zipnn"
references = (Reference(relation="wraps", work=ZIPNN), Reference(relation="describes", work=ZIPNN_PAPER))
def __init__(self, params: BaseModel | None = None, *, threads: int = 1) -> None:
super().__init__(params)
self.threads = threads
[ドキュメント]
def with_threads(self, threads: int) -> ZipNNCodec:
"""Return a copy that runs each `zipnn` call on `threads` threads."""
codec = copy.copy(self)
codec.threads = threads
return codec
def _check(self, meta: TensorMeta) -> None:
if meta.dtype not in self.dtypes:
raise UnsupportedDtypeError(f"{self.id} handles {sorted(ZIPNN_DTYPES)}, got {meta.dtype}")
[ドキュメント]
def encode(self, data: memoryview, meta: TensorMeta, ref: memoryview | None = None) -> bytes:
"""Return the chunk compressed with `zipnn`. Raises `UnsupportedDtypeError` for a dtype other than float16,
bfloat16, and float32, and `MissingDependencyError` if the `zipnn` package is not installed.
"""
self._check(meta)
if not len(data):
return b""
# zipnn 0.5 reorders the bits of float32 and bfloat16 input in place, even through a read-only buffer, so
# those get a private copy. It leaves float16 input as it is. It reads the length of a typed view in items.
buf = data.cast("B") if meta.dtype == "float16" else bytearray(data)
return bytes(_zipnn(meta.dtype, self.threads).compress(buf))
[ドキュメント]
def decode(
self, payload: memoryview, meta: TensorMeta, raw_length: int, ref: memoryview | None = None
) -> bytes | bytearray:
"""Return the chunk decompressed with `zipnn`. Raises the same errors as `encode`."""
self._check(meta)
if not raw_length:
return b""
out: bytearray = _zipnn(meta.dtype, self.threads).decompress(payload)
return out