Source code for jabara.schemas

"""State schemas: set the role of each tensor from its path in the nested state. See DESIGN.md."""

from __future__ import annotations

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

from jabara.types import Role


[docs] class StateSchema(ABC): """Sets the role of each tensor from its path in the nested state. Subclass it and implement `role`."""
[docs] @abstractmethod def role(self, path: tuple[object, ...]) -> Role: """Return the role of the tensor at `path`, a tuple of the keys and indices that lead to it."""
[docs] class OptimizerSchema(StateSchema): """Roles by the last path element: `exp_avg` is `adam_m`, `exp_avg_sq` is `adam_v`, `max_exp_avg_sq` is `adam_vmax`, `momentum_buffer` is `momentum`, `step` is `step`, and anything else is `other`. """ roles: ClassVar[Mapping[str, Role]] = { "exp_avg": "adam_m", "exp_avg_sq": "adam_v", "max_exp_avg_sq": "adam_vmax", "momentum_buffer": "momentum", "step": "step", }
[docs] def role(self, path: tuple[object, ...]) -> Role: """Return the role for the last element of `path`.""" last = path[-1] if path else None return self.roles.get(last, "other") if isinstance(last, str) else "other"
[docs] class MuonSchema(OptimizerSchema): """Like `OptimizerSchema`, but `momentum_buffer` is `muon_momentum`.""" roles: ClassVar[Mapping[str, Role]] = {**OptimizerSchema.roles, "momentum_buffer": "muon_momentum"}
[docs] class WeightsSchema(StateSchema): """Gives every tensor the role `weight`."""
[docs] def role(self, path: tuple[object, ...]) -> Role: # noqa: ARG002 - StateSchema.role's signature """Return `weight`.""" return "weight"