Source code for jabara.assign

"""Choosing a codec per tensor. See DESIGN.md, "Assignment"."""

from __future__ import annotations

from abc import ABC, abstractmethod
from collections.abc import Mapping

from pydantic import BaseModel, JsonValue

from jabara.types import FLOAT_DTYPES, TensorMeta


[docs] class CodecChoice(BaseModel, frozen=True, extra="forbid"): """A codec id with its parameters. `params` is checked against the codec's `Params` model. `fallback` is used for a delta codec when the base has no matching tensor; it must not need a base. """ #: The id of the codec, such as `bytegroup-zstd/1`. codec_id: str #: The codec's parameters; those left out take the codec's defaults. params: dict[str, JsonValue] = {} #: Used when a delta codec is chosen but the base has no matching tensor; it must not need a base. fallback: CodecChoice | None = None
[docs] class Assigner(ABC): """Picks the codec for each tensor. Subclass it and implement `choose`."""
[docs] @abstractmethod def choose(self, meta: TensorMeta) -> CodecChoice: """Return the `CodecChoice` for the tensor that `meta` describes."""
[docs] class DefaultAssigner(Assigner): """`bytegroup-zstd/1` for float dtypes and `zstd/1` for everything else."""
[docs] def choose(self, meta: TensorMeta) -> CodecChoice: """Return the default choice for the dtype of `meta`.""" return CodecChoice(codec_id="bytegroup-zstd/1" if meta.dtype in FLOAT_DTYPES else "zstd/1")
[docs] class UniformAssigner(Assigner): """Applies one choice to float tensors and the default choice to every other tensor.""" def __init__(self, choice: CodecChoice) -> None: self.choice = choice
[docs] def choose(self, meta: TensorMeta) -> CodecChoice: """Return `choice` for a float tensor and the default choice otherwise.""" return self.choice if meta.dtype in FLOAT_DTYPES else DefaultAssigner().choose(meta)
[docs] class RoleAssigner(Assigner): """Picks a choice by tensor role. A role that `by_role` does not list goes to `default`, which is `DefaultAssigner()` when omitted. """ def __init__(self, by_role: Mapping[str, CodecChoice], default: Assigner | None = None) -> None: self.by_role = dict(by_role) self.default = default or DefaultAssigner()
[docs] def choose(self, meta: TensorMeta) -> CodecChoice: """Return the choice for the role of `meta`, or the default's choice if the role is not listed.""" return self.by_role.get(meta.role) or self.default.choose(meta)