repo
stringclasses
1 value
text
stringclasses
1 value
marin-community/haliax
commit 03862c2981cd83de2f50b20e39b43dc1f79a230f Date: 2022-05-24T00:18:26-07:00 silly readme diff --git a/README.md b/README.md new file mode 100644 index 0000000..9e1c1e9 --- /dev/null +++ b/README.md @@ -0,0 +1,5 @@ +> I hear the wind among the trees <br> +> Playing celestial symphonies; <br> +> I see the branches downward bent, <br> +> Like keys of some great instrument.<br> +> - Henry Wadsworth Longfellow commit bae9c4216fedd3e1a563e1370c4257c3d261895f Date: 2022-05-24T00:18:45-07:00 fix .gitigore diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..7e25864 --- /dev/null +++ b/.gitignore @@ -0,0 +1,132 @@ +# Byte-compiled / optimized / DLL files +__pycache__/ +*.py[cod] +*$py.class + +# C extensions +*.so + +# Distribution / packaging +.Python +build/ +develop-eggs/ +dist/ +downloads/ +eggs/ +.eggs/ +lib/ +lib64/ +parts/ +sdist/ +var/ +wheels/ +pip-wheel-metadata/ +share/python-wheels/ +*.egg-info/ +.installed.cfg +*.egg +MANIFEST + +# PyInstaller +# Usually these files are written by a python script from a template +# before PyInstaller builds the exe, so as to inject date/other infos into it. +*.manifest +*.spec + +# Installer logs +pip-log.txt +pip-delete-this-directory.txt + +# Unit test / coverage reports +htmlcov/ +.tox/ +.nox/ +.coverage +.coverage.* +.cache +nosetests.xml +coverage.xml +*.cover +*.py,cover +.hypothesis/ +.pytest_cache/ + +# Translations +*.mo +*.pot + +# Django stuff: +*.log +local_settings.py +db.sqlite3 +db.sqlite3-journal + +# Flask stuff: +instance/ +.webassets-cache + +# Scrapy stuff: +.scrapy + +# Sphinx documentation +docs/_build/ + +# PyBuilder +target/ + +# Jupyter Notebook +.ipynb_checkpoints + +# IPython +profile_default/ +ipython_config.py + +# pyenv +.python-version + +# pipenv +# According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control. +# However, in case of collaboration, if having platform-specific dependencies or dependencies +# having no cross-platform support, pipenv may install dependencies that don't work, or not +# install all needed dependencies. +#Pipfile.lock + +# PEP 582; used by e.g. github.com/David-OConnor/pyflow +__pypackages__/ + +# Celery stuff +celerybeat-schedule +celerybeat.pid + +# SageMath parsed files +*.sage.py + +# Environments +.env +.venv +env/ +venv/ +ENV/ +env.bak/ +venv.bak/ + +# Spyder project settings +.spyderproject +.spyproject + +# Rope project settings +.ropeproject + +# mkdocs documentation +/site + +# mypy +.mypy_cache/ +.dmypy.json +dmypy.json + +# Pyre type checker +.pyre/ + +# JetBrains +.idea/ diff --git a/requirements.txt b/requirements.txt new file mode 100644 index 0000000..0b02853 --- /dev/null +++ b/requirements.txt @@ -0,0 +1,3 @@ +equinox +transformers +optax commit 65a54d9214b1bcd43574c7a99ba20160f70ba0ad Date: 2022-05-26T10:48:49-07:00 forgot einops diff --git a/requirements.txt b/requirements.txt index 0b02853..54b3988 100644 --- a/requirements.txt +++ b/requirements.txt @@ -1,3 +1,4 @@ equinox transformers optax +einops commit e9842736e8cea8eaf6bf212e038d5c7e706b137f Date: 2022-05-27T16:45:30-07:00 add config, microbatching diff --git a/requirements.txt b/requirements.txt index 54b3988..7a26413 100644 --- a/requirements.txt +++ b/requirements.txt @@ -2,3 +2,5 @@ equinox transformers optax einops +wandb +pyrallis \ No newline at end of file commit 41a9763191de56b49290de5237e484724bb7a966 Date: 2022-05-27T23:48:38-07:00 factor eval better diff --git a/.gitignore b/.gitignore index 7e25864..3533666 100644 --- a/.gitignore +++ b/.gitignore @@ -130,3 +130,7 @@ dmypy.json # JetBrains .idea/ + + +# Wandb stuff +/wandb \ No newline at end of file commit 14daab0b5338a9e4992ff89b37025a3c9f381f00 Date: 2022-05-31T13:28:51-07:00 add in data loader?!? diff --git a/requirements.txt b/requirements.txt index 7a26413..7d41139 100644 --- a/requirements.txt +++ b/requirements.txt @@ -3,4 +3,5 @@ transformers optax einops wandb -pyrallis \ No newline at end of file +pyrallis +pyarrow \ No newline at end of file commit f2ead0da392ee56f440dbe60d8aa79a6c3698e55 Date: 2022-05-31T13:39:38-07:00 cleanup diff --git a/requirements.txt b/requirements.txt index 7d41139..c29d419 100644 --- a/requirements.txt +++ b/requirements.txt @@ -4,4 +4,6 @@ optax einops wandb pyrallis -pyarrow \ No newline at end of file +pyarrow +zstandard +datasets \ No newline at end of file commit 55044763729be635aec3c7b67d275909076f67fa Date: 2022-06-08T21:15:37-07:00 add support for fsspec tokenization so i can use gcs diff --git a/requirements.txt b/requirements.txt index c29d419..a24402a 100644 --- a/requirements.txt +++ b/requirements.txt @@ -6,4 +6,6 @@ wandb pyrallis pyarrow zstandard -datasets \ No newline at end of file +datasets +fsspec +gcsfs \ No newline at end of file commit 6ce8dfcbcff43f564c56135dfa863643903d4123 Date: 2022-06-28T16:06:05-07:00 ignore scratch diff --git a/.gitignore b/.gitignore index 3533666..21b0fa6 100644 --- a/.gitignore +++ b/.gitignore @@ -1,3 +1,5 @@ +/scratch + # Byte-compiled / optimized / DLL files __pycache__/ *.py[cod] commit 67dade3a2052b5dab896a0cda1f7858df5d122ee Date: 2022-07-25T16:59:44-07:00 ok, actually works loading to/from gcs diff --git a/requirements.txt b/requirements.txt index a24402a..b788062 100644 --- a/requirements.txt +++ b/requirements.txt @@ -8,4 +8,5 @@ pyarrow zstandard datasets fsspec -gcsfs \ No newline at end of file +gcsfs +braceexpand \ No newline at end of file commit c28c0a8bd792d0eacd9ba49c739fe66537e71547 Date: 2022-08-03T17:07:46-07:00 renamed psithuros to levanter diff --git a/README.md b/README.md index 9e1c1e9..fa3b6bf 100644 --- a/README.md +++ b/README.md @@ -1,5 +1,10 @@ -> I hear the wind among the trees <br> -> Playing celestial symphonies; <br> -> I see the branches downward bent, <br> -> Like keys of some great instrument.<br> -> - Henry Wadsworth Longfellow +# Levanter + +> You could not prevent a thunderstorm, but you could use the electricity; you could not direct the wind, but you could trim your sail so as to propel your vessel as you pleased, no matter which way the wind blew. <br/> +> — Cora L. V. Hatch + + +Levanter is a library based on [Jax](https:://github.com/google/jax) and [Equinox](https://github.com/patrick-kidger/equinox) +for training [foundation models](https://en.wikipedia.org/wiki/Foundation_models) created by [Stanford's Center for Research +on Foundation Models (CRFM)](https://crfm.stanford.edu/). + commit e6bab23e1d0ff047be462265642a8556915f7913 Date: 2022-08-03T17:11:19-07:00 renamed hapax to haliax diff --git a/README.md b/README.md index fa3b6bf..3344b1c 100644 --- a/README.md +++ b/README.md @@ -8,3 +8,10 @@ Levanter is a library based on [Jax](https:://github.com/google/jax) and [Equino for training [foundation models](https://en.wikipedia.org/wiki/Foundation_models) created by [Stanford's Center for Research on Foundation Models (CRFM)](https://crfm.stanford.edu/). +## Haliax + +> Though you don’t seem to be much for listening, it’s best to be careful. If you managed to catch hold of even just a piece of my name, you’d have all manner of power over me.<br/> +> — Patrick Rothfuss, *The Name of the Wind* + +Haliax is a module (currently) inside Levanter for named tensors, modeled on Alexander Rush's [Tensor Considered Harmful](https://arxiv.org/abs/1803.09868). +It's designed to work with Equinox to make constructing distributed models easier. \ No newline at end of file diff --git a/src/haliax/__init__.py b/src/haliax/__init__.py new file mode 100644 index 0000000..476b6f3 --- /dev/null +++ b/src/haliax/__init__.py @@ -0,0 +1,137 @@ +from .core import * +# creation routines +# we could codegen these or do it dynamically, but Codex will do it for us and it's a bit less weird this way +from .core import _ensure_sequence +import haliax.random as random +from .wrap import wrap_elemwise_unary, wrap_reduction_call + + + +def zeros(shape: AxisSpec, dtype=None) -> NamedArray: + """Creates a NamedArray with all elements set to 0""" + return full(shape, 0, dtype) + +def ones(shape: AxisSpec, dtype=None) -> NamedArray: + """Creates a NamedArray with all elements set to 1""" + return full(shape, 1, dtype) + +def full(shape: AxisSpec, fill_value, dtype=None) -> NamedArray: + """Creates a NamedArray with all elements set to `fill_value`""" + if isinstance(shape, Axis): + return NamedArray(jnp.full(shape=shape.size, fill_value=fill_value, dtype=dtype), (shape, )) + else: + x_shape = tuple(x.size for x in shape) + return NamedArray(jnp.full(shape=x_shape, fill_value=fill_value, dtype=dtype), shape) + + +def zeros_like(a: NamedArray, dtype=None) -> NamedArray: + """Creates a NamedArray with all elements set to 0""" + return NamedArray(jnp.zeros_like(a.array, dtype=dtype), a.axes) + + +def ones_like(a: NamedArray, dtype=None) -> NamedArray: + """Creates a NamedArray with all elements set to 1""" + return NamedArray(jnp.ones_like(a.array, dtype=dtype), a.axes) + + +def full_like(a: NamedArray, fill_value, dtype=None) -> NamedArray: + """Creates a NamedArray with all elements set to `fill_value`""" + return NamedArray(jnp.full_like(a.array, fill_value, dtype=dtype), a.axes) + + +# elementwise unary operations +abs = wrap_elemwise_unary(jnp.abs) +absolute = wrap_elemwise_unary(jnp.absolute) +angle = wrap_elemwise_unary(jnp.angle) +arccos = wrap_elemwise_unary(jnp.arccos) +arccosh = wrap_elemwise_unary(jnp.arccosh) +arcsin = wrap_elemwise_unary(jnp.arcsin) +arcsinh = wrap_elemwise_unary(jnp.arcsinh) +arctan = wrap_elemwise_unary(jnp.arctan) +arctanh = wrap_elemwise_unary(jnp.arctanh) +around = wrap_elemwise_unary(jnp.around) +bitwise_not = wrap_elemwise_unary(jnp.bitwise_not) +cbrt = wrap_elemwise_unary(jnp.cbrt) +ceil = wrap_elemwise_unary(jnp.ceil) +conj = wrap_elemwise_unary(jnp.conj) +conjugate = wrap_elemwise_unary(jnp.conjugate) +copy = wrap_elemwise_unary(jnp.copy) +cos = wrap_elemwise_unary(jnp.cos) +cosh = wrap_elemwise_unary(jnp.cosh) +deg2rad = wrap_elemwise_unary(jnp.deg2rad) +degrees = wrap_elemwise_unary(jnp.degrees) +exp = wrap_elemwise_unary(jnp.exp) +exp2 = wrap_elemwise_unary(jnp.exp2) +expm1 = wrap_elemwise_unary(jnp.expm1) +fabs = wrap_elemwise_unary(jnp.fabs) +fix = wrap_elemwise_unary(jnp.fix) +floor = wrap_elemwise_unary(jnp.floor) +frexp = wrap_elemwise_unary(jnp.frexp) +i0 = wrap_elemwise_unary(jnp.i0) +imag = wrap_elemwise_unary(jnp.imag) +iscomplex = wrap_elemwise_unary(jnp.iscomplex) +isfinite = wrap_elemwise_unary(jnp.isfinite) +isinf = wrap_elemwise_unary(jnp.isinf) +isnan = wrap_elemwise_unary(jnp.isnan) +isneginf = wrap_elemwise_unary(jnp.isneginf) +isposinf = wrap_elemwise_unary(jnp.isposinf) +isreal = wrap_elemwise_unary(jnp.isreal) +log = wrap_elemwise_unary(jnp.log) +log10 = wrap_elemwise_unary(jnp.log10) +log1p = wrap_elemwise_unary(jnp.log1p) +log2 = wrap_elemwise_unary(jnp.log2) +logical_not = wrap_elemwise_unary(jnp.logical_not) +ndim = wrap_elemwise_unary(jnp.ndim) +negative = wrap_elemwise_unary(jnp.negative) +positive = wrap_elemwise_unary(jnp.positive) +rad2deg = wrap_elemwise_unary(jnp.rad2deg) +radians = wrap_elemwise_unary(jnp.radians) +real = wrap_elemwise_unary(jnp.real) +reciprocal = wrap_elemwise_unary(jnp.reciprocal) +rint = wrap_elemwise_unary(jnp.rint) +round = wrap_elemwise_unary(jnp.round) +sign = wrap_elemwise_unary(jnp.sign) +signbit = wrap_elemwise_unary(jnp.signbit) +sin = wrap_elemwise_unary(jnp.sin) +sinc = wrap_elemwise_unary(jnp.sinc) +sinh = wrap_elemwise_unary(jnp.sinh) +square = wrap_elemwise_unary(jnp.square) +sqrt = wrap_elemwise_unary(jnp.sqrt) +tan = wrap_elemwise_unary(jnp.tan) +tanh = wrap_elemwise_unary(jnp.tanh) +trunc = wrap_elemwise_unary(jnp.trunc) + + +# Reduction functions + +all = wrap_reduction_call(jnp.all) +amax = wrap_reduction_call(jnp.amax) +any = wrap_reduction_call(jnp.any) +# argmax = wrap_reduction_call(jnp.argmax) +# argmin = wrap_reduction_call(jnp.argmin) +max = wrap_reduction_call(jnp.max) +mean = wrap_reduction_call(jnp.mean) +min = wrap_reduction_call(jnp.min) +prod = wrap_reduction_call(jnp.prod) +product = wrap_reduction_call(jnp.product) +sometrue = wrap_reduction_call(jnp.sometrue) +std = wrap_reduction_call(jnp.std) +sum = wrap_reduction_call(jnp.sum) +var = wrap_reduction_call(jnp.var) + + +# "Normalization" functions that use an axis but don't change the shape +cumsum = wrap_reduction_call(jnp.cumsum) +cumprod = wrap_reduction_call(jnp.cumprod) +cumproduct = wrap_reduction_call(jnp.cumproduct) + + +__all__ = ["Axis", "NamedArray", "AxisSpec", + "named", "dot", + "zeros", "ones", "full", "zeros_like", "ones_like", "full_like", + "random" + ] + + + + diff --git a/src/haliax/core.py b/src/haliax/core.py new file mode 100644 index 0000000..6df7d91 --- /dev/null +++ b/src/haliax/core.py @@ -0,0 +1,280 @@ +from dataclasses import dataclass +from typing import Sequence, Union, Any, Dict, TypeVar, Optional, Tuple + +import jax +import jax.numpy as jnp +from jax.interpreters.partial_eval import DynamicJaxprTracer +from jaxlib.xla_extension import DeviceArray + +import haliax + + +@dataclass(frozen=True) +class Axis: + name: str + size: int + + +AxisSpec = Union[Axis, Sequence[Axis]] + + +@jax.tree_util.register_pytree_node_class +@dataclass(frozen=True) +class NamedArray: + array: jnp.ndarray + axes: Sequence[Axis] + + def __post_init__(self): + # ensure unique axes for now + if len(set(a.name for a in self.axes)) != len(self.axes): + raise ValueError(f"Axes must be unique, but {self.axes} are not") + + if isinstance(self.array, jax.core.Tracer) or isinstance(self.array, DeviceArray): + s = jnp.shape(self.array) + if s != tuple(a.size for a in self.axes): + raise ValueError(f"Shape of underlying array {s} does not match shape of axes {self.axes}") + + def __array__(self): + return self.array.__array__() + + # shape = property(lambda self: self.array.shape) + dtype = property(lambda self: self.array.dtype) + ndim = property(lambda self: self.array.ndim) + size = property(lambda self: self.array.size) + nbytes = property(lambda self: self.array.nbytes) + + def tree_flatten(self) -> Any: + return ((self.array,), self.axes) + + @classmethod + def tree_unflatten(cls, aux, tree: Any) -> Any: + return cls(*tree, axes=aux) + + def lookup_indices(self, axis: AxisSpec): + """ + For a single axis, returns an int corresponding to the index of the axis. + For multiple axes, returns a tuple of ints corresponding to the indices of the axes. + + If the axis is not present, returns None for that position + """ + if isinstance(axis, Axis): + try: + return self.axes.index(axis) + except ValueError: + return None + else: + return tuple(self.lookup_indices(a) for a in axis) + + # np.ndarray methods: + def all(self, axis: Optional[AxisSpec] = None, out=None, keepdims=None) -> Any: + return haliax.all(self, axis=axis, out=out, keepdims=keepdims) + + def any(self, axis: Optional[AxisSpec] = None, out=None, keepdims=None) -> Any: + return haliax.any(self, axis=axis, out=out, keepdims=keepdims) + + # def select(self, axis: Axis, index: Union[int, 'NamedArray', jnp.ndarray]) -> Any: + # if isinstance(index, NamedArray): + # index = index.array + + # TODO + # def argmax(self, axis: Optional[int] = None, out=None, keepdims=None) -> Any: + # ... + # + # def argmin(self, axis: Optional[int] = None, out=None, keepdims=None) -> Any: + # ... + # + # def argpartition(self, kth, axis=-1, kind='introselect', order=None) -> Any: + # ... + # + # def argsort(self, axis: Optional[int] = -1, kind='quicksort', order=None) -> Any: + # ... + + def astype(self, dtype) -> Any: + return NamedArray(self.array.astype(dtype), self.axes) + + # TODO + # def clip(self, a_min=None, a_max=None, out=None) -> Any: + # ... + + # def compress(self, condition, axis: Optional[int] = None, out=None) -> Any: + # ... + + def conj(self) -> Any: + return NamedArray(self.array.conj(), self.axes) + + def conjugate(self) -> Any: + return NamedArray(self.array.conjugate(), self.axes) + + def copy(self) -> Any: + return NamedArray(self.array.copy(), self.axes) + + def cumprod(self, axis: Optional[AxisSpec] = None, dtype=None, out=None) -> Any: + return haliax.cumprod(self, axis=axis, dtype=dtype, out=out) + + def cumsum(self, axis: Optional[AxisSpec] = None, dtype=None, out=None) -> Any: + return haliax.cumsum(self, axis=axis, dtype=dtype, out=out) + + # def diagonal(self, offset=0, axis1: int = 0, axis2: int = 1) -> Any: + # ... + + def dot(self, axis: AxisSpec, b, *, precision=None) -> Any: + return dot(axis, self, b, precision=precision) + + @property + def imag(self) -> Any: + return NamedArray(self.array.imag, self.axes) + + # TODO: + # def item(self, *args) -> Any: + # + + def max(self, axis: Optional[AxisSpec] = None, out=None, keepdims=None, initial=None, where=None) -> Any: + return haliax.max(self, axis=axis, out=out, keepdims=keepdims, initial=initial, where=where) + + def mean(self, axis: Optional[AxisSpec] = None, dtype=None, out=None, keepdims=False, *, where=None, ) -> Any: + return haliax.mean(self, axis=axis, dtype=dtype, out=out, keepdims=keepdims, where=where) + + def min(self, axis: Optional[AxisSpec] = None, out=None, keepdims=None, initial=None, where=None) -> Any: + return haliax.min(self, axis=axis, out=out, keepdims=keepdims, initial=initial, where=where) + + # TODO + # def nonzero(self, *, size=None, fill_value=None) -> Any: + # ... + + def prod(self, axis: Optional[AxisSpec] = None, dtype=None, out=None, keepdims=None, initial=None, where=None) -> Any: + return haliax.prod(self, axis=axis, dtype=dtype, out=out, keepdims=keepdims, initial=initial, where=where) + + # def ptp(self, axis: Optional[Union[int, Tuple[int, ...]]] = None, out=None, + # keepdims=False, ) -> Any: + # ... + + # def ravel(self, order='C') -> Any: + # ... + + @property + def real(self) -> Any: + return NamedArray(self.array.real, self.axes) + + # def repeat(self, repeats, axis: Optional[int] = None, *, + # total_repeat_length=None) -> Any: + # ... + + # def reshape(self, *args, order='C') -> Any: + # ... + + def round(self, decimals=0, out=None) -> Any: + return haliax.round(self, decimals=decimals, out=out) + + # def searchsorted(self, v, side='left', sorter=None) -> Any: + # ... + + # def sort(self, axis: Optional[int] = -1, kind='quicksort', order=None) -> Any: + # ... + + # def squeeze(self, axis: Optional[AxisSpec] = None) -> Any: + # return haliax.squeeze(self, axis=axis) + + def std(self, axis: Optional[AxisSpec] = None, dtype=None, out=None, ddof=0, keepdims=False, *, where=None) -> Any: + return haliax.std(self, axis=axis, dtype=dtype, out=out, ddof=ddof, keepdims=keepdims, where=where) + + def sum(self, axis: Optional[AxisSpec] = None, dtype=None, out=None, keepdims=None, + initial=None, where=None) -> Any: + return haliax.sum(self, axis=axis, ) + + # def take(self, indices, axis: Optional[int] = None, out=None, + # mode=None) -> Any: + # ... + + def tobytes(self, order='C') -> Any: + return self.array.tobytes(order=order) + + def tolist(self) -> Any: + return self.array.tolist() + + # def trace(self, offset=0, axis1: int = 0, axis2: int = 1, dtype=None, + # out=None) -> Any: + + def var(self, axis: Optional[AxisSpec] = None,dtype=None, out=None, ddof=0, keepdims=False, *, where=None) -> Any: + return haliax.var(self, axis=axis, dtype=dtype, out=out, ddof=ddof, keepdims=keepdims, where=where) + + + # operators + def __add__(self, other) -> Any: + # TODO: check shape and broadcast + raise NotImplementedError + + def __mul__(self, other): + if jnp.isscalar(other): + return NamedArray(self.array * other, self.axes) + + raise NotImplementedError + + def __rmul__(self, other): + return self.__mul__(other) + + def __truediv__(self, other): + if jnp.isscalar(other): + return NamedArray(self.array / other, self.axes) + + raise NotImplementedError + + def __rtruediv__(self, other): + if jnp.isscalar(other): + return NamedArray(other / self.array, self.axes) + + raise NotImplementedError + + +def dot(axis: AxisSpec, *arrays: NamedArray, precision=None) -> NamedArray: + """Returns the tensor product of two NamedArrays. The axes `axis` are contracted over, + and any other axes that are shared between the arrays are batched over. Non-contracted Axes in one + that are not in the other are preserved. + """ + if isinstance(axis, Axis): + axis = [axis] + + array_specs = [] + + next_index = 0 + axis_mappings: Dict[Axis, int] = {} + + for a in arrays: + spec = '' + for ax in a.axes: + if ax in axis_mappings: + spec += f'{axis_mappings[ax]} ' + else: + axis_mappings[ax] = next_index + spec += f'{next_index} ' + next_index += 1 + + array_specs.append(spec) + + # now compute the output axes: + output_axes = [ax for ax in axis_mappings.keys() if ax not in axis] + output_spec = ' '.join(str(axis_mappings[ax]) for ax in output_axes) + + output = jnp.einsum(', '.join(array_specs) + "-> " + output_spec, *[a.array for a in arrays], precision=precision) + + return NamedArray(output, output_axes) + + +T = TypeVar('T') + + +def _ensure_sequence(x: Union[T, Sequence[T]]) -> Sequence[T]: + if isinstance(x, Sequence): + return x + return (x,) + + +def named(a: jnp.ndarray, axis: AxisSpec) -> NamedArray: + """Creates a NamedArray from a numpy array and a list of axes""" + shape = _ensure_sequence(axis) + # verify the shape is correct + if jnp.shape(a) != tuple(x.size for x in shape): + raise ValueError(f"Shape of array {jnp.shape(a)} does not match shape of axes {axis}") + + return NamedArray(a, shape) + + diff --git a/src/haliax/nn.py b/src/haliax/nn.py new file mode 100644 index 0000000..0b8bb9f --- /dev/null +++ b/src/haliax/nn.py @@ -0,0 +1,28 @@ +import jax.nn as jnn +from .wrap import wrap_elemwise_unary, wrap_reduction_call, wrap_normalization_call + +relu = wrap_elemwise_unary(jnn.relu) +relu6 = wrap_elemwise_unary(jnn.relu6) +sigmoid = wrap_elemwise_unary(jnn.sigmoid) +softplus = wrap_elemwise_unary(jnn.softplus) +softsign = wrap_elemwise_unary(jnn.softsign) +silu = wrap_elemwise_unary(jnn.silu) +swish = wrap_elemwise_unary(jnn.swish) +log_sigmoid = wrap_elemwise_unary(jnn.log_sigmoid) +leaky_relu = wrap_elemwise_unary(jnn.leaky_relu) +hard_sigmoid = wrap_elemwise_unary(jnn.hard_sigmoid) +hard_silu = wrap_elemwise_unary(jnn.hard_silu) +hard_swish = wrap_elemwise_unary(jnn.hard_swish) +hard_tanh = wrap_elemwise_unary(jnn.hard_tanh) +elu = wrap_elemwise_unary(jnn.elu) +celu = wrap_elemwise_unary(jnn.celu) +selu = wrap_elemwise_unary(jnn.selu) +gelu = wrap_elemwise_unary(jnn.gelu) + +logsumexp = wrap_reduction_call(jnn.logsumexp) + +softmax = wrap_normalization_call(jnn.softmax) +log_softmax = wrap_normalization_call(jnn.log_softmax) + + +__all__ = ["relu", "relu6", "sigmoid", "softplus", "softsign", "silu", "swish", "log_sigmoid", "leaky_relu", "hard_sigmoid", "hard_silu", "hard_swish", "hard_tanh", "elu", "celu", "selu", "gelu", "logsumexp", "softmax", "log_softmax"] \ No newline at end of file diff --git a/src/haliax/random.py b/src/haliax/random.py new file mode 100644 index 0000000..2f0307c --- /dev/null +++ b/src/haliax/random.py @@ -0,0 +1,51 @@ +"""Wrappers around jax.random functions.""" + +import jax.random as jrandom + +import functools + +from haliax import _ensure_sequence +from haliax.core import * + + + +# TODO: handle broadcasting of array args to random functions (e.g. minval and maxval for uniform) +def _wrap_random_function(func): + """Wrap a jax random function to return a NamedArray and takes axes as inputs""" + @functools.wraps(func) + def wrapper(key: jrandom.KeyArray, shape: AxisSpec, *args, **kwargs): + shape = _ensure_sequence(shape) + lens = [ax.size for ax in shape] + + return NamedArray(func(key, lens, *args, **kwargs), shape) + return wrapper + + +uniform = _wrap_random_function(jrandom.uniform) +normal = _wrap_random_function(jrandom.normal) +randint = _wrap_random_function(jrandom.randint) +bernoulli = _wrap_random_function(jrandom.bernoulli) +poisson = _wrap_random_function(jrandom.poisson) +exponential = _wrap_random_function(jrandom.exponential) +gamma = _wrap_random_function(jrandom.gamma) +beta = _wrap_random_function(jrandom.beta) +laplace = _wrap_random_function(jrandom.laplace) +cauchy = _wrap_random_function(jrandom.cauchy) +logistic = _wrap_random_function(jrandom.logistic) +truncated_normal = _wrap_random_function(jrandom.truncated_normal) + + +__all__ = [ + 'uniform', + 'normal', + 'randint', + 'bernoulli', + 'poisson', + 'exponential', + 'gamma', + 'beta', + 'laplace', + 'cauchy', + 'logistic', + 'truncated_normal', +] \ No newline at end of file diff --git a/src/haliax/wrap.py b/src/haliax/wrap.py new file mode 100644 index 0000000..dac64c2 --- /dev/null +++ b/src/haliax/wrap.py @@ -0,0 +1,82 @@ +import functools +from typing import Optional + +import jax.numpy as jnp + +from haliax.core import NamedArray, _ensure_sequence, AxisSpec + + +def wrap_elemwise_unary(f): + """Wraps a unary elementwise function to take and return NamedArrays""" + + @functools.wraps(f) + def wrapper(a, *args, **kwargs): + if isinstance(a, NamedArray): + return NamedArray(f(a.array, *args, **kwargs), a.axes) + else: + return f(a, *args, **kwargs) + + return wrapper + + +def wrap_reduction_call(fn): + @functools.wraps(fn) + def wrapper(a, axis: Optional[AxisSpec] = None, keepdims=False, **kwargs): + if kwargs.get('where', None) is not None: + raise ValueError("where is not supported yet for NamedArray") + if kwargs.get('out', None) is not None: + raise ValueError("where is not supported yet for NamedArray") + + if isinstance(a, NamedArray): + if axis is None: + result = fn(a.array, axis=None, keepdims=keepdims, **kwargs) + if jnp.isscalar(result): + return result + else: + return NamedArray(result, ()) + else: + axis = _ensure_sequence(axis) + indices = a.lookup_indices(axis) + if indices is None or any(x is None for x in indices): + raise ValueError(f"axis {axis} is not in {a.axes}") + new_axes = a.axes if keepdims else [ax for ax in a.axes if ax not in axis] + result = fn(a.array, axis=indices, keepdims=keepdims, **kwargs) + if jnp.isscalar(result): + return result + return NamedArray(fn(a.array, axis=indices, keepdims=keepdims, **kwargs), new_axes) + else: + return fn(a, axis=axis, keepdims=keepdims, **kwargs) + + wrapper.__doc__ = """ + This function augments the behavior of `{fn}` to support NamedArrays, so that axis is a NamedArray. + At the moment, neither `where` nor `out` are supported. + ===== + + """ + fn.__doc__ + return wrapper + + +def wrap_normalization_call(fn): + @functools.wraps(fn) + def wrapper(a, axis: Optional[AxisSpec] = None, **kwargs): + if isinstance(a, NamedArray): + if axis is None: + return NamedArray(fn(a.array, axis=None, **kwargs), ()) + else: + indices = _ensure_sequence(a.lookup_indices(axis)) + if any(x is None for x in indices): + raise ValueError(f"axis {axis} is not in {a.axes}") + return NamedArray(fn(a.array, axis=indices, **kwargs), a.axes) + else: + return fn(a, axis=axis, **kwargs) + + wrapper.__doc__ = """ + This function augments the behavior of `{fn}` to support NamedArrays, so that axis is a NamedArray. + At the moment, neither `where` nor `out` are supported. + ===== + + """ + fn.__doc__ + return wrapper + + +__all__ = ["wrap_elemwise_unary", "wrap_reduction_call", "wrap_normalization_call"] \ No newline at end of file commit e940244064dbd05b583f53d7b50ce810bf97ee2c Date: 2022-08-02T15:48:36-07:00 add split diff --git a/src/haliax/__init__.py b/src/haliax/__init__.py index 476b6f3..250d136 100644 --- a/src/haliax/__init__.py +++ b/src/haliax/__init__.py @@ -1,12 +1,13 @@ from .core import * -# creation routines -# we could codegen these or do it dynamically, but Codex will do it for us and it's a bit less weird this way -from .core import _ensure_sequence +from .core import _ensure_tuple import haliax.random as random -from .wrap import wrap_elemwise_unary, wrap_reduction_call +from .wrap import wrap_elemwise_unary, wrap_reduction_call, wrap_normalization_call +import numpy as np +_sum = sum +# creation routines def zeros(shape: AxisSpec, dtype=None) -> NamedArray: """Creates a NamedArray with all elements set to 0""" return full(shape, 0, dtype) @@ -39,6 +40,27 @@ def full_like(a: NamedArray, fill_value, dtype=None) -> NamedArray: return NamedArray(jnp.full_like(a.array, fill_value, dtype=dtype), a.axes) +# splitting and stacking etc +def split(a: NamedArray, axis: Axis, new_axes: Sequence[Axis])-> Sequence[NamedArray]: + # check the lengths of the new axes + if axis not in a.axes: + raise ValueError(f"Axis {axis} not found in {a.axes}") + + total_len = _sum(x.size for x in new_axes) + if total_len != axis.size: + raise ValueError(f"The total length of the new axes {total_len} does not match the length of the axis {axis}") + + index = a.lookup_indices(axis) + + # now we can split the array + offsets = np.cumsum([0] + [x.size for x in new_axes])[1:-1] + + new_arrays = np.split(a.array, indices_or_sections=offsets, axis=index) + new_axes = [[ax2 if ax2 is not axis else new_axis for ax2 in a.axes] for new_axis in new_axes] + + return [NamedArray(x, ax) for x, ax in zip(new_arrays, new_axes)] + + # elementwise unary operations abs = wrap_elemwise_unary(jnp.abs) absolute = wrap_elemwise_unary(jnp.absolute) @@ -103,7 +125,6 @@ trunc = wrap_elemwise_unary(jnp.trunc) # Reduction functions - all = wrap_reduction_call(jnp.all) amax = wrap_reduction_call(jnp.amax) any = wrap_reduction_call(jnp.any) @@ -121,16 +142,27 @@ var = wrap_reduction_call(jnp.var) # "Normalization" functions that use an axis but don't change the shape -cumsum = wrap_reduction_call(jnp.cumsum) -cumprod = wrap_reduction_call(jnp.cumprod) -cumproduct = wrap_reduction_call(jnp.cumproduct) +cumsum = wrap_normalization_call(jnp.cumsum) +cumprod = wrap_normalization_call(jnp.cumprod) +cumproduct = wrap_normalization_call(jnp.cumproduct) __all__ = ["Axis", "NamedArray", "AxisSpec", "named", "dot", "zeros", "ones", "full", "zeros_like", "ones_like", "full_like", - "random" - ] + "random", + "abs", "absolute", "angle", "arccos", "arccosh", "arcsin", "arcsinh", + "arctan", "arctanh", "around", "bitwise_not", "cbrt", "ceil", "conj", + "conjugate", "copy", "cos", "cosh", "deg2rad", "degrees", "exp", + "exp2", "expm1", "fabs", "fix", "floor", "frexp", "i0", "imag", + "iscomplex", "isfinite", "isinf", "isnan", "isneginf", "isposinf", + "isreal", "log", "log10", "log1p", "log2", "logical_not", "ndim", + "negative", "positive", "rad2deg", "radians", "real", "reciprocal", + "rint", "round", "sign", "signbit", "sin", "sinc", "sinh", "square", + "sqrt", "tan", "tanh", "trunc", "all", "amax", "any", "max", "mean", + "min", "prod", "product", "sometrue", "std", "sum", "var", "cumsum", + "cumprod", "cumproduct"] + diff --git a/src/haliax/core.py b/src/haliax/core.py index 6df7d91..486bfa7 100644 --- a/src/haliax/core.py +++ b/src/haliax/core.py @@ -22,9 +22,11 @@ AxisSpec = Union[Axis, Sequence[Axis]] @dataclass(frozen=True) class NamedArray: array: jnp.ndarray - axes: Sequence[Axis] + axes: Tuple[Axis, ...] def __post_init__(self): + if not isinstance(self.axes, tuple): + object.__setattr__(self, 'axes', tuple(self.axes)) # ensure unique axes for now if len(set(a.name for a in self.axes)) != len(self.axes): raise ValueError(f"Axes must be unique, but {self.axes} are not") @@ -171,6 +173,9 @@ class NamedArray: # def sort(self, axis: Optional[int] = -1, kind='quicksort', order=None) -> Any: # ... + def split(self, axis: Axis, new_axes: Sequence[Axis]) -> Sequence['NamedArray']: + return hapax.split(self, axis=axis, new_axes=new_axes) + # def squeeze(self, axis: Optional[AxisSpec] = None) -> Any: # return haliax.squeeze(self, axis=axis) @@ -262,9 +267,9 @@ def dot(axis: AxisSpec, *arrays: NamedArray, precision=None) -> NamedArray: T = TypeVar('T') -def _ensure_sequence(x: Union[T, Sequence[T]]) -> Sequence[T]: +def _ensure_tuple(x: Union[T, Tuple[T, ...]]) -> Tuple[T, ...]: if isinstance(x, Sequence): - return x + return tuple(x) return (x,) diff --git a/src/haliax/random.py b/src/haliax/random.py index 2f0307c..ed4057b 100644 --- a/src/haliax/random.py +++ b/src/haliax/random.py @@ -4,7 +4,7 @@ import jax.random as jrandom import functools -from haliax import _ensure_sequence +from haliax import _ensure_tuple from haliax.core import * @@ -14,10 +14,13 @@ def _wrap_random_function(func): """Wrap a jax random function to return a NamedArray and takes axes as inputs""" @functools.wraps(func) def wrapper(key: jrandom.KeyArray, shape: AxisSpec, *args, **kwargs): - shape = _ensure_sequence(shape) - lens = [ax.size for ax in shape] + if isinstance(shape, Axis): + return NamedArray(func(key, shape.size, *args, **kwargs), (shape, )) + else: + shape = _ensure_tuple(shape) + lens = [ax.size for ax in shape] - return NamedArray(func(key, lens, *args, **kwargs), shape) + return NamedArray(func(key, lens, *args, **kwargs), shape) return wrapper diff --git a/src/haliax/wrap.py b/src/haliax/wrap.py index dac64c2..e695235 100644 --- a/src/haliax/wrap.py +++ b/src/haliax/wrap.py @@ -3,7 +3,7 @@ from typing import Optional import jax.numpy as jnp -from haliax.core import NamedArray, _ensure_sequence, AxisSpec +from haliax.core import NamedArray, _ensure_tuple, AxisSpec def wrap_elemwise_unary(f): @@ -35,7 +35,7 @@ def wrap_reduction_call(fn): else: return NamedArray(result, ()) else: - axis = _ensure_sequence(axis) + axis = _ensure_tuple(axis) indices = a.lookup_indices(axis) if indices is None or any(x is None for x in indices): raise ValueError(f"axis {axis} is not in {a.axes}") commit 1163d5f05f562965352e80f1b8f83dc19d19aa6d Date: 2022-08-02T22:00:26-07:00 add 'take' diff --git a/src/haliax/core.py b/src/haliax/core.py index 486bfa7..5ca5cb3 100644 --- a/src/haliax/core.py +++ b/src/haliax/core.py @@ -186,9 +186,8 @@ class NamedArray: initial=None, where=None) -> Any: return haliax.sum(self, axis=axis, ) - # def take(self, indices, axis: Optional[int] = None, out=None, - # mode=None) -> Any: - # ... + def take(self, axis: Axis, index: Union[int, 'NamedArray']) -> Any: + return hapax.take(self, axis=axis, index=index) def tobytes(self, order='C') -> Any: return self.array.tobytes(order=order) @@ -230,6 +229,24 @@ class NamedArray: raise NotImplementedError +def take(array: NamedArray, axis: Axis, index: Union[int, NamedArray]) -> NamedArray: + """ + Selects elements from an array along an axis, by an index or by another named array + """ + axis_index = array.lookup_indices(axis) + if axis_index is None: + raise ValueError(f"axis {axis} not found in {array}") + if isinstance(index, int): + # just drop the axis + new_array = jnp.take(array.array, index, axis=axis_index) + new_axes = array.axes[:axis_index] + array.axes[axis_index+1:] + else: + new_array = jnp.take(array.array, index.array, axis=axis_index) + new_axes = array.axes[:axis_index] + index.axes + array.axes[axis_index+1:] + # new axes come from splicing the old axis with + return NamedArray(new_array, new_axes) + + def dot(axis: AxisSpec, *arrays: NamedArray, precision=None) -> NamedArray: """Returns the tensor product of two NamedArrays. The axes `axis` are contracted over, and any other axes that are shared between the arrays are batched over. Non-contracted Axes in one @@ -256,7 +273,7 @@ def dot(axis: AxisSpec, *arrays: NamedArray, precision=None) -> NamedArray: array_specs.append(spec) # now compute the output axes: - output_axes = [ax for ax in axis_mappings.keys() if ax not in axis] + output_axes = tuple(ax for ax in axis_mappings.keys() if ax not in axis) output_spec = ' '.join(str(axis_mappings[ax]) for ax in output_axes) output = jnp.einsum(', '.join(array_specs) + "-> " + output_spec, *[a.array for a in arrays], precision=precision) @@ -275,11 +292,15 @@ def _ensure_tuple(x: Union[T, Tuple[T, ...]]) -> Tuple[T, ...]: def named(a: jnp.ndarray, axis: AxisSpec) -> NamedArray: """Creates a NamedArray from a numpy array and a list of axes""" - shape = _ensure_sequence(axis) - # verify the shape is correct - if jnp.shape(a) != tuple(x.size for x in shape): - raise ValueError(f"Shape of array {jnp.shape(a)} does not match shape of axes {axis}") - - return NamedArray(a, shape) - + if isinstance(axis, Axis): + if jnp.shape(a) != axis.size: + raise ValueError(f'Shape of array {jnp.shape(a)} does not match size of axis {axis.size}') + return NamedArray(a, (axis, )) + else: + shape = _ensure_tuple(axis) + # verify the shape is correct + if jnp.shape(a) != tuple(x.size for x in shape): + raise ValueError(f"Shape of array {jnp.shape(a)} does not match shape of axes {axis}") + + return NamedArray(a, shape) commit 50fd35e9d2213909fcc72a19d1c8f9a28f6bd6fd Date: 2022-08-02T22:04:33-07:00 missed some args diff --git a/src/haliax/core.py b/src/haliax/core.py index 5ca5cb3..2493d4b 100644 --- a/src/haliax/core.py +++ b/src/haliax/core.py @@ -184,7 +184,7 @@ class NamedArray: def sum(self, axis: Optional[AxisSpec] = None, dtype=None, out=None, keepdims=None, initial=None, where=None) -> Any: - return haliax.sum(self, axis=axis, ) + return haliax.sum(self, axis=axis, dtype=dtype, out=out, keepdims=keepdims, initial=initial, where=where) def take(self, axis: Axis, index: Union[int, 'NamedArray']) -> Any: return hapax.take(self, axis=axis, index=index) commit da012d8929941eb098b7e9c71d87e2d17a331ca2 Date: 2022-08-02T22:07:06-07:00 cleanup diff --git a/src/haliax/core.py b/src/haliax/core.py index 2493d4b..6849c4c 100644 --- a/src/haliax/core.py +++ b/src/haliax/core.py @@ -3,7 +3,6 @@ from typing import Sequence, Union, Any, Dict, TypeVar, Optional, Tuple import jax import jax.numpy as jnp -from jax.interpreters.partial_eval import DynamicJaxprTracer from jaxlib.xla_extension import DeviceArray import haliax @@ -143,7 +142,7 @@ class NamedArray: # def nonzero(self, *, size=None, fill_value=None) -> Any: # ... - def prod(self, axis: Optional[AxisSpec] = None, dtype=None, out=None, keepdims=None, initial=None, where=None) -> Any: + def prod(self, axis: Optional[AxisSpec] = None, dtype=None, out=None, keepdims=None, initial=None, where=None): return haliax.prod(self, axis=axis, dtype=dtype, out=out, keepdims=keepdims, initial=initial, where=where) # def ptp(self, axis: Optional[Union[int, Tuple[int, ...]]] = None, out=None, @@ -198,10 +197,9 @@ class NamedArray: # def trace(self, offset=0, axis1: int = 0, axis2: int = 1, dtype=None, # out=None) -> Any: - def var(self, axis: Optional[AxisSpec] = None,dtype=None, out=None, ddof=0, keepdims=False, *, where=None) -> Any: + def var(self, axis: Optional[AxisSpec] = None, dtype=None, out=None, ddof=0, keepdims=False, *, where=None) -> Any: return haliax.var(self, axis=axis, dtype=dtype, out=out, ddof=ddof, keepdims=keepdims, where=where) - # operators def __add__(self, other) -> Any: # TODO: check shape and broadcast @@ -284,7 +282,7 @@ def dot(axis: AxisSpec, *arrays: NamedArray, precision=None) -> NamedArray: T = TypeVar('T') -def _ensure_tuple(x: Union[T, Tuple[T, ...]]) -> Tuple[T, ...]: +def _ensure_tuple(x: Union[Sequence[T, ...], T]) -> Tuple[T, ...]: if isinstance(x, Sequence): return tuple(x) return (x,) @@ -297,7 +295,7 @@ def named(a: jnp.ndarray, axis: AxisSpec) -> NamedArray: raise ValueError(f'Shape of array {jnp.shape(a)} does not match size of axis {axis.size}') return NamedArray(a, (axis, )) else: - shape = _ensure_tuple(axis) + shape: Tuple[Axis, ...] = _ensure_tuple(axis) # verify the shape is correct if jnp.shape(a) != tuple(x.size for x in shape): raise ValueError(f"Shape of array {jnp.shape(a)} does not match shape of axes {axis}") diff --git a/src/haliax/wrap.py b/src/haliax/wrap.py index e695235..ac880ad 100644 --- a/src/haliax/wrap.py +++ b/src/haliax/wrap.py @@ -79,4 +79,4 @@ def wrap_normalization_call(fn): return wrapper -__all__ = ["wrap_elemwise_unary", "wrap_reduction_call", "wrap_normalization_call"] \ No newline at end of file +__all__ = ["wrap_elemwise_unary", "wrap_reduction_call", "wrap_normalization_call"] commit 1aae8e75b3ef61a23ef1217ead88c56138f95fcd Date: 2022-08-05T15:05:42-07:00 ok add support cumsum etc diff --git a/src/haliax/__init__.py b/src/haliax/__init__.py index 250d136..2bb3e10 100644 --- a/src/haliax/__init__.py +++ b/src/haliax/__init__.py @@ -142,9 +142,9 @@ var = wrap_reduction_call(jnp.var) # "Normalization" functions that use an axis but don't change the shape -cumsum = wrap_normalization_call(jnp.cumsum) -cumprod = wrap_normalization_call(jnp.cumprod) -cumproduct = wrap_normalization_call(jnp.cumproduct) +cumsum = wrap_normalization_call(jnp.cumsum, True) +cumprod = wrap_normalization_call(jnp.cumprod, True) +cumproduct = wrap_normalization_call(jnp.cumproduct, True) __all__ = ["Axis", "NamedArray", "AxisSpec", diff --git a/src/haliax/core.py b/src/haliax/core.py index 6849c4c..87ba21f 100644 --- a/src/haliax/core.py +++ b/src/haliax/core.py @@ -282,7 +282,7 @@ def dot(axis: AxisSpec, *arrays: NamedArray, precision=None) -> NamedArray: T = TypeVar('T') -def _ensure_tuple(x: Union[Sequence[T, ...], T]) -> Tuple[T, ...]: +def _ensure_tuple(x: Union[Sequence[T], T]) -> Tuple[T, ...]: if isinstance(x, Sequence): return tuple(x) return (x,) diff --git a/src/haliax/nn.py b/src/haliax/nn.py index 0b8bb9f..4bbf86b 100644 --- a/src/haliax/nn.py +++ b/src/haliax/nn.py @@ -21,8 +21,8 @@ gelu = wrap_elemwise_unary(jnn.gelu) logsumexp = wrap_reduction_call(jnn.logsumexp) -softmax = wrap_normalization_call(jnn.softmax) -log_softmax = wrap_normalization_call(jnn.log_softmax) +softmax = wrap_normalization_call(jnn.softmax, False) +log_softmax = wrap_normalization_call(jnn.log_softmax, False) __all__ = ["relu", "relu6", "sigmoid", "softplus", "softsign", "silu", "swish", "log_sigmoid", "leaky_relu", "hard_sigmoid", "hard_silu", "hard_swish", "hard_tanh", "elu", "celu", "selu", "gelu", "logsumexp", "softmax", "log_softmax"] \ No newline at end of file diff --git a/src/haliax/wrap.py b/src/haliax/wrap.py index ac880ad..9a8f37d 100644 --- a/src/haliax/wrap.py +++ b/src/haliax/wrap.py @@ -56,17 +56,23 @@ def wrap_reduction_call(fn): return wrapper -def wrap_normalization_call(fn): +def wrap_normalization_call(fn, single_axis_only: bool): @functools.wraps(fn) def wrapper(a, axis: Optional[AxisSpec] = None, **kwargs): if isinstance(a, NamedArray): if axis is None: return NamedArray(fn(a.array, axis=None, **kwargs), ()) else: - indices = _ensure_sequence(a.lookup_indices(axis)) + indices = _ensure_tuple(a.lookup_indices(axis)) if any(x is None for x in indices): raise ValueError(f"axis {axis} is not in {a.axes}") - return NamedArray(fn(a.array, axis=indices, **kwargs), a.axes) + if len(indices) == 1: + return NamedArray(fn(a.array, axis=indices[0], **kwargs), a.axes) + elif single_axis_only: + raise ValueError(f"{fn.__name__} only supports a single axis") + else: + return NamedArray(fn(a.array, axis=indices, **kwargs), a.axes) + else: return fn(a, axis=axis, **kwargs) commit cbcecd4ca24546acb3c77921558a3a263d0a765c Date: 2022-08-05T16:45:19-07:00 make flake happy diff --git a/src/haliax/__init__.py b/src/haliax/__init__.py index 2bb3e10..4e1f310 100644 --- a/src/haliax/__init__.py +++ b/src/haliax/__init__.py @@ -1,8 +1,10 @@ -from .core import * -from .core import _ensure_tuple +from typing import Sequence + +from .core import AxisSpec, NamedArray, Axis, named, dot, take import haliax.random as random from .wrap import wrap_elemwise_unary, wrap_reduction_call, wrap_normalization_call import numpy as np +import jax.numpy as jnp _sum = sum @@ -12,14 +14,16 @@ def zeros(shape: AxisSpec, dtype=None) -> NamedArray: """Creates a NamedArray with all elements set to 0""" return full(shape, 0, dtype) + def ones(shape: AxisSpec, dtype=None) -> NamedArray: """Creates a NamedArray with all elements set to 1""" return full(shape, 1, dtype) + def full(shape: AxisSpec, fill_value, dtype=None) -> NamedArray: """Creates a NamedArray with all elements set to `fill_value`""" if isinstance(shape, Axis): - return NamedArray(jnp.full(shape=shape.size, fill_value=fill_value, dtype=dtype), (shape, )) + return NamedArray(jnp.full(shape=shape.size, fill_value=fill_value, dtype=dtype), (shape,)) else: x_shape = tuple(x.size for x in shape) return NamedArray(jnp.full(shape=x_shape, fill_value=fill_value, dtype=dtype), shape) @@ -41,7 +45,7 @@ def full_like(a: NamedArray, fill_value, dtype=None) -> NamedArray: # splitting and stacking etc -def split(a: NamedArray, axis: Axis, new_axes: Sequence[Axis])-> Sequence[NamedArray]: +def split(a: NamedArray, axis: Axis, new_axes: Sequence[Axis]) -> Sequence[NamedArray]: # check the lengths of the new axes if axis not in a.axes: raise ValueError(f"Axis {axis} not found in {a.axes}") @@ -123,7 +127,6 @@ tan = wrap_elemwise_unary(jnp.tan) tanh = wrap_elemwise_unary(jnp.tanh) trunc = wrap_elemwise_unary(jnp.trunc) - # Reduction functions all = wrap_reduction_call(jnp.all) amax = wrap_reduction_call(jnp.amax) @@ -140,15 +143,13 @@ std = wrap_reduction_call(jnp.std) sum = wrap_reduction_call(jnp.sum) var = wrap_reduction_call(jnp.var) - # "Normalization" functions that use an axis but don't change the shape cumsum = wrap_normalization_call(jnp.cumsum, True) cumprod = wrap_normalization_call(jnp.cumprod, True) cumproduct = wrap_normalization_call(jnp.cumproduct, True) - __all__ = ["Axis", "NamedArray", "AxisSpec", - "named", "dot", + "named", "dot", "take", "zeros", "ones", "full", "zeros_like", "ones_like", "full_like", "random", "abs", "absolute", "angle", "arccos", "arccosh", "arcsin", "arcsinh", @@ -162,8 +163,3 @@ __all__ = ["Axis", "NamedArray", "AxisSpec", "sqrt", "tan", "tanh", "trunc", "all", "amax", "any", "max", "mean", "min", "prod", "product", "sometrue", "std", "sum", "var", "cumsum", "cumprod", "cumproduct"] - - - - - diff --git a/src/haliax/core.py b/src/haliax/core.py index 87ba21f..61467d6 100644 --- a/src/haliax/core.py +++ b/src/haliax/core.py @@ -173,7 +173,7 @@ class NamedArray: # ... def split(self, axis: Axis, new_axes: Sequence[Axis]) -> Sequence['NamedArray']: - return hapax.split(self, axis=axis, new_axes=new_axes) + return haliax.split(self, axis=axis, new_axes=new_axes) # def squeeze(self, axis: Optional[AxisSpec] = None) -> Any: # return haliax.squeeze(self, axis=axis) @@ -186,7 +186,7 @@ class NamedArray: return haliax.sum(self, axis=axis, dtype=dtype, out=out, keepdims=keepdims, initial=initial, where=where) def take(self, axis: Axis, index: Union[int, 'NamedArray']) -> Any: - return hapax.take(self, axis=axis, index=index) + return haliax.take(self, axis=axis, index=index) def tobytes(self, order='C') -> Any: return self.array.tobytes(order=order) @@ -301,4 +301,3 @@ def named(a: jnp.ndarray, axis: AxisSpec) -> NamedArray: raise ValueError(f"Shape of array {jnp.shape(a)} does not match shape of axes {axis}") return NamedArray(a, shape) - diff --git a/src/haliax/nn.py b/src/haliax/nn.py index 4bbf86b..7ceec15 100644 --- a/src/haliax/nn.py +++ b/src/haliax/nn.py @@ -5,7 +5,7 @@ relu = wrap_elemwise_unary(jnn.relu) relu6 = wrap_elemwise_unary(jnn.relu6) sigmoid = wrap_elemwise_unary(jnn.sigmoid) softplus = wrap_elemwise_unary(jnn.softplus) -softsign = wrap_elemwise_unary(jnn.softsign) +soft_sign = wrap_elemwise_unary(jnn.soft_sign) silu = wrap_elemwise_unary(jnn.silu) swish = wrap_elemwise_unary(jnn.swish) log_sigmoid = wrap_elemwise_unary(jnn.log_sigmoid) @@ -25,4 +25,6 @@ softmax = wrap_normalization_call(jnn.softmax, False) log_softmax = wrap_normalization_call(jnn.log_softmax, False) -__all__ = ["relu", "relu6", "sigmoid", "softplus", "softsign", "silu", "swish", "log_sigmoid", "leaky_relu", "hard_sigmoid", "hard_silu", "hard_swish", "hard_tanh", "elu", "celu", "selu", "gelu", "logsumexp", "softmax", "log_softmax"] \ No newline at end of file +__all__ = ["relu", "relu6", "sigmoid", "softplus", "soft_sign", "silu", "swish", "log_sigmoid", "leaky_relu", + "hard_sigmoid", "hard_silu", "hard_swish", "hard_tanh", "elu", "celu", "selu", "gelu", "logsumexp", + "softmax", "log_softmax"] diff --git a/src/haliax/random.py b/src/haliax/random.py index ed4057b..1d113bb 100644 --- a/src/haliax/random.py +++ b/src/haliax/random.py @@ -4,23 +4,25 @@ import jax.random as jrandom import functools -from haliax import _ensure_tuple -from haliax.core import * +from haliax.core import Axis, AxisSpec, NamedArray +# TODO: handle broadcasting of array args to random functions (e.g. minval and maxval for uniform) +from haliax.core import _ensure_tuple -# TODO: handle broadcasting of array args to random functions (e.g. minval and maxval for uniform) def _wrap_random_function(func): """Wrap a jax random function to return a NamedArray and takes axes as inputs""" + @functools.wraps(func) def wrapper(key: jrandom.KeyArray, shape: AxisSpec, *args, **kwargs): if isinstance(shape, Axis): - return NamedArray(func(key, shape.size, *args, **kwargs), (shape, )) + return NamedArray(func(key, shape.size, *args, **kwargs), (shape,)) else: shape = _ensure_tuple(shape) lens = [ax.size for ax in shape] return NamedArray(func(key, lens, *args, **kwargs), shape) + return wrapper @@ -37,7 +39,6 @@ cauchy = _wrap_random_function(jrandom.cauchy) logistic = _wrap_random_function(jrandom.logistic) truncated_normal = _wrap_random_function(jrandom.truncated_normal) - __all__ = [ 'uniform', 'normal', @@ -51,4 +52,4 @@ __all__ = [ 'cauchy', 'logistic', 'truncated_normal', -] \ No newline at end of file +] commit cacf7ba5259c51581683d3d8c7a6c8f99346b5f1 Date: 2022-08-11T10:22:33-07:00 please precommit gods diff --git a/README.md b/README.md index 3344b1c..c58291e 100644 --- a/README.md +++ b/README.md @@ -1,10 +1,10 @@ # Levanter > You could not prevent a thunderstorm, but you could use the electricity; you could not direct the wind, but you could trim your sail so as to propel your vessel as you pleased, no matter which way the wind blew. <br/> -> — Cora L. V. Hatch +> — Cora L. V. Hatch -Levanter is a library based on [Jax](https:://github.com/google/jax) and [Equinox](https://github.com/patrick-kidger/equinox) +Levanter is a library based on [Jax](https:://github.com/google/jax) and [Equinox](https://github.com/patrick-kidger/equinox) for training [foundation models](https://en.wikipedia.org/wiki/Foundation_models) created by [Stanford's Center for Research on Foundation Models (CRFM)](https://crfm.stanford.edu/). @@ -14,4 +14,4 @@ on Foundation Models (CRFM)](https://crfm.stanford.edu/). > — Patrick Rothfuss, *The Name of the Wind* Haliax is a module (currently) inside Levanter for named tensors, modeled on Alexander Rush's [Tensor Considered Harmful](https://arxiv.org/abs/1803.09868). -It's designed to work with Equinox to make constructing distributed models easier. \ No newline at end of file +It's designed to work with Equinox to make constructing distributed models easier. diff --git a/pyproject.toml b/pyproject.toml new file mode 100644 index 0000000..6fbaff1 --- /dev/null +++ b/pyproject.toml @@ -0,0 +1,14 @@ +[tool.black] +line-length = 119 +target-version = ["py36", "py37", "py38"] +experimental_string_processing = true + +[tool.isort] +profile = "black" +multi_line_output = 3 +lines_after_imports = 2 +include_trailing_comma = true +force_grid_wrap = 0 +use_parentheses = true +ensure_newline_before_comments = true +line_length = 119 diff --git a/requirements.txt b/requirements.txt index b788062..081e6d5 100644 --- a/requirements.txt +++ b/requirements.txt @@ -9,4 +9,4 @@ zstandard datasets fsspec gcsfs -braceexpand \ No newline at end of file +braceexpand diff --git a/src/haliax/__init__.py b/src/haliax/__init__.py index 4e1f310..ece8b23 100644 --- a/src/haliax/__init__.py +++ b/src/haliax/__init__.py @@ -1,10 +1,13 @@ from typing import Sequence -from .core import AxisSpec, NamedArray, Axis, named, dot, take -import haliax.random as random -from .wrap import wrap_elemwise_unary, wrap_reduction_call, wrap_normalization_call -import numpy as np import jax.numpy as jnp +import numpy as np + +import haliax.random as random + +from .core import Axis, AxisSpec, NamedArray, dot, named, take +from .wrap import wrap_elemwise_unary, wrap_normalization_call, wrap_reduction_call + _sum = sum @@ -26,7 +29,7 @@ def full(shape: AxisSpec, fill_value, dtype=None) -> NamedArray: return NamedArray(jnp.full(shape=shape.size, fill_value=fill_value, dtype=dtype), (shape,)) else: x_shape = tuple(x.size for x in shape) - return NamedArray(jnp.full(shape=x_shape, fill_value=fill_value, dtype=dtype), shape) + return NamedArray(jnp.full(shape=x_shape, fill_value=fill_value, dtype=dtype), tuple(shape)) def zeros_like(a: NamedArray, dtype=None) -> NamedArray: @@ -60,9 +63,9 @@ def split(a: NamedArray, axis: Axis, new_axes: Sequence[Axis]) -> Sequence[Named offsets = np.cumsum([0] + [x.size for x in new_axes])[1:-1] new_arrays = np.split(a.array, indices_or_sections=offsets, axis=index) - new_axes = [[ax2 if ax2 is not axis else new_axis for ax2 in a.axes] for new_axis in new_axes] + ret_axes = [tuple(ax2 if ax2 is not axis else new_axis for ax2 in a.axes) for new_axis in new_axes] - return [NamedArray(x, ax) for x, ax in zip(new_arrays, new_axes)] + return [NamedArray(x, ax) for x, ax in zip(new_arrays, ret_axes)] # elementwise unary operations @@ -148,18 +151,93 @@ cumsum = wrap_normalization_call(jnp.cumsum, True) cumprod = wrap_normalization_call(jnp.cumprod, True) cumproduct = wrap_normalization_call(jnp.cumproduct, True) -__all__ = ["Axis", "NamedArray", "AxisSpec", - "named", "dot", "take", - "zeros", "ones", "full", "zeros_like", "ones_like", "full_like", - "random", - "abs", "absolute", "angle", "arccos", "arccosh", "arcsin", "arcsinh", - "arctan", "arctanh", "around", "bitwise_not", "cbrt", "ceil", "conj", - "conjugate", "copy", "cos", "cosh", "deg2rad", "degrees", "exp", - "exp2", "expm1", "fabs", "fix", "floor", "frexp", "i0", "imag", - "iscomplex", "isfinite", "isinf", "isnan", "isneginf", "isposinf", - "isreal", "log", "log10", "log1p", "log2", "logical_not", "ndim", - "negative", "positive", "rad2deg", "radians", "real", "reciprocal", - "rint", "round", "sign", "signbit", "sin", "sinc", "sinh", "square", - "sqrt", "tan", "tanh", "trunc", "all", "amax", "any", "max", "mean", - "min", "prod", "product", "sometrue", "std", "sum", "var", "cumsum", - "cumprod", "cumproduct"] +__all__ = [ + "Axis", + "NamedArray", + "AxisSpec", + "named", + "dot", + "take", + "zeros", + "ones", + "full", + "zeros_like", + "ones_like", + "full_like", + "random", + "abs", + "absolute", + "angle", + "arccos", + "arccosh", + "arcsin", + "arcsinh", + "arctan", + "arctanh", + "around", + "bitwise_not", + "cbrt", + "ceil", + "conj", + "conjugate", + "copy", + "cos", + "cosh", + "deg2rad", + "degrees", + "exp", + "exp2", + "expm1", + "fabs", + "fix", + "floor", + "frexp", + "i0", + "imag", + "iscomplex", + "isfinite", + "isinf", + "isnan", + "isneginf", + "isposinf", + "isreal", + "log", + "log10", + "log1p", + "log2", + "logical_not", + "ndim", + "negative", + "positive", + "rad2deg", + "radians", + "real", + "reciprocal", + "rint", + "round", + "sign", + "signbit", + "sin", + "sinc", + "sinh", + "square", + "sqrt", + "tan", + "tanh", + "trunc", + "all", + "amax", + "any", + "max", + "mean", + "min", + "prod", + "product", + "sometrue", + "std", + "sum", + "var", + "cumsum", + "cumprod", + "cumproduct", +] diff --git a/src/haliax/core.py b/src/haliax/core.py index 61467d6..1025ff5 100644 --- a/src/haliax/core.py +++ b/src/haliax/core.py @@ -1,5 +1,5 @@ from dataclasses import dataclass -from typing import Sequence, Union, Any, Dict, TypeVar, Optional, Tuple +from typing import Any, Dict, Optional, Sequence, Tuple, TypeVar, Union import jax import jax.numpy as jnp @@ -25,7 +25,7 @@ class NamedArray: def __post_init__(self): if not isinstance(self.axes, tuple): - object.__setattr__(self, 'axes', tuple(self.axes)) + object.__setattr__(self, "axes", tuple(self.axes)) # ensure unique axes for now if len(set(a.name for a in self.axes)) != len(self.axes): raise ValueError(f"Axes must be unique, but {self.axes} are not") @@ -49,7 +49,8 @@ class NamedArray: @classmethod def tree_unflatten(cls, aux, tree: Any) -> Any: - return cls(*tree, axes=aux) + assert len(tree) == 1 + return cls(tree[0], axes=aux) def lookup_indices(self, axis: AxisSpec): """ @@ -129,21 +130,59 @@ class NamedArray: # def item(self, *args) -> Any: # - def max(self, axis: Optional[AxisSpec] = None, out=None, keepdims=None, initial=None, where=None) -> Any: + def max( + self, + axis: Optional[AxisSpec] = None, + out=None, + keepdims=None, + initial=None, + where=None, + ) -> Any: return haliax.max(self, axis=axis, out=out, keepdims=keepdims, initial=initial, where=where) - def mean(self, axis: Optional[AxisSpec] = None, dtype=None, out=None, keepdims=False, *, where=None, ) -> Any: + def mean( + self, + axis: Optional[AxisSpec] = None, + dtype=None, + out=None, + keepdims=False, + *, + where=None, + ) -> Any: return haliax.mean(self, axis=axis, dtype=dtype, out=out, keepdims=keepdims, where=where) - def min(self, axis: Optional[AxisSpec] = None, out=None, keepdims=None, initial=None, where=None) -> Any: + def min( + self, + axis: Optional[AxisSpec] = None, + out=None, + keepdims=None, + initial=None, + where=None, + ) -> Any: return haliax.min(self, axis=axis, out=out, keepdims=keepdims, initial=initial, where=where) # TODO # def nonzero(self, *, size=None, fill_value=None) -> Any: # ... - def prod(self, axis: Optional[AxisSpec] = None, dtype=None, out=None, keepdims=None, initial=None, where=None): - return haliax.prod(self, axis=axis, dtype=dtype, out=out, keepdims=keepdims, initial=initial, where=where) + def prod( + self, + axis: Optional[AxisSpec] = None, + dtype=None, + out=None, + keepdims=None, + initial=None, + where=None, + ): + return haliax.prod( + self, + axis=axis, + dtype=dtype, + out=out, + keepdims=keepdims, + initial=initial, + where=where, + ) # def ptp(self, axis: Optional[Union[int, Tuple[int, ...]]] = None, out=None, # keepdims=False, ) -> Any: @@ -172,23 +211,55 @@ class NamedArray: # def sort(self, axis: Optional[int] = -1, kind='quicksort', order=None) -> Any: # ... - def split(self, axis: Axis, new_axes: Sequence[Axis]) -> Sequence['NamedArray']: + def split(self, axis: Axis, new_axes: Sequence[Axis]) -> Sequence["NamedArray"]: return haliax.split(self, axis=axis, new_axes=new_axes) # def squeeze(self, axis: Optional[AxisSpec] = None) -> Any: # return haliax.squeeze(self, axis=axis) - def std(self, axis: Optional[AxisSpec] = None, dtype=None, out=None, ddof=0, keepdims=False, *, where=None) -> Any: - return haliax.std(self, axis=axis, dtype=dtype, out=out, ddof=ddof, keepdims=keepdims, where=where) - - def sum(self, axis: Optional[AxisSpec] = None, dtype=None, out=None, keepdims=None, - initial=None, where=None) -> Any: - return haliax.sum(self, axis=axis, dtype=dtype, out=out, keepdims=keepdims, initial=initial, where=where) - - def take(self, axis: Axis, index: Union[int, 'NamedArray']) -> Any: + def std( + self, + axis: Optional[AxisSpec] = None, + dtype=None, + out=None, + ddof=0, + keepdims=False, + *, + where=None, + ) -> Any: + return haliax.std( + self, + axis=axis, + dtype=dtype, + out=out, + ddof=ddof, + keepdims=keepdims, + where=where, + ) + + def sum( + self, + axis: Optional[AxisSpec] = None, + dtype=None, + out=None, + keepdims=None, + initial=None, + where=None, + ) -> Any: + return haliax.sum( + self, + axis=axis, + dtype=dtype, + out=out, + keepdims=keepdims, + initial=initial, + where=where, + ) + + def take(self, axis: Axis, index: Union[int, "NamedArray"]) -> Any: return haliax.take(self, axis=axis, index=index) - def tobytes(self, order='C') -> Any: + def tobytes(self, order="C") -> Any: return self.array.tobytes(order=order) def tolist(self) -> Any: @@ -197,8 +268,25 @@ class NamedArray: # def trace(self, offset=0, axis1: int = 0, axis2: int = 1, dtype=None, # out=None) -> Any: - def var(self, axis: Optional[AxisSpec] = None, dtype=None, out=None, ddof=0, keepdims=False, *, where=None) -> Any: - return haliax.var(self, axis=axis, dtype=dtype, out=out, ddof=ddof, keepdims=keepdims, where=where) + def var( + self, + axis: Optional[AxisSpec] = None, + dtype=None, + out=None, + ddof=0, + keepdims=False, + *, + where=None, + ) -> Any: + return haliax.var( + self, + axis=axis, + dtype=dtype, + out=out, + ddof=ddof, + keepdims=keepdims, + where=where, + ) # operators def __add__(self, other) -> Any: @@ -237,10 +325,10 @@ def take(array: NamedArray, axis: Axis, index: Union[int, NamedArray]) -> NamedA if isinstance(index, int): # just drop the axis new_array = jnp.take(array.array, index, axis=axis_index) - new_axes = array.axes[:axis_index] + array.axes[axis_index+1:] + new_axes = array.axes[:axis_index] + array.axes[axis_index + 1 :] else: new_array = jnp.take(array.array, index.array, axis=axis_index) - new_axes = array.axes[:axis_index] + index.axes + array.axes[axis_index+1:] + new_axes = array.axes[:axis_index] + index.axes + array.axes[axis_index + 1 :] # new axes come from splicing the old axis with return NamedArray(new_array, new_axes) @@ -259,27 +347,31 @@ def dot(axis: AxisSpec, *arrays: NamedArray, precision=None) -> NamedArray: axis_mappings: Dict[Axis, int] = {} for a in arrays: - spec = '' + spec = "" for ax in a.axes: if ax in axis_mappings: - spec += f'{axis_mappings[ax]} ' + spec += f"{axis_mappings[ax]} " else: axis_mappings[ax] = next_index - spec += f'{next_index} ' + spec += f"{next_index} " next_index += 1 array_specs.append(spec) # now compute the output axes: output_axes = tuple(ax for ax in axis_mappings.keys() if ax not in axis) - output_spec = ' '.join(str(axis_mappings[ax]) for ax in output_axes) + output_spec = " ".join(str(axis_mappings[ax]) for ax in output_axes) - output = jnp.einsum(', '.join(array_specs) + "-> " + output_spec, *[a.array for a in arrays], precision=precision) + output = jnp.einsum( + ", ".join(array_specs) + "-> " + output_spec, + *[a.array for a in arrays], + precision=precision, + ) return NamedArray(output, output_axes) -T = TypeVar('T') +T = TypeVar("T") def _ensure_tuple(x: Union[Sequence[T], T]) -> Tuple[T, ...]: @@ -292,8 +384,8 @@ def named(a: jnp.ndarray, axis: AxisSpec) -> NamedArray: """Creates a NamedArray from a numpy array and a list of axes""" if isinstance(axis, Axis): if jnp.shape(a) != axis.size: - raise ValueError(f'Shape of array {jnp.shape(a)} does not match size of axis {axis.size}') - return NamedArray(a, (axis, )) + raise ValueError(f"Shape of array {jnp.shape(a)} does not match size of axis {axis.size}") + return NamedArray(a, (axis,)) else: shape: Tuple[Axis, ...] = _ensure_tuple(axis) # verify the shape is correct diff --git a/src/haliax/nn.py b/src/haliax/nn.py index 7ceec15..400204b 100644 --- a/src/haliax/nn.py +++ b/src/haliax/nn.py @@ -1,5 +1,7 @@ import jax.nn as jnn -from .wrap import wrap_elemwise_unary, wrap_reduction_call, wrap_normalization_call + +from .wrap import wrap_elemwise_unary, wrap_normalization_call, wrap_reduction_call + relu = wrap_elemwise_unary(jnn.relu) relu6 = wrap_elemwise_unary(jnn.relu6) @@ -25,6 +27,25 @@ softmax = wrap_normalization_call(jnn.softmax, False) log_softmax = wrap_normalization_call(jnn.log_softmax, False) -__all__ = ["relu", "relu6", "sigmoid", "softplus", "soft_sign", "silu", "swish", "log_sigmoid", "leaky_relu", - "hard_sigmoid", "hard_silu", "hard_swish", "hard_tanh", "elu", "celu", "selu", "gelu", "logsumexp", - "softmax", "log_softmax"] +__all__ = [ + "relu", + "relu6", + "sigmoid", + "softplus", + "soft_sign", + "silu", + "swish", + "log_sigmoid", + "leaky_relu", + "hard_sigmoid", + "hard_silu", + "hard_swish", + "hard_tanh", + "elu", + "celu", + "selu", + "gelu", + "logsumexp", + "softmax", + "log_softmax", +] diff --git a/src/haliax/random.py b/src/haliax/random.py index 1d113bb..773ade8 100644 --- a/src/haliax/random.py +++ b/src/haliax/random.py @@ -1,13 +1,11 @@ """Wrappers around jax.random functions.""" -import jax.random as jrandom - import functools -from haliax.core import Axis, AxisSpec, NamedArray +import jax.random as jrandom # TODO: handle broadcasting of array args to random functions (e.g. minval and maxval for uniform) -from haliax.core import _ensure_tuple +from haliax.core import Axis, AxisSpec, NamedArray, _ensure_tuple def _wrap_random_function(func): @@ -40,16 +38,16 @@ logistic = _wrap_random_function(jrandom.logistic) truncated_normal = _wrap_random_function(jrandom.truncated_normal) __all__ = [ - 'uniform', - 'normal', - 'randint', - 'bernoulli', - 'poisson', - 'exponential', - 'gamma', - 'beta', - 'laplace', - 'cauchy', - 'logistic', - 'truncated_normal', + "uniform", + "normal", + "randint", + "bernoulli", + "poisson", + "exponential", + "gamma", + "beta", + "laplace", + "cauchy", + "logistic", + "truncated_normal", ] diff --git a/src/haliax/wrap.py b/src/haliax/wrap.py index 9a8f37d..9a9df32 100644 --- a/src/haliax/wrap.py +++ b/src/haliax/wrap.py @@ -3,7 +3,7 @@ from typing import Optional import jax.numpy as jnp -from haliax.core import NamedArray, _ensure_tuple, AxisSpec +from haliax.core import AxisSpec, NamedArray, _ensure_tuple def wrap_elemwise_unary(f): @@ -22,9 +22,9 @@ def wrap_elemwise_unary(f): def wrap_reduction_call(fn): @functools.wraps(fn) def wrapper(a, axis: Optional[AxisSpec] = None, keepdims=False, **kwargs): - if kwargs.get('where', None) is not None: + if kwargs.get("where", None) is not None: raise ValueError("where is not supported yet for NamedArray") - if kwargs.get('out', None) is not None: + if kwargs.get("out", None) is not None: raise ValueError("where is not supported yet for NamedArray") if isinstance(a, NamedArray): @@ -43,16 +43,19 @@ def wrap_reduction_call(fn): result = fn(a.array, axis=indices, keepdims=keepdims, **kwargs) if jnp.isscalar(result): return result - return NamedArray(fn(a.array, axis=indices, keepdims=keepdims, **kwargs), new_axes) + return NamedArray(fn(a.array, axis=indices, keepdims=keepdims, **kwargs), tuple(new_axes)) else: return fn(a, axis=axis, keepdims=keepdims, **kwargs) - wrapper.__doc__ = """ + wrapper.__doc__ = ( + """ This function augments the behavior of `{fn}` to support NamedArrays, so that axis is a NamedArray. At the moment, neither `where` nor `out` are supported. ===== - """ + fn.__doc__ + """ + + fn.__doc__ + ) return wrapper @@ -76,12 +79,15 @@ def wrap_normalization_call(fn, single_axis_only: bool): else: return fn(a, axis=axis, **kwargs) - wrapper.__doc__ = """ + wrapper.__doc__ = ( + """ This function augments the behavior of `{fn}` to support NamedArrays, so that axis is a NamedArray. At the moment, neither `where` nor `out` are supported. ===== - """ + fn.__doc__ + """ + + fn.__doc__ + ) return wrapper commit 0cc8f924ce5b04a127ed4bc61274b29070407343 Date: 2022-08-12T13:27:44-07:00 add flake8 file diff --git a/.flake8 b/.flake8 new file mode 100644 index 0000000..e856b50 --- /dev/null +++ b/.flake8 @@ -0,0 +1,7 @@ +[flake8] +exclude = .git +max-line-length = 119 +ignore = E203, E501, W503, W605, F821 +per-file-ignores = + */__init__.py: F401 + examples/*.py: E402 commit c023403e6b84683dec07a2c98f550eb2c29febe5 Date: 2022-08-18T11:46:13-07:00 support mixed precision training via jmp diff --git a/requirements.txt b/requirements.txt index 081e6d5..982043e 100644 --- a/requirements.txt +++ b/requirements.txt @@ -10,3 +10,4 @@ datasets fsspec gcsfs braceexpand +git+https://github.com/deepmind/jmp#260e5ba01f46b10c579a61393e6c7e546aeae93e commit c263fdb7160ab5a53414fb91e93c7d78a0ea8d89 Date: 2022-08-18T20:16:03+00:00 gpt2 small with owt diff --git a/src/haliax/core.py b/src/haliax/core.py index 1025ff5..fa6b130 100644 --- a/src/haliax/core.py +++ b/src/haliax/core.py @@ -30,10 +30,10 @@ class NamedArray: if len(set(a.name for a in self.axes)) != len(self.axes): raise ValueError(f"Axes must be unique, but {self.axes} are not") - if isinstance(self.array, jax.core.Tracer) or isinstance(self.array, DeviceArray): - s = jnp.shape(self.array) - if s != tuple(a.size for a in self.axes): - raise ValueError(f"Shape of underlying array {s} does not match shape of axes {self.axes}") + #if isinstance(self.array, jax.core.Tracer) or isinstance(self.array, DeviceArray): + # s = jnp.shape(self.array) + # if s != tuple(a.size for a in self.axes): + # raise ValueError(f"Shape of underlying array {s} does not match shape of axes {self.axes}") def __array__(self): return self.array.__array__() commit c564b80f54c230c98cdfe3bc22487e82ab7974a1 Date: 2022-08-18T13:18:07-07:00 add back shape check diff --git a/src/haliax/core.py b/src/haliax/core.py index fa6b130..1025ff5 100644 --- a/src/haliax/core.py +++ b/src/haliax/core.py @@ -30,10 +30,10 @@ class NamedArray: if len(set(a.name for a in self.axes)) != len(self.axes): raise ValueError(f"Axes must be unique, but {self.axes} are not") - #if isinstance(self.array, jax.core.Tracer) or isinstance(self.array, DeviceArray): - # s = jnp.shape(self.array) - # if s != tuple(a.size for a in self.axes): - # raise ValueError(f"Shape of underlying array {s} does not match shape of axes {self.axes}") + if isinstance(self.array, jax.core.Tracer) or isinstance(self.array, DeviceArray): + s = jnp.shape(self.array) + if s != tuple(a.size for a in self.axes): + raise ValueError(f"Shape of underlying array {s} does not match shape of axes {self.axes}") def __array__(self): return self.array.__array__() commit 8cd591fbfc71e484b1576eb7196d1776d55b8231 Date: 2022-08-22T12:45:27-07:00 add rearrange to haliax diff --git a/pyproject.toml b/pyproject.toml index 6fbaff1..f473a39 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -12,3 +12,9 @@ force_grid_wrap = 0 use_parentheses = true ensure_newline_before_comments = true line_length = 119 + +[tool.mypy] +python_version = "3.10" + +[tool.mypy-haliax.core] +ignore_missing_imports = true diff --git a/src/haliax/__init__.py b/src/haliax/__init__.py index ece8b23..5264e90 100644 --- a/src/haliax/__init__.py +++ b/src/haliax/__init__.py @@ -5,7 +5,7 @@ import numpy as np import haliax.random as random -from .core import Axis, AxisSpec, NamedArray, dot, named, take +from .core import Axis, AxisSpec, NamedArray, dot, named, rearrange, take from .wrap import wrap_elemwise_unary, wrap_normalization_call, wrap_reduction_call @@ -158,6 +158,7 @@ __all__ = [ "named", "dot", "take", + "rearrange", "zeros", "ones", "full", diff --git a/src/haliax/core.py b/src/haliax/core.py index 1025ff5..1e5ea6e 100644 --- a/src/haliax/core.py +++ b/src/haliax/core.py @@ -1,5 +1,6 @@ from dataclasses import dataclass -from typing import Any, Dict, Optional, Sequence, Tuple, TypeVar, Union +from types import EllipsisType +from typing import Any, Dict, List, Optional, Sequence, Tuple, TypeVar, Union, cast import jax import jax.numpy as jnp @@ -67,6 +68,9 @@ class NamedArray: else: return tuple(self.lookup_indices(a) for a in axis) + def rearrange(self, axis: Sequence[Union[Axis, EllipsisType]]): + return rearrange(self, axis) + # np.ndarray methods: def all(self, axis: Optional[AxisSpec] = None, out=None, keepdims=None) -> Any: return haliax.all(self, axis=axis, out=out, keepdims=keepdims) @@ -371,6 +375,52 @@ def dot(axis: AxisSpec, *arrays: NamedArray, precision=None) -> NamedArray: return NamedArray(output, output_axes) +def rearrange(array: NamedArray, axes: Sequence[Union[Axis, EllipsisType]]): + """ + Rearrange an array so that its underlying storage conforms to axes. + axes may include up to 1 ellipsis, indicating that the remaining axes should be + permuted in the same order as the array's axes. + """ + if len(axes) == 0 and len(array.axes) != 0: + raise ValueError("No axes specified") + + if len(axes) == 1 and axes[0] is Ellipsis: + return array + + if axes.count(Ellipsis) > 1: + raise ValueError("Only one ellipsis allowed") + + used_indices = [False] * len(array.axes) + permute_spec: List[Union[int, EllipsisType]] = [] + for ax in axes: + if ax is Ellipsis: + permute_spec.append(Ellipsis) # will revisit + else: + assert isinstance(ax, Axis) # please mypy + index = array.lookup_indices(ax) + if index is None: + raise ValueError(f"Axis {ax} not found in {array}") + if used_indices[index]: + raise ValueError(f"Axis {ax} specified more than once") + used_indices[index] = True + permute_spec.append(index) + + if not all(used_indices): + # find the ellipsis position, replace it with all the unused indices + try: + ellipsis_index = permute_spec.index(Ellipsis) + except ValueError: + missing_axes = [ax for i, ax in enumerate(array.axes) if not used_indices[i]] + raise ValueError(f"Axes {missing_axes} not found and no ... specified. Array axes: {array.axes}") from None + + permute_spec[ellipsis_index : ellipsis_index + 1] = tuple( + i for i in range(len(array.axes)) if not used_indices[i] + ) + + out_axes = tuple(array.axes[i] for i in cast(List[int], permute_spec)) + return NamedArray(jnp.transpose(array.array, permute_spec), out_axes) + + T = TypeVar("T") commit 65c92e2efe559ddde236a1df41f684ba2181c20b Date: 2022-08-22T13:55:53-07:00 implement scan in haliax diff --git a/src/haliax/__init__.py b/src/haliax/__init__.py index 5264e90..bce5dfd 100644 --- a/src/haliax/__init__.py +++ b/src/haliax/__init__.py @@ -6,6 +6,7 @@ import numpy as np import haliax.random as random from .core import Axis, AxisSpec, NamedArray, dot, named, rearrange, take +from .hof import scan from .wrap import wrap_elemwise_unary, wrap_normalization_call, wrap_reduction_call @@ -241,4 +242,5 @@ __all__ = [ "cumsum", "cumprod", "cumproduct", + "scan", ] diff --git a/src/haliax/hof.py b/src/haliax/hof.py new file mode 100644 index 0000000..488832f --- /dev/null +++ b/src/haliax/hof.py @@ -0,0 +1,101 @@ +import dataclasses +from typing import Any, Callable, Tuple, TypeVar + +import jax +import jax.lax as lax + +from .core import Axis, NamedArray + + +Carry = TypeVar("Carry") +X = TypeVar("X") +Y = TypeVar("Y") + + +@jax.tree_util.register_pytree_node_class +@dataclasses.dataclass(frozen=True) +class _ScannedArrayResult: + """With scan in NamedArray, we can't just have the scan tree prepend the scanned axis to the result, because + we don't have a way to feed it the name of the scanned axis. This class is a 'chill' version of NamedArray + that doesn't check invariants until we're ready to create the result + """ + + array: jax.numpy.ndarray + main_axes: Tuple[Axis, ...] + + def to_named_array(self, scan_axis: Axis): + return NamedArray(self.array, (scan_axis,) + self.main_axes) + + def tree_flatten(self) -> Any: + return ((self.array,), self.main_axes) + + @classmethod + def tree_unflatten(cls, aux, tree: Any) -> Any: + assert len(tree) == 1 + return cls(tree[0], main_axes=aux) + + +def scan(f: Callable[[Carry, X], Tuple[Carry, Y]], axis: Axis, init: Carry, xs: X, reverse=False, unroll=1): + """ + Scan over a named axis. Arrays that are not part of a named axis will have their 0th dim scanned over + """ + if axis.size == 0: + return init, xs + + # This implementation is a bit tricky. + # First we have to hoist the axis we're scanning over to the front of the array. + # Then we have to scan over the 0th dim of the arrays (as flattened non-pytrees) + # We have to be careful that we don't try to create NamedArrays that have the shape of the scanned result + # but don't yet have the scanned axis as ones of `axes`, so we use _ScannedArrayResult that doesn't check + # invariants until we're ready to create the result. + + def ensure_first(leaf): + if isinstance(leaf, NamedArray): + return leaf.rearrange((axis, ...)) + else: + return leaf + + def named_array_leaf(leaf): + return isinstance(leaf, NamedArray) + + axis_first_xs = jax.tree_util.tree_map(ensure_first, xs, is_leaf=named_array_leaf) + + # now get a template for where we fold over the axis in question + def select_0th(leaf): + if isinstance(leaf, NamedArray): + return leaf.take(axis, 0) + else: + # other leaves don't matter + return leaf + + x_elem = jax.tree_util.tree_map(select_0th, axis_first_xs, is_leaf=named_array_leaf) + x_elem_structure = jax.tree_util.tree_structure(x_elem) + + def chill_named_arrays(leaf): + if isinstance(leaf, NamedArray): + return _ScannedArrayResult(leaf.array, leaf.axes) + else: + return leaf + + # now we can fold over the axis + def wrapped_fn(carry, x): + x = jax.tree_util.tree_unflatten(x_elem_structure, x) + carry, y = f(carry, x) + y = jax.tree_util.tree_map(chill_named_arrays, y, is_leaf=named_array_leaf) + return carry, y + + leaves = jax.tree_util.tree_leaves(axis_first_xs) + carry, ys = lax.scan(wrapped_fn, init, leaves, reverse=reverse, unroll=unroll) + + def unchill_named_arrays(leaf): + if isinstance(leaf, _ScannedArrayResult): + return leaf.to_named_array(axis) + else: + return leaf + + ys = jax.tree_util.tree_map(unchill_named_arrays, ys, is_leaf=lambda arr: isinstance(arr, _ScannedArrayResult)) + + return carry, ys + + +__all__ = ["scan"] commit fc58c37ce9d6edcb85bdb6c0ed58e5a7e400e125 Date: 2022-08-22T14:09:15-07:00 add fold_left since it's so much simpler diff --git a/src/haliax/__init__.py b/src/haliax/__init__.py index bce5dfd..6ea6160 100644 --- a/src/haliax/__init__.py +++ b/src/haliax/__init__.py @@ -6,7 +6,7 @@ import numpy as np import haliax.random as random from .core import Axis, AxisSpec, NamedArray, dot, named, rearrange, take -from .hof import scan +from .hof import fold_left, scan from .wrap import wrap_elemwise_unary, wrap_normalization_call, wrap_reduction_call @@ -243,4 +243,5 @@ __all__ = [ "cumprod", "cumproduct", "scan", + "fold_left", ] diff --git a/src/haliax/core.py b/src/haliax/core.py index 1e5ea6e..c37ab8f 100644 --- a/src/haliax/core.py +++ b/src/haliax/core.py @@ -387,6 +387,14 @@ def rearrange(array: NamedArray, axes: Sequence[Union[Axis, EllipsisType]]): if len(axes) == 1 and axes[0] is Ellipsis: return array + if len(axes) > len(array.axes): + raise ValueError("Too many axes specified") + + if axes == array.axes: + return array + + # TODO: add more fast paths? + if axes.count(Ellipsis) > 1: raise ValueError("Only one ellipsis allowed") diff --git a/src/haliax/hof.py b/src/haliax/hof.py index 488832f..996ba2d 100644 --- a/src/haliax/hof.py +++ b/src/haliax/hof.py @@ -1,4 +1,5 @@ import dataclasses +from functools import partial from typing import Any, Callable, Tuple, TypeVar import jax @@ -39,8 +40,6 @@ def scan(f: Callable[[Carry, X], Tuple[Carry, Y]], axis: Axis, init: Carry, xs: """ Scan over a named axis. Arrays that are not part of a named axis will have their 0th dim scanned over """ - if axis.size == 0: - return init, xs # This implementation is a bit tricky. # First we have to hoist the axis we're scanning over to the front of the array. @@ -49,26 +48,10 @@ def scan(f: Callable[[Carry, X], Tuple[Carry, Y]], axis: Axis, init: Carry, xs: # but don't yet have the scanned axis as ones of `axes`, so we use _ScannedArrayResult that doesn't check # invariants until we're ready to create the result. - def ensure_first(leaf): - if isinstance(leaf, NamedArray): - return leaf.rearrange((axis, ...)) - else: - return leaf - - def named_array_leaf(leaf): - return isinstance(leaf, NamedArray) - - axis_first_xs = jax.tree_util.tree_map(ensure_first, xs, is_leaf=named_array_leaf) + axis_first_xs = jax.tree_util.tree_map(partial(_ensure_first, axis), xs, is_leaf=_named_array_leaf) # now get a template for where we fold over the axis in question - def select_0th(leaf): - if isinstance(leaf, NamedArray): - return leaf.take(axis, 0) - else: - # other leaves don't matter - return leaf - - x_elem = jax.tree_util.tree_map(select_0th, axis_first_xs, is_leaf=named_array_leaf) + x_elem = jax.tree_util.tree_map(partial(_select_0th, axis), axis_first_xs, is_leaf=_named_array_leaf) x_elem_structure = jax.tree_util.tree_structure(x_elem) def chill_named_arrays(leaf): @@ -81,7 +64,7 @@ def scan(f: Callable[[Carry, X], Tuple[Carry, Y]], axis: Axis, init: Carry, xs: def wrapped_fn(carry, x): x = jax.tree_util.tree_unflatten(x_elem_structure, x) carry, y = f(carry, x) - y = jax.tree_util.tree_map(chill_named_arrays, y, is_leaf=named_array_leaf) + y = jax.tree_util.tree_map(chill_named_arrays, y, is_leaf=_named_array_leaf) return carry, y leaves = jax.tree_util.tree_leaves(axis_first_xs) @@ -98,4 +81,58 @@ def scan(f: Callable[[Carry, X], Tuple[Carry, Y]], axis: Axis, init: Carry, xs: return carry, ys -__all__ = ["scan"] +def _select_0th(axis, leaf): + if isinstance(leaf, NamedArray): + return leaf.take(axis, 0) + else: + # other leaves don't matter + return leaf + + +def _named_array_leaf(leaf): + return isinstance(leaf, NamedArray) + + +def _ensure_first(axis, leaf): + if isinstance(leaf, NamedArray): + return leaf.rearrange((axis, ...)) + else: + return leaf + + +def fold_left( + fn: Callable[[Carry, X], Carry], axis: Axis, init: Carry, xs: X, reverse: bool = False, unroll: int = 1 +) -> Carry: + """ + Slightly simpler implementation of scan that folds over the first axis of the array, not returning intermediates. + + If reverse is True, the fold is actually a fold_right + """ + if axis.size == 0: + return init + + # This implementation is a bit tricky. + # First we have to hoist the axis we're scanning over to the front of the array. + # Then we have to scan over the 0th dim of the arrays (as flattened non-pytrees) + # We have to be careful that we don't try to create NamedArrays that have the shape of the scanned result + # but don't yet have the scanned axis as ones of `axes`, so we use _ScannedArrayResult that doesn't check + # invariants until we're ready to create the result. + + axis_first_xs = jax.tree_util.tree_map(partial(_ensure_first, axis), xs, is_leaf=_named_array_leaf) + + # now get a template for where we fold over the axis in question + x_elem = jax.tree_util.tree_map(partial(_select_0th, axis), axis_first_xs, is_leaf=_named_array_leaf) + x_elem_structure = jax.tree_util.tree_structure(x_elem) + + # now we can fold over the axis + def wrapped_fn(carry, x): + x = jax.tree_util.tree_unflatten(x_elem_structure, x) + return fn(carry, x), None + + leaves = jax.tree_util.tree_leaves(axis_first_xs) + carry, _ = lax.scan(wrapped_fn, init, leaves, reverse=reverse, unroll=unroll) + + return carry + + +__all__ = ["scan", "fold_left"] commit d9f9f28cce9581573aed1cf9b3f4adc9c6914a2a Date: 2022-08-22T14:36:36-07:00 add fast paths for rearrange diff --git a/src/haliax/core.py b/src/haliax/core.py index c37ab8f..b2f69aa 100644 --- a/src/haliax/core.py +++ b/src/haliax/core.py @@ -384,16 +384,21 @@ def rearrange(array: NamedArray, axes: Sequence[Union[Axis, EllipsisType]]): if len(axes) == 0 and len(array.axes) != 0: raise ValueError("No axes specified") - if len(axes) == 1 and axes[0] is Ellipsis: - return array - if len(axes) > len(array.axes): raise ValueError("Too many axes specified") + # various fast paths + if len(axes) == 1 and axes[0] is Ellipsis: + return array + if axes == array.axes: return array - # TODO: add more fast paths? + if axes[-1] is Ellipsis and array.axes[0 : len(axes) - 1] == axes[0 : len(axes) - 1]: + return array + + if axes[0] is Ellipsis and array.axes[len(axes) - 1 :] == axes[1:]: + return array if axes.count(Ellipsis) > 1: raise ValueError("Only one ellipsis allowed") commit cd1e41b9bbdbb20ba32089345b8b14bac8dba7f9 Date: 2022-08-22T16:12:35-07:00 add vmap, switch Gpt2Transformer to haliax.vmap + scan diff --git a/src/haliax/__init__.py b/src/haliax/__init__.py index 6ea6160..c00dabb 100644 --- a/src/haliax/__init__.py +++ b/src/haliax/__init__.py @@ -6,7 +6,7 @@ import numpy as np import haliax.random as random from .core import Axis, AxisSpec, NamedArray, dot, named, rearrange, take -from .hof import fold_left, scan +from .hof import fold_left, scan, vmap from .wrap import wrap_elemwise_unary, wrap_normalization_call, wrap_reduction_call @@ -48,6 +48,10 @@ def full_like(a: NamedArray, fill_value, dtype=None) -> NamedArray: return NamedArray(jnp.full_like(a.array, fill_value, dtype=dtype), a.axes) +def arange(axis: Axis, dtype=None) -> NamedArray: + return NamedArray(jnp.arange(axis.size, dtype=dtype), (axis,)) + + # splitting and stacking etc def split(a: NamedArray, axis: Axis, new_axes: Sequence[Axis]) -> Sequence[NamedArray]: # check the lengths of the new axes @@ -166,6 +170,7 @@ __all__ = [ "zeros_like", "ones_like", "full_like", + "arange", "random", "abs", "absolute", @@ -244,4 +249,5 @@ __all__ = [ "cumproduct", "scan", "fold_left", + "vmap", ] diff --git a/src/haliax/hof.py b/src/haliax/hof.py index 996ba2d..aa14da0 100644 --- a/src/haliax/hof.py +++ b/src/haliax/hof.py @@ -1,11 +1,12 @@ import dataclasses -from functools import partial -from typing import Any, Callable, Tuple, TypeVar +from functools import partial, wraps +from typing import Any, Callable, Sequence, Tuple, TypeVar, Union +import equinox import jax import jax.lax as lax -from .core import Axis, NamedArray +from .core import Axis, NamedArray, _ensure_tuple Carry = TypeVar("Carry") @@ -54,31 +55,36 @@ def scan(f: Callable[[Carry, X], Tuple[Carry, Y]], axis: Axis, init: Carry, xs: x_elem = jax.tree_util.tree_map(partial(_select_0th, axis), axis_first_xs, is_leaf=_named_array_leaf) x_elem_structure = jax.tree_util.tree_structure(x_elem) - def chill_named_arrays(leaf): - if isinstance(leaf, NamedArray): - return _ScannedArrayResult(leaf.array, leaf.axes) - else: - return leaf - # now we can fold over the axis def wrapped_fn(carry, x): x = jax.tree_util.tree_unflatten(x_elem_structure, x) carry, y = f(carry, x) - y = jax.tree_util.tree_map(chill_named_arrays, y, is_leaf=_named_array_leaf) + y = jax.tree_util.tree_map(_chill_named_arrays, y, is_leaf=_named_array_leaf) return carry, y leaves = jax.tree_util.tree_leaves(axis_first_xs) carry, ys = lax.scan(wrapped_fn, init, leaves, reverse=reverse, unroll=unroll) + ys = jax.tree_util.tree_map(partial(_unchill_named_arrays, axis), ys, is_leaf=_is_chill_array) - def unchill_named_arrays(leaf): - if isinstance(leaf, _ScannedArrayResult): - return leaf.to_named_array(axis) - else: - return leaf + return carry, ys - ys = jax.tree_util.tree_map(unchill_named_arrays, ys, is_leaf=lambda arr: isinstance(arr, _ScannedArrayResult)) - return carry, ys +def _is_chill_array(arr): + return isinstance(arr, _ScannedArrayResult) + + +def _unchill_named_arrays(axis, leaf): + if isinstance(leaf, _ScannedArrayResult): + return leaf.to_named_array(axis) + else: + return leaf + + +def _chill_named_arrays(leaf): + if isinstance(leaf, NamedArray): + return _ScannedArrayResult(leaf.array, leaf.axes) + else: + return leaf def _select_0th(axis, leaf): @@ -135,4 +141,57 @@ def fold_left( return carry -__all__ = ["scan", "fold_left"] +# TODO: add test for vmap +def vmap( + fn, + axis: Axis, + unmapped_argnums: Union[int, Sequence[int]] = (), +): + """ + NamedArray aware version of jax.vmap. + unmapped_argnums are the argnums of the function that are not batched over the axis. + """ + unmmapped_argnums = _ensure_tuple(unmapped_argnums) + + def _index_of_axis(array): + if isinstance(array, NamedArray): + return array.axes.index(axis) + elif equinox.is_array(array): + return 0 + else: + return None + + # TODO: do fancier things with kwargs and signature and such + # TODO: maybe implement equinox-style filtering vmap + @wraps(fn) + def wrapped_vmap_fn(*args): + # TODO: this probably results in a lot of compilation misses. Need to think about it. + mapped_axes = [] + chilled_args = [] + # TODO: have to figure out element structure, but not relevant today + + for i, arg in enumerate(args): + if i in unmmapped_argnums: + mapped_axes.append(None) + else: + chilled_arg = jax.tree_util.tree_map(_chill_named_arrays, arg, is_leaf=_named_array_leaf) + chilled_args.append(chilled_arg) + mapped_axis = jax.tree_util.tree_map(_index_of_axis, chilled_arg, is_leaf=_is_chill_array) + mapped_axes.append(mapped_axis) + + def wrapped_fn(*args): + unchilled_args = jax.tree_util.tree_map( + partial(_unchill_named_arrays, axis), args, is_leaf=_named_array_leaf + ) + r = fn(*unchilled_args) + chilled = jax.tree_util.tree_map(_chill_named_arrays, r, is_leaf=_named_array_leaf) + return chilled + + result = jax.vmap(wrapped_fn, in_axes=mapped_axes, out_axes=0, axis_size=axis.size)(*args) + result = jax.tree_util.tree_map(partial(_unchill_named_arrays, axis), result, is_leaf=_is_chill_array) + return result + + return wrapped_vmap_fn + + +__all__ = ["scan", "fold_left", "vmap"] commit 13dca22984a886a7140d3b38bd95e2acb6f44127 Date: 2022-08-22T17:10:49-07:00 fix serialization/deserialization given new vectorized loading diff --git a/src/haliax/core.py b/src/haliax/core.py index b2f69aa..6e65e6c 100644 --- a/src/haliax/core.py +++ b/src/haliax/core.py @@ -384,9 +384,6 @@ def rearrange(array: NamedArray, axes: Sequence[Union[Axis, EllipsisType]]): if len(axes) == 0 and len(array.axes) != 0: raise ValueError("No axes specified") - if len(axes) > len(array.axes): - raise ValueError("Too many axes specified") - # various fast paths if len(axes) == 1 and axes[0] is Ellipsis: return array commit 769f763cdc0fba398874952fbb81493749bd67bd Date: 2022-08-23T11:30:34-07:00 less noise via .gitignore diff --git a/.gitignore b/.gitignore index 21b0fa6..b07acad 100644 --- a/.gitignore +++ b/.gitignore @@ -135,4 +135,11 @@ dmypy.json # Wandb stuff -/wandb \ No newline at end of file +/wandb + +# dataset cache files +*.parquet +ledger.json + +/checkpoints +*.jaxpr \ No newline at end of file commit 836afacd35524bf435ec7a25161159560d911524 Date: 2022-08-25T21:00:03+00:00 rename "hidden" to "embed" everywhere diff --git a/src/haliax/core.py b/src/haliax/core.py index 6e65e6c..7ccc463 100644 --- a/src/haliax/core.py +++ b/src/haliax/core.py @@ -14,6 +14,9 @@ class Axis: name: str size: int + def alias(self, new_name: str): + return Axis(new_name, self.size) + AxisSpec = Union[Axis, Sequence[Axis]] commit 848535626dcb0f779f39dac56d5b8ea5338fc807 Date: 2022-08-25T14:50:29-07:00 Merge remote-tracking branch 'origin/sorta_working' into named_scan commit f0a9524a84c2feee23675b17e9c9dde1fd20e3d7 Date: 2022-08-26T14:06:29-07:00 fix behavior if an unnecessary ... is added diff --git a/src/haliax/core.py b/src/haliax/core.py index 7ccc463..80f5ff1 100644 --- a/src/haliax/core.py +++ b/src/haliax/core.py @@ -405,9 +405,11 @@ def rearrange(array: NamedArray, axes: Sequence[Union[Axis, EllipsisType]]): used_indices = [False] * len(array.axes) permute_spec: List[Union[int, EllipsisType]] = [] + ellipsis_pos = None for ax in axes: if ax is Ellipsis: permute_spec.append(Ellipsis) # will revisit + ellipsis_pos = len(permute_spec) - 1 else: assert isinstance(ax, Axis) # please mypy index = array.lookup_indices(ax) @@ -420,15 +422,13 @@ def rearrange(array: NamedArray, axes: Sequence[Union[Axis, EllipsisType]]): if not all(used_indices): # find the ellipsis position, replace it with all the unused indices - try: - ellipsis_index = permute_spec.index(Ellipsis) - except ValueError: + if ellipsis_pos is None: missing_axes = [ax for i, ax in enumerate(array.axes) if not used_indices[i]] raise ValueError(f"Axes {missing_axes} not found and no ... specified. Array axes: {array.axes}") from None - permute_spec[ellipsis_index : ellipsis_index + 1] = tuple( - i for i in range(len(array.axes)) if not used_indices[i] - ) + permute_spec[ellipsis_pos : ellipsis_pos + 1] = tuple(i for i in range(len(array.axes)) if not used_indices[i]) + elif ellipsis_pos is not None: + permute_spec.remove(Ellipsis) out_axes = tuple(array.axes[i] for i in cast(List[int], permute_spec)) return NamedArray(jnp.transpose(array.array, permute_spec), out_axes) commit 8216bbf85cb3c4d5da8938b5dcdabbc724d633e2 Date: 2022-08-26T14:12:28-07:00 add methods to haliax for unflatten/renaming diff --git a/src/haliax/__init__.py b/src/haliax/__init__.py index c00dabb..457445b 100644 --- a/src/haliax/__init__.py +++ b/src/haliax/__init__.py @@ -1,18 +1,26 @@ -from typing import Sequence - import jax.numpy as jnp -import numpy as np import haliax.random as random -from .core import Axis, AxisSpec, NamedArray, dot, named, rearrange, take +from .core import ( + Axis, + AxisSpec, + NamedArray, + concat_axis_specs, + dot, + flatten_axes, + named, + rearrange, + rename, + split, + take, + unbind, + unflatten_axis, +) from .hof import fold_left, scan, vmap from .wrap import wrap_elemwise_unary, wrap_normalization_call, wrap_reduction_call -_sum = sum - - # creation routines def zeros(shape: AxisSpec, dtype=None) -> NamedArray: """Creates a NamedArray with all elements set to 0""" @@ -52,27 +60,6 @@ def arange(axis: Axis, dtype=None) -> NamedArray: return NamedArray(jnp.arange(axis.size, dtype=dtype), (axis,)) -# splitting and stacking etc -def split(a: NamedArray, axis: Axis, new_axes: Sequence[Axis]) -> Sequence[NamedArray]: - # check the lengths of the new axes - if axis not in a.axes: - raise ValueError(f"Axis {axis} not found in {a.axes}") - - total_len = _sum(x.size for x in new_axes) - if total_len != axis.size: - raise ValueError(f"The total length of the new axes {total_len} does not match the length of the axis {axis}") - - index = a.lookup_indices(axis) - - # now we can split the array - offsets = np.cumsum([0] + [x.size for x in new_axes])[1:-1] - - new_arrays = np.split(a.array, indices_or_sections=offsets, axis=index) - ret_axes = [tuple(ax2 if ax2 is not axis else new_axis for ax2 in a.axes) for new_axis in new_axes] - - return [NamedArray(x, ax) for x, ax in zip(new_arrays, ret_axes)] - - # elementwise unary operations abs = wrap_elemwise_unary(jnp.abs) absolute = wrap_elemwise_unary(jnp.absolute) @@ -162,8 +149,13 @@ __all__ = [ "AxisSpec", "named", "dot", + "split", + "flatten_axes", "take", + "unbind", + "rename", "rearrange", + "concat_axis_specs", "zeros", "ones", "full", diff --git a/src/haliax/core.py b/src/haliax/core.py index 80f5ff1..1cccddf 100644 --- a/src/haliax/core.py +++ b/src/haliax/core.py @@ -1,9 +1,11 @@ from dataclasses import dataclass +from math import prod from types import EllipsisType -from typing import Any, Dict, List, Optional, Sequence, Tuple, TypeVar, Union, cast +from typing import Any, Dict, List, Mapping, Optional, Sequence, Tuple, TypeVar, Union, cast import jax import jax.numpy as jnp +import numpy as np from jaxlib.xla_extension import DeviceArray import haliax @@ -221,6 +223,18 @@ class NamedArray: def split(self, axis: Axis, new_axes: Sequence[Axis]) -> Sequence["NamedArray"]: return haliax.split(self, axis=axis, new_axes=new_axes) + def flatten_axes(self, old_axes: Sequence[Axis], new_axis: Axis) -> "NamedArray": + return haliax.flatten_axes(self, old_axes=old_axes, new_axis=new_axis) + + def unflatten_axis(self, axis: Axis, new_axes: Sequence[Axis]) -> "NamedArray": + return haliax.unflatten_axis(self, axis=axis, new_axes=new_axes) + + def unbind(self, axis: Axis) -> Sequence["NamedArray"]: + return haliax.unbind(self, axis=axis) + + def rename(self, renames: Mapping[Axis, Axis]): + return haliax.rename(self, renames=renames) + # def squeeze(self, axis: Optional[AxisSpec] = None) -> Any: # return haliax.squeeze(self, axis=axis) @@ -378,6 +392,30 @@ def dot(axis: AxisSpec, *arrays: NamedArray, precision=None) -> NamedArray: return NamedArray(output, output_axes) +def split(a: NamedArray, axis: Axis, new_axes: Sequence[Axis]) -> Sequence[NamedArray]: + # check the lengths of the new axes + if axis not in a.axes: + raise ValueError(f"Axis {axis} not found in {a.axes}") + + total_len = sum(x.size for x in new_axes) + if total_len != axis.size: + raise ValueError(f"The total length of the new axes {total_len} does not match the length of the axis {axis}") + + index = a.lookup_indices(axis) + + # now we can split the array + offsets = np.cumsum([0] + [x.size for x in new_axes])[1:-1] + + new_arrays = np.split(a.array, indices_or_sections=offsets, axis=index) + ret_axes = [tuple(ax2 if ax2 is not axis else new_axis for ax2 in a.axes) for new_axis in new_axes] + + return [NamedArray(x, ax) for x, ax in zip(new_arrays, ret_axes)] + + +# TODO: can we add einops-style combined split/merge here? +# e.g. we'd like something like rearrange(array, (..., new_axis), merge_axes={new_axis: (old_axis1, old_axis2)}) +# or rearrange(array, (new_axis1, ..., new_axis2), split_axes={old_axis: (new_axis1, new_axis2)}) +# or even rearrange(array, (x, ..., b, a), map_axes={old_axis: (a, b), x: (old1, old2)}) def rearrange(array: NamedArray, axes: Sequence[Union[Axis, EllipsisType]]): """ Rearrange an array so that its underlying storage conforms to axes. @@ -434,6 +472,69 @@ def rearrange(array: NamedArray, axes: Sequence[Union[Axis, EllipsisType]]): return NamedArray(jnp.transpose(array.array, permute_spec), out_axes) +def unbind(array: NamedArray, axis: Axis) -> List[NamedArray]: + """ + Unbind an array along an axis, returning a list of NamedArrays. Analogous to torch.unbind or np.rollaxis + """ + axis_index = array.lookup_indices(axis) + if axis_index is None: + raise ValueError(f"axis {axis} not found in {array}") + arrays = jnp.rollaxis(array.array, axis=axis_index, start=0) + new_axes = array.axes[:axis_index] + array.axes[axis_index + 1 :] + return [NamedArray(a, new_axes) for a in arrays] + + +def rename(array: NamedArray, renames: Mapping[Axis, Axis]) -> NamedArray: + for old, new in renames.items(): + if old.size != new.size: + raise ValueError(f"Cannot rename axis {old} to {new}: size mismatch") + new_axes = tuple(renames.get(ax, ax) for ax in array.axes) + return NamedArray(array.array, new_axes) + + +def flatten_axes(array: NamedArray, old_axes: Sequence[Axis], new_axis: Axis) -> NamedArray: + """ + Merge a sequence of axes into a single axis. The new axis must have the same size as the product of the old axes. + For now the new axis will always be the last axis + """ + if len(old_axes) == 0: + raise ValueError("Must specify at least one axis to merge") + + if new_axis.size != prod(ax.size for ax in old_axes): + raise ValueError(f"Cannot merge {old_axes} into {new_axis}: size mismatch") + + # TODO: might want to do something more clever here when the old_axes aren't at the end + array = rearrange(array, (...,) + tuple(old_axes)) + new_axes = array.axes[: -len(old_axes)] + (new_axis,) + raw_array = array.array.reshape(array.array.shape[: -len(old_axes)] + (new_axis.size,)) + return NamedArray(raw_array, new_axes) + + +def unflatten_axis(array: NamedArray, axis: Axis, new_axes: Sequence[Axis]) -> NamedArray: + """ + Split an axis into a sequence of axes. The old axis must have the same size as the product of the new axes. + """ + old_index = array.lookup_indices(axis) + if old_index is None: + raise ValueError(f"Axis {axis} not found in {array}") + + if len(new_axes) == 0: + if axis.size == 1: + # just remove the old axis, akin to squeeze + new_array = jnp.squeeze(array.array, axis=old_index) + new_axes = array.axes[:old_index] + array.axes[old_index + 1 :] + return NamedArray(new_array, new_axes) + else: + raise ValueError("Must specify at least one axis to split") + + if axis.size != prod(ax.size for ax in new_axes): + raise ValueError(f"Cannot split {axis} into {new_axes}: size mismatch") + + new_axes = array.axes[:old_index] + tuple(new_axes) + array.axes[old_index + 1 :] + new_array = jnp.reshape(array.array, [ax.size for ax in new_axes]) + return NamedArray(new_array, new_axes) + + T = TypeVar("T") @@ -456,3 +557,34 @@ def named(a: jnp.ndarray, axis: AxisSpec) -> NamedArray: raise ValueError(f"Shape of array {jnp.shape(a)} does not match shape of axes {axis}") return NamedArray(a, shape) + + +def concat_axis_specs(a1: AxisSpec, a2: AxisSpec) -> AxisSpec: + """Concatenates two AxisSpec. Raises ValueError if any axis is present in both specs""" + if isinstance(a1, Axis) and isinstance(a2, Axis): + if a1 == a2: + raise ValueError(f"Axis {a1} specified twice") + return (a1, a2) + else: + a1 = _ensure_tuple(a1) + a2 = _ensure_tuple(a2) + if any(x in a2 for x in a1) or any(x in a1 for x in a2): + overlap = set(a1).intersection(set(a2)) + raise ValueError(f"AxisSpecs overlap! {' '.join(str(x) for x in overlap)}") + return a1 + a2 + + +__all__ = [ + "Axis", + "AxisSpec", + "NamedArray", + "concat_axis_specs", + "dot", + "named", + "rearrange", + "take", + "split", + "flatten_axes", + "unflatten_axis", + "unbind", +] commit fbe5040ccc3151fad3f86231ca75b8f4ffc756aa Date: 2022-08-27T09:20:47-07:00 add logical axis partitioning with_sharding_constraint diff --git a/src/haliax/core.py b/src/haliax/core.py index 1cccddf..6cb28e0 100644 --- a/src/haliax/core.py +++ b/src/haliax/core.py @@ -1,7 +1,7 @@ from dataclasses import dataclass from math import prod from types import EllipsisType -from typing import Any, Dict, List, Mapping, Optional, Sequence, Tuple, TypeVar, Union, cast +from typing import Any, Dict, List, Mapping, Optional, Sequence, Tuple, Union, cast import jax import jax.numpy as jnp @@ -9,6 +9,7 @@ import numpy as np from jaxlib.xla_extension import DeviceArray import haliax +from haliax.util import ensure_tuple @dataclass(frozen=True) @@ -535,15 +536,6 @@ def unflatten_axis(array: NamedArray, axis: Axis, new_axes: Sequence[Axis]) -> N return NamedArray(new_array, new_axes) -T = TypeVar("T") - - -def _ensure_tuple(x: Union[Sequence[T], T]) -> Tuple[T, ...]: - if isinstance(x, Sequence): - return tuple(x) - return (x,) - - def named(a: jnp.ndarray, axis: AxisSpec) -> NamedArray: """Creates a NamedArray from a numpy array and a list of axes""" if isinstance(axis, Axis): @@ -551,7 +543,7 @@ def named(a: jnp.ndarray, axis: AxisSpec) -> NamedArray: raise ValueError(f"Shape of array {jnp.shape(a)} does not match size of axis {axis.size}") return NamedArray(a, (axis,)) else: - shape: Tuple[Axis, ...] = _ensure_tuple(axis) + shape: Tuple[Axis, ...] = ensure_tuple(axis) # verify the shape is correct if jnp.shape(a) != tuple(x.size for x in shape): raise ValueError(f"Shape of array {jnp.shape(a)} does not match shape of axes {axis}") @@ -566,8 +558,8 @@ def concat_axis_specs(a1: AxisSpec, a2: AxisSpec) -> AxisSpec: raise ValueError(f"Axis {a1} specified twice") return (a1, a2) else: - a1 = _ensure_tuple(a1) - a2 = _ensure_tuple(a2) + a1 = ensure_tuple(a1) + a2 = ensure_tuple(a2) if any(x in a2 for x in a1) or any(x in a1 for x in a2): overlap = set(a1).intersection(set(a2)) raise ValueError(f"AxisSpecs overlap! {' '.join(str(x) for x in overlap)}") diff --git a/src/haliax/hof.py b/src/haliax/hof.py index aa14da0..60dd1e5 100644 --- a/src/haliax/hof.py +++ b/src/haliax/hof.py @@ -6,7 +6,8 @@ import equinox import jax import jax.lax as lax -from .core import Axis, NamedArray, _ensure_tuple +from .core import Axis, NamedArray +from .util import ensure_tuple, is_named_array Carry = TypeVar("Carry") @@ -49,17 +50,17 @@ def scan(f: Callable[[Carry, X], Tuple[Carry, Y]], axis: Axis, init: Carry, xs: # but don't yet have the scanned axis as ones of `axes`, so we use _ScannedArrayResult that doesn't check # invariants until we're ready to create the result. - axis_first_xs = jax.tree_util.tree_map(partial(_ensure_first, axis), xs, is_leaf=_named_array_leaf) + axis_first_xs = jax.tree_util.tree_map(partial(_ensure_first, axis), xs, is_leaf=is_named_array) # now get a template for where we fold over the axis in question - x_elem = jax.tree_util.tree_map(partial(_select_0th, axis), axis_first_xs, is_leaf=_named_array_leaf) + x_elem = jax.tree_util.tree_map(partial(_select_0th, axis), axis_first_xs, is_leaf=is_named_array) x_elem_structure = jax.tree_util.tree_structure(x_elem) # now we can fold over the axis def wrapped_fn(carry, x): x = jax.tree_util.tree_unflatten(x_elem_structure, x) carry, y = f(carry, x) - y = jax.tree_util.tree_map(_chill_named_arrays, y, is_leaf=_named_array_leaf) + y = jax.tree_util.tree_map(_chill_named_arrays, y, is_leaf=is_named_array) return carry, y leaves = jax.tree_util.tree_leaves(axis_first_xs) @@ -95,10 +96,6 @@ def _select_0th(axis, leaf): return leaf -def _named_array_leaf(leaf): - return isinstance(leaf, NamedArray) - - def _ensure_first(axis, leaf): if isinstance(leaf, NamedArray): return leaf.rearrange((axis, ...)) @@ -124,10 +121,10 @@ def fold_left( # but don't yet have the scanned axis as ones of `axes`, so we use _ScannedArrayResult that doesn't check # invariants until we're ready to create the result. - axis_first_xs = jax.tree_util.tree_map(partial(_ensure_first, axis), xs, is_leaf=_named_array_leaf) + axis_first_xs = jax.tree_util.tree_map(partial(_ensure_first, axis), xs, is_leaf=is_named_array) # now get a template for where we fold over the axis in question - x_elem = jax.tree_util.tree_map(partial(_select_0th, axis), axis_first_xs, is_leaf=_named_array_leaf) + x_elem = jax.tree_util.tree_map(partial(_select_0th, axis), axis_first_xs, is_leaf=is_named_array) x_elem_structure = jax.tree_util.tree_structure(x_elem) # now we can fold over the axis @@ -151,7 +148,7 @@ def vmap( NamedArray aware version of jax.vmap. unmapped_argnums are the argnums of the function that are not batched over the axis. """ - unmmapped_argnums = _ensure_tuple(unmapped_argnums) + unmmapped_argnums = ensure_tuple(unmapped_argnums) def _index_of_axis(array): if isinstance(array, NamedArray): @@ -174,17 +171,15 @@ def vmap( if i in unmmapped_argnums: mapped_axes.append(None) else: - chilled_arg = jax.tree_util.tree_map(_chill_named_arrays, arg, is_leaf=_named_array_leaf) + chilled_arg = jax.tree_util.tree_map(_chill_named_arrays, arg, is_leaf=is_named_array) chilled_args.append(chilled_arg) mapped_axis = jax.tree_util.tree_map(_index_of_axis, chilled_arg, is_leaf=_is_chill_array) mapped_axes.append(mapped_axis) def wrapped_fn(*args): - unchilled_args = jax.tree_util.tree_map( - partial(_unchill_named_arrays, axis), args, is_leaf=_named_array_leaf - ) + unchilled_args = jax.tree_util.tree_map(partial(_unchill_named_arrays, axis), args, is_leaf=is_named_array) r = fn(*unchilled_args) - chilled = jax.tree_util.tree_map(_chill_named_arrays, r, is_leaf=_named_array_leaf) + chilled = jax.tree_util.tree_map(_chill_named_arrays, r, is_leaf=is_named_array) return chilled result = jax.vmap(wrapped_fn, in_axes=mapped_axes, out_axes=0, axis_size=axis.size)(*args) diff --git a/src/haliax/partitioning.py b/src/haliax/partitioning.py new file mode 100644 index 0000000..5c7e4dc --- /dev/null +++ b/src/haliax/partitioning.py @@ -0,0 +1,84 @@ +import contextlib +import threading +from typing import List, Mapping, Optional, Sequence, TypeVar, Union + +import jax +from equinox import is_array +from equinox.custom_types import PyTree +from jax.experimental import pjit +from jax.interpreters.pxla import PartitionSpec + +from .core import NamedArray +from .util import ensure_tuple, is_named_array + + +LogicalAxisName = str +PhysicalAxis = str +PhysicalAxisSpec = Union[PhysicalAxis, Sequence[PhysicalAxis]] +ResourceMapping = Mapping[LogicalAxisName, PhysicalAxisSpec] +"""Mapping from logical axis names to physical axis names""" + + +class _ResourceMappingHolder: + """Global resource mapping, used with a context manager to give dynamic scoping to resource mappings""" + + def __init__(self): + self.thread_data = threading.local() + self.thread_data.resource_mapping = None + + +_mapping_holder = _ResourceMappingHolder() + + +@contextlib.contextmanager +def resource_mapping(mapping: ResourceMapping, **kwargs): + """Context manager for setting the global resource mapping""" + if len(kwargs): + mapping = dict(mapping) + mapping.update(kwargs) + + old_mapping = _mapping_holder.thread_data.resource_mapping + _mapping_holder.thread_data.resource_mapping = mapping + yield + _mapping_holder.thread_data.resource_mapping = old_mapping + + +T = TypeVar("T", bound=PyTree) + + +def logically_sharded(x: T, logical_axes: Optional[PyTree] = None) -> T: + """ + Shard a PyTree using the global resource mapping. NamedArrays in the PyTree are sharded using the resource mapping + and the names in the tree. Non-NamedArrays are sharded using the logical_axes argument, if provided. + + If there is no global resource mapping, this function is a no-op. + """ + mapping = _mapping_holder.thread_data.resource_mapping + + if mapping is None: + return x + + def _as_pspec(x, logical_axis=None): + if isinstance(x, NamedArray): + physical_names: List[Optional[PhysicalAxisSpec]] = [mapping.get(a.name, None) for a in x.axes] + elif logical_axis is not None: + physical_names: List[Optional[PhysicalAxisSpec]] = [ + mapping.get(a, None) for a in ensure_tuple(logical_axis) + ] + elif is_array(x): + physical_names = [None] * len(x.shape) + else: + return None + + spec = PartitionSpec( + *tuple(tuple(p) if not (isinstance(p, str)) and isinstance(p, Sequence) else p for p in physical_names) + ) + return spec + + if logical_axes is None: + # TODO: support logical_axes as a tree prefix. jax doesn't seem to have a good utility for this. + pspec = jax.tree_util.tree_map(_as_pspec, x, is_leaf=is_named_array) + else: + pspec = jax.tree_util.tree_map(_as_pspec, x, logical_axes, is_leaf=is_named_array) + + return pjit.with_sharding_constraint(x, pspec) diff --git a/src/haliax/random.py b/src/haliax/random.py index 773ade8..75d0ee1 100644 --- a/src/haliax/random.py +++ b/src/haliax/random.py @@ -5,7 +5,8 @@ import functools import jax.random as jrandom # TODO: handle broadcasting of array args to random functions (e.g. minval and maxval for uniform) -from haliax.core import Axis, AxisSpec, NamedArray, _ensure_tuple +from haliax.core import Axis, AxisSpec, NamedArray +from haliax.util import ensure_tuple def _wrap_random_function(func): @@ -16,7 +17,7 @@ def _wrap_random_function(func): if isinstance(shape, Axis): return NamedArray(func(key, shape.size, *args, **kwargs), (shape,)) else: - shape = _ensure_tuple(shape) + shape = ensure_tuple(shape) lens = [ax.size for ax in shape] return NamedArray(func(key, lens, *args, **kwargs), shape) diff --git a/src/haliax/util.py b/src/haliax/util.py new file mode 100644 index 0000000..c437482 --- /dev/null +++ b/src/haliax/util.py @@ -0,0 +1,17 @@ +from typing import Sequence, Tuple, TypeVar, Union + + +T = TypeVar("T") + + +def is_named_array(leaf): + from .core import NamedArray + + "Typically used as the is_leaf predicate in tree_map" + return isinstance(leaf, NamedArray) + + +def ensure_tuple(x: Union[Sequence[T], T]) -> Tuple[T, ...]: + if isinstance(x, Sequence): + return tuple(x) + return (x,) diff --git a/src/haliax/wrap.py b/src/haliax/wrap.py index 9a9df32..f113add 100644 --- a/src/haliax/wrap.py +++ b/src/haliax/wrap.py @@ -3,7 +3,8 @@ from typing import Optional import jax.numpy as jnp -from haliax.core import AxisSpec, NamedArray, _ensure_tuple +from haliax.core import AxisSpec, NamedArray +from haliax.util import ensure_tuple def wrap_elemwise_unary(f): @@ -35,7 +36,7 @@ def wrap_reduction_call(fn): else: return NamedArray(result, ()) else: - axis = _ensure_tuple(axis) + axis = ensure_tuple(axis) indices = a.lookup_indices(axis) if indices is None or any(x is None for x in indices): raise ValueError(f"axis {axis} is not in {a.axes}") @@ -66,7 +67,7 @@ def wrap_normalization_call(fn, single_axis_only: bool): if axis is None: return NamedArray(fn(a.array, axis=None, **kwargs), ()) else: - indices = _ensure_tuple(a.lookup_indices(axis)) + indices = ensure_tuple(a.lookup_indices(axis)) if any(x is None for x in indices): raise ValueError(f"axis {axis} is not in {a.axes}") if len(indices) == 1: commit 9fd6a491317aae38275532ef9d52cbc59f2e98d4 Date: 2022-08-27T12:57:29-07:00 try a different approach to unbind diff --git a/src/haliax/core.py b/src/haliax/core.py index 6cb28e0..7606a1f 100644 --- a/src/haliax/core.py +++ b/src/haliax/core.py @@ -480,8 +480,11 @@ def unbind(array: NamedArray, axis: Axis) -> List[NamedArray]: axis_index = array.lookup_indices(axis) if axis_index is None: raise ValueError(f"axis {axis} not found in {array}") - arrays = jnp.rollaxis(array.array, axis=axis_index, start=0) new_axes = array.axes[:axis_index] + array.axes[axis_index + 1 :] + # this implementation maybe triggers an all-gather in pjit so no good + # arrays = jnp.rollaxis(array.array, axis=axis_index, start=0) + # instead we just loop over the axes pulling one out at a time + arrays = [jnp.take(array.array, i, axis=axis_index) for i in range(axis.size)] return [NamedArray(a, new_axes) for a in arrays] diff --git a/src/haliax/partitioning.py b/src/haliax/partitioning.py index 5c7e4dc..242bd96 100644 --- a/src/haliax/partitioning.py +++ b/src/haliax/partitioning.py @@ -81,4 +81,6 @@ def logically_sharded(x: T, logical_axes: Optional[PyTree] = None) -> T: else: pspec = jax.tree_util.tree_map(_as_pspec, x, logical_axes, is_leaf=is_named_array) + print(x, pspec) + return pjit.with_sharding_constraint(x, pspec) commit 2215b472b3598c3d2682461710733ce065f64b4e Date: 2022-08-27T23:04:37-07:00 added test for vmap diff --git a/src/haliax/hof.py b/src/haliax/hof.py index 60dd1e5..448279b 100644 --- a/src/haliax/hof.py +++ b/src/haliax/hof.py @@ -138,14 +138,13 @@ def fold_left( return carry -# TODO: add test for vmap def vmap( fn, axis: Axis, unmapped_argnums: Union[int, Sequence[int]] = (), ): """ - NamedArray aware version of jax.vmap. + NamedArray aware version of jax.vmap. Normal arrays are mapped over the 0th axis. unmapped_argnums are the argnums of the function that are not batched over the axis. """ unmmapped_argnums = ensure_tuple(unmapped_argnums) @@ -159,6 +158,8 @@ def vmap( return None # TODO: do fancier things with kwargs and signature and such + # TODO: allow specifying spmd axis name and/or inferring it from resource_mapping + # TODO: allow other axes to be mapped over # TODO: maybe implement equinox-style filtering vmap @wraps(fn) def wrapped_vmap_fn(*args): commit a7cd5112d092240189de648980ab52292c2dd81e Date: 2022-08-29T19:37:13+00:00 something diff --git a/src/haliax/partitioning.py b/src/haliax/partitioning.py index 242bd96..cce5cbf 100644 --- a/src/haliax/partitioning.py +++ b/src/haliax/partitioning.py @@ -82,5 +82,4 @@ def logically_sharded(x: T, logical_axes: Optional[PyTree] = None) -> T: pspec = jax.tree_util.tree_map(_as_pspec, x, logical_axes, is_leaf=is_named_array) print(x, pspec) - return pjit.with_sharding_constraint(x, pspec) commit e648cdb323385ef749487603d7d81e7b67d7fd6a Date: 2022-08-29T22:45:55+00:00 Merge branch 'main' of github.com:stanford-crfm/levanter into main commit 41879dc65f645c401bb5e6a7614435d5847a8f02 Date: 2022-08-30T23:03:40-07:00 rename fold_left to reduce, unify the reduce call in gpt2 diff --git a/src/haliax/__init__.py b/src/haliax/__init__.py index 457445b..08b9bca 100644 --- a/src/haliax/__init__.py +++ b/src/haliax/__init__.py @@ -17,7 +17,7 @@ from .core import ( unbind, unflatten_axis, ) -from .hof import fold_left, scan, vmap +from .hof import reduce, scan, vmap from .wrap import wrap_elemwise_unary, wrap_normalization_call, wrap_reduction_call @@ -240,6 +240,6 @@ __all__ = [ "cumprod", "cumproduct", "scan", - "fold_left", + "reduce", "vmap", ] diff --git a/src/haliax/hof.py b/src/haliax/hof.py index 448279b..e4d5664 100644 --- a/src/haliax/hof.py +++ b/src/haliax/hof.py @@ -103,7 +103,7 @@ def _ensure_first(axis, leaf): return leaf -def fold_left( +def reduce( fn: Callable[[Carry, X], Carry], axis: Axis, init: Carry, xs: X, reverse: bool = False, unroll: int = 1 ) -> Carry: """ @@ -190,4 +190,4 @@ def vmap( return wrapped_vmap_fn -__all__ = ["scan", "fold_left", "vmap"] +__all__ = ["scan", "reduce", "vmap"] commit f8c6fae2d1978e321c2c8cacaa7deedd71f55bc6 Date: 2022-08-30T23:10:39-07:00 clarify and cleanup diff --git a/src/haliax/hof.py b/src/haliax/hof.py index e4d5664..83cb352 100644 --- a/src/haliax/hof.py +++ b/src/haliax/hof.py @@ -44,7 +44,7 @@ def scan(f: Callable[[Carry, X], Tuple[Carry, Y]], axis: Axis, init: Carry, xs: """ # This implementation is a bit tricky. - # First we have to hoist the axis we're scanning over to the front of the array. + # First we have to hoist the axis we're scanning over to the front of the array, because that's what scan expects. # Then we have to scan over the 0th dim of the arrays (as flattened non-pytrees) # We have to be careful that we don't try to create NamedArrays that have the shape of the scanned result # but don't yet have the scanned axis as ones of `axes`, so we use _ScannedArrayResult that doesn't check @@ -52,7 +52,7 @@ def scan(f: Callable[[Carry, X], Tuple[Carry, Y]], axis: Axis, init: Carry, xs: axis_first_xs = jax.tree_util.tree_map(partial(_ensure_first, axis), xs, is_leaf=is_named_array) - # now get a template for where we fold over the axis in question + # now get a template of an element of "X" x_elem = jax.tree_util.tree_map(partial(_select_0th, axis), axis_first_xs, is_leaf=is_named_array) x_elem_structure = jax.tree_util.tree_structure(x_elem) @@ -149,7 +149,7 @@ def vmap( """ unmmapped_argnums = ensure_tuple(unmapped_argnums) - def _index_of_axis(array): + def _index_of_batch_axis(array): if isinstance(array, NamedArray): return array.axes.index(axis) elif equinox.is_array(array): @@ -174,7 +174,7 @@ def vmap( else: chilled_arg = jax.tree_util.tree_map(_chill_named_arrays, arg, is_leaf=is_named_array) chilled_args.append(chilled_arg) - mapped_axis = jax.tree_util.tree_map(_index_of_axis, chilled_arg, is_leaf=_is_chill_array) + mapped_axis = jax.tree_util.tree_map(_index_of_batch_axis, chilled_arg, is_leaf=_is_chill_array) mapped_axes.append(mapped_axis) def wrapped_fn(*args): commit f4e3929b92dbbd0fae39701ecbf1459f6ca9e4c9 Date: 2022-08-31T10:45:58-07:00 fix type annotations for hax diff --git a/src/haliax/core.py b/src/haliax/core.py index 7606a1f..56582b8 100644 --- a/src/haliax/core.py +++ b/src/haliax/core.py @@ -233,7 +233,7 @@ class NamedArray: def unbind(self, axis: Axis) -> Sequence["NamedArray"]: return haliax.unbind(self, axis=axis) - def rename(self, renames: Mapping[Axis, Axis]): + def rename(self, renames: Mapping[Axis, Axis]) -> "NamedArray": return haliax.rename(self, renames=renames) # def squeeze(self, axis: Optional[AxisSpec] = None) -> Any: @@ -248,7 +248,7 @@ class NamedArray: keepdims=False, *, where=None, - ) -> Any: + ) -> "NamedArray": return haliax.std( self, axis=axis, @@ -267,7 +267,7 @@ class NamedArray: keepdims=None, initial=None, where=None, - ) -> Any: + ) -> "NamedArray": return haliax.sum( self, axis=axis, @@ -278,7 +278,7 @@ class NamedArray: where=where, ) - def take(self, axis: Axis, index: Union[int, "NamedArray"]) -> Any: + def take(self, axis: Axis, index: Union[int, "NamedArray"]) -> "NamedArray": return haliax.take(self, axis=axis, index=index) def tobytes(self, order="C") -> Any: commit e80168f6df2e392eea7e77161eb33d115cf2aae1 Date: 2022-08-31T16:37:24-07:00 fix dependency breakage diff --git a/requirements.txt b/requirements.txt index 982043e..47b40f2 100644 --- a/requirements.txt +++ b/requirements.txt @@ -7,7 +7,7 @@ pyrallis pyarrow zstandard datasets -fsspec gcsfs braceexpand git+https://github.com/deepmind/jmp#260e5ba01f46b10c579a61393e6c7e546aeae93e +fsspec==2022.7.1 # pin this to make gcsfs happy commit 06d5a8cde31e11c9296a97097f0f54c2cc0dc2a9 Date: 2022-09-06T15:38:11-07:00 Haliax (#23) Lots of improvements to Haliax: binary broadcast ops, a few nn modules, bug fixes inter alia diff --git a/src/haliax/__init__.py b/src/haliax/__init__.py index 08b9bca..a4267c8 100644 --- a/src/haliax/__init__.py +++ b/src/haliax/__init__.py @@ -1,11 +1,15 @@ +import jax import jax.numpy as jnp import haliax.random as random +from haliax import nn as nn from .core import ( Axis, AxisSpec, NamedArray, + broadcast_axis, + broadcast_to, concat_axis_specs, dot, flatten_axes, @@ -18,7 +22,8 @@ from .core import ( unflatten_axis, ) from .hof import reduce, scan, vmap -from .wrap import wrap_elemwise_unary, wrap_normalization_call, wrap_reduction_call +from .ops import trace, where +from .wrap import wrap_axiswise_call, wrap_elemwise_binary, wrap_elemwise_unary, wrap_reduction_call # creation routines @@ -56,8 +61,10 @@ def full_like(a: NamedArray, fill_value, dtype=None) -> NamedArray: return NamedArray(jnp.full_like(a.array, fill_value, dtype=dtype), a.axes) -def arange(axis: Axis, dtype=None) -> NamedArray: - return NamedArray(jnp.arange(axis.size, dtype=dtype), (axis,)) +def arange(axis: Axis, *, start=0, step=1, dtype=None) -> NamedArray: + """Version of jnp.arange that returns a NamedArray""" + stop = start + axis.size * step + return NamedArray(jnp.arange(start, stop, step, dtype=dtype), (axis,)) # elementwise unary operations @@ -90,6 +97,7 @@ floor = wrap_elemwise_unary(jnp.floor) frexp = wrap_elemwise_unary(jnp.frexp) i0 = wrap_elemwise_unary(jnp.i0) imag = wrap_elemwise_unary(jnp.imag) +invert = wrap_elemwise_unary(jnp.invert) iscomplex = wrap_elemwise_unary(jnp.iscomplex) isfinite = wrap_elemwise_unary(jnp.isfinite) isinf = wrap_elemwise_unary(jnp.isinf) @@ -111,6 +119,7 @@ real = wrap_elemwise_unary(jnp.real) reciprocal = wrap_elemwise_unary(jnp.reciprocal) rint = wrap_elemwise_unary(jnp.rint) round = wrap_elemwise_unary(jnp.round) +rsqrt = wrap_elemwise_unary(jax.lax.rsqrt) # nb this is in lax sign = wrap_elemwise_unary(jnp.sign) signbit = wrap_elemwise_unary(jnp.signbit) sin = wrap_elemwise_unary(jnp.sin) @@ -132,6 +141,7 @@ max = wrap_reduction_call(jnp.max) mean = wrap_reduction_call(jnp.mean) min = wrap_reduction_call(jnp.min) prod = wrap_reduction_call(jnp.prod) +ptp = wrap_reduction_call(jnp.ptp) product = wrap_reduction_call(jnp.product) sometrue = wrap_reduction_call(jnp.sometrue) std = wrap_reduction_call(jnp.std) @@ -139,14 +149,55 @@ sum = wrap_reduction_call(jnp.sum) var = wrap_reduction_call(jnp.var) # "Normalization" functions that use an axis but don't change the shape -cumsum = wrap_normalization_call(jnp.cumsum, True) -cumprod = wrap_normalization_call(jnp.cumprod, True) -cumproduct = wrap_normalization_call(jnp.cumproduct, True) +cumsum = wrap_axiswise_call(jnp.cumsum, True) +cumprod = wrap_axiswise_call(jnp.cumprod, True) +cumproduct = wrap_axiswise_call(jnp.cumproduct, True) +sort = wrap_axiswise_call(jnp.sort, True) + +# elemwise binary ops +add = wrap_elemwise_binary(jnp.add) +arctan2 = wrap_elemwise_binary(jnp.arctan2) +bitwise_and = wrap_elemwise_binary(jnp.bitwise_and) +bitwise_or = wrap_elemwise_binary(jnp.bitwise_or) +bitwise_xor = wrap_elemwise_binary(jnp.bitwise_xor) +divide = wrap_elemwise_binary(jnp.divide) +divmod = wrap_elemwise_binary(jnp.divmod) +equal = wrap_elemwise_binary(jnp.equal) +float_power = wrap_elemwise_binary(jnp.float_power) +floor_divide = wrap_elemwise_binary(jnp.floor_divide) +fmax = wrap_elemwise_binary(jnp.fmax) +fmin = wrap_elemwise_binary(jnp.fmin) +fmod = wrap_elemwise_binary(jnp.fmod) +greater = wrap_elemwise_binary(jnp.greater) +greater_equal = wrap_elemwise_binary(jnp.greater_equal) +hypot = wrap_elemwise_binary(jnp.hypot) +left_shift = wrap_elemwise_binary(jnp.left_shift) +less = wrap_elemwise_binary(jnp.less) +less_equal = wrap_elemwise_binary(jnp.less_equal) +logaddexp = wrap_elemwise_binary(jnp.logaddexp) +logaddexp2 = wrap_elemwise_binary(jnp.logaddexp2) +logical_and = wrap_elemwise_binary(jnp.logical_and) +logical_or = wrap_elemwise_binary(jnp.logical_or) +logical_xor = wrap_elemwise_binary(jnp.logical_xor) +maximum = wrap_elemwise_binary(jnp.maximum) +minimum = wrap_elemwise_binary(jnp.minimum) +mod = wrap_elemwise_binary(jnp.mod) +multiply = wrap_elemwise_binary(jnp.multiply) +nextafter = wrap_elemwise_binary(jnp.nextafter) +not_equal = wrap_elemwise_binary(jnp.not_equal) +power = wrap_elemwise_binary(jnp.power) +remainder = wrap_elemwise_binary(jnp.remainder) +right_shift = wrap_elemwise_binary(jnp.right_shift) +subtract = wrap_elemwise_binary(jnp.subtract) +true_divide = wrap_elemwise_binary(jnp.true_divide) + __all__ = [ "Axis", "NamedArray", "AxisSpec", + "broadcast_to", + "broadcast_axis", "named", "dot", "split", @@ -213,6 +264,7 @@ __all__ = [ "real", "reciprocal", "rint", + "rsqrt", "round", "sign", "signbit", @@ -232,6 +284,7 @@ __all__ = [ "min", "prod", "product", + "ptp", "sometrue", "std", "sum", @@ -239,7 +292,45 @@ __all__ = [ "cumsum", "cumprod", "cumproduct", + "sort", "scan", "reduce", "vmap", + "trace", + "where", + "add", + "arctan2", + "bitwise_and", + "bitwise_or", + "bitwise_xor", + "divide", + "divmod", + "equal", + "float_power", + "floor_divide", + "fmax", + "fmin", + "fmod", + "greater", + "greater_equal", + "hypot", + "left_shift", + "less", + "less_equal", + "logaddexp", + "logaddexp2", + "logical_and", + "logical_or", + "logical_xor", + "maximum", + "minimum", + "mod", + "multiply", + "nextafter", + "not_equal", + "power", + "remainder", + "right_shift", + "subtract", + "true_divide", ] diff --git a/src/haliax/core.py b/src/haliax/core.py index 56582b8..5649ea5 100644 --- a/src/haliax/core.py +++ b/src/haliax/core.py @@ -1,3 +1,4 @@ +import functools as ft from dataclasses import dataclass from math import prod from types import EllipsisType @@ -33,6 +34,12 @@ class NamedArray: def __post_init__(self): if not isinstance(self.axes, tuple): object.__setattr__(self, "axes", tuple(self.axes)) + # ensure axes are all Axis objects + # TODO: anonymous positional axes? + for axis in self.axes: + if not isinstance(axis, Axis): + raise TypeError(f"Expected Axis, got {type(axis)}") + # ensure unique axes for now if len(set(a.name for a in self.axes)) != len(self.axes): raise ValueError(f"Axes must be unique, but {self.axes} are not") @@ -59,7 +66,7 @@ class NamedArray: assert len(tree) == 1 return cls(tree[0], axes=aux) - def lookup_indices(self, axis: AxisSpec): + def _lookup_indices(self, axis: AxisSpec): """ For a single axis, returns an int corresponding to the index of the axis. For multiple axes, returns a tuple of ints corresponding to the indices of the axes. @@ -72,27 +79,53 @@ class NamedArray: except ValueError: return None else: - return tuple(self.lookup_indices(a) for a in axis) + return tuple(self._lookup_indices(a) for a in axis) - def rearrange(self, axis: Sequence[Union[Axis, EllipsisType]]): + # Axis rearrangement + def rearrange(self, axis: Sequence[Union[Axis, EllipsisType]]) -> "NamedArray": return rearrange(self, axis) + def broadcast_to(self, axes: AxisSpec) -> "NamedArray": + axes = ensure_tuple(axes) + return haliax.broadcast_to(self, axes=axes) + + def broadcast_axis(self, axis: AxisSpec) -> "NamedArray": + return haliax.broadcast_axis(self, axis=axis) + + def split(self, axis: Axis, new_axes: Sequence[Axis]) -> Sequence["NamedArray"]: + return haliax.split(self, axis=axis, new_axes=new_axes) + + def flatten_axes(self, old_axes: Sequence[Axis], new_axis: Axis) -> "NamedArray": + return haliax.flatten_axes(self, old_axes=old_axes, new_axis=new_axis) + + def unflatten_axis(self, axis: Axis, new_axes: Sequence[Axis]) -> "NamedArray": + return haliax.unflatten_axis(self, axis=axis, new_axes=new_axes) + + def unbind(self, axis: Axis) -> Sequence["NamedArray"]: + return haliax.unbind(self, axis=axis) + + def rename(self, renames: Mapping[Axis, Axis]) -> "NamedArray": + return haliax.rename(self, renames=renames) + + def take(self, axis: Axis, index: Union[int, "NamedArray"]) -> "NamedArray": + return haliax.take(self, axis=axis, index=index) + # np.ndarray methods: - def all(self, axis: Optional[AxisSpec] = None, out=None, keepdims=None) -> Any: - return haliax.all(self, axis=axis, out=out, keepdims=keepdims) + def all(self, axis: Optional[AxisSpec] = None, *, keepdims=None) -> "NamedArray": + return haliax.all(self, axis=axis, keepdims=keepdims) - def any(self, axis: Optional[AxisSpec] = None, out=None, keepdims=None) -> Any: - return haliax.any(self, axis=axis, out=out, keepdims=keepdims) + def any(self, axis: Optional[AxisSpec] = None, *, keepdims=None) -> "NamedArray": + return haliax.any(self, axis=axis, keepdims=keepdims) # def select(self, axis: Axis, index: Union[int, 'NamedArray', jnp.ndarray]) -> Any: # if isinstance(index, NamedArray): # index = index.array # TODO - # def argmax(self, axis: Optional[int] = None, out=None, keepdims=None) -> Any: + # def argmax(self, axis: Optional[int] = None, keepdims=None) -> Any: # ... # - # def argmin(self, axis: Optional[int] = None, out=None, keepdims=None) -> Any: + # def argmin(self, axis: Optional[int] = None, keepdims=None) -> Any: # ... # # def argpartition(self, kth, axis=-1, kind='introselect', order=None) -> Any: @@ -101,75 +134,70 @@ class NamedArray: # def argsort(self, axis: Optional[int] = -1, kind='quicksort', order=None) -> Any: # ... - def astype(self, dtype) -> Any: + def astype(self, dtype) -> "NamedArray": return NamedArray(self.array.astype(dtype), self.axes) # TODO - # def clip(self, a_min=None, a_max=None, out=None) -> Any: + # def clip(self, a_min=None, a_max=None) -> Any: # ... - # def compress(self, condition, axis: Optional[int] = None, out=None) -> Any: + # def compress(self, condition, axis: Optional[int] = None) -> Any: # ... - def conj(self) -> Any: + def conj(self) -> "NamedArray": return NamedArray(self.array.conj(), self.axes) - def conjugate(self) -> Any: + def conjugate(self) -> "NamedArray": return NamedArray(self.array.conjugate(), self.axes) - def copy(self) -> Any: + def copy(self) -> "NamedArray": return NamedArray(self.array.copy(), self.axes) - def cumprod(self, axis: Optional[AxisSpec] = None, dtype=None, out=None) -> Any: - return haliax.cumprod(self, axis=axis, dtype=dtype, out=out) + def cumprod(self, axis: Optional[AxisSpec] = None, *, dtype=None) -> "NamedArray": + return haliax.cumprod(self, axis=axis, dtype=dtype) - def cumsum(self, axis: Optional[AxisSpec] = None, dtype=None, out=None) -> Any: - return haliax.cumsum(self, axis=axis, dtype=dtype, out=out) + def cumsum(self, axis: Optional[AxisSpec] = None, *, dtype=None) -> "NamedArray": + return haliax.cumsum(self, axis=axis, dtype=dtype) # def diagonal(self, offset=0, axis1: int = 0, axis2: int = 1) -> Any: # ... - def dot(self, axis: AxisSpec, b, *, precision=None) -> Any: + def dot(self, axis: AxisSpec, b, *, precision=None) -> "NamedArray": return dot(axis, self, b, precision=precision) @property - def imag(self) -> Any: + def imag(self) -> "NamedArray": return NamedArray(self.array.imag, self.axes) - # TODO: - # def item(self, *args) -> Any: - # - def max( self, axis: Optional[AxisSpec] = None, - out=None, + *, keepdims=None, initial=None, where=None, - ) -> Any: - return haliax.max(self, axis=axis, out=out, keepdims=keepdims, initial=initial, where=where) + ) -> "NamedArray": + return haliax.max(self, axis=axis, keepdims=keepdims, initial=initial, where=where) def mean( self, axis: Optional[AxisSpec] = None, + *, dtype=None, - out=None, keepdims=False, - *, where=None, - ) -> Any: - return haliax.mean(self, axis=axis, dtype=dtype, out=out, keepdims=keepdims, where=where) + ) -> "NamedArray": + return haliax.mean(self, axis=axis, dtype=dtype, keepdims=keepdims, where=where) def min( self, axis: Optional[AxisSpec] = None, - out=None, + *, keepdims=None, initial=None, where=None, - ) -> Any: - return haliax.min(self, axis=axis, out=out, keepdims=keepdims, initial=initial, where=where) + ) -> "NamedArray": + return haliax.min(self, axis=axis, keepdims=keepdims, initial=initial, where=where) # TODO # def nonzero(self, *, size=None, fill_value=None) -> Any: @@ -178,82 +206,58 @@ class NamedArray: def prod( self, axis: Optional[AxisSpec] = None, + *, dtype=None, - out=None, keepdims=None, initial=None, where=None, - ): + ) -> "NamedArray": return haliax.prod( self, axis=axis, dtype=dtype, - out=out, keepdims=keepdims, initial=initial, where=where, ) - # def ptp(self, axis: Optional[Union[int, Tuple[int, ...]]] = None, out=None, - # keepdims=False, ) -> Any: - # ... + def ptp(self, axis: AxisSpec = None) -> "NamedArray": + return haliax.ptp(self, axis=axis) + # TODO: implement ravel. Can only do if we either ask for an axis or add ProductAxis or something # def ravel(self, order='C') -> Any: # ... @property - def real(self) -> Any: + def real(self) -> "NamedArray": return NamedArray(self.array.real, self.axes) - # def repeat(self, repeats, axis: Optional[int] = None, *, - # total_repeat_length=None) -> Any: - # ... - + # TODO: what should reshape look like? # def reshape(self, *args, order='C') -> Any: # ... - def round(self, decimals=0, out=None) -> Any: - return haliax.round(self, decimals=decimals, out=out) + def round(self, decimals=0) -> "NamedArray": + return haliax.round(self, decimals=decimals) # def searchsorted(self, v, side='left', sorter=None) -> Any: # ... - # def sort(self, axis: Optional[int] = -1, kind='quicksort', order=None) -> Any: - # ... - - def split(self, axis: Axis, new_axes: Sequence[Axis]) -> Sequence["NamedArray"]: - return haliax.split(self, axis=axis, new_axes=new_axes) - - def flatten_axes(self, old_axes: Sequence[Axis], new_axis: Axis) -> "NamedArray": - return haliax.flatten_axes(self, old_axes=old_axes, new_axis=new_axis) - - def unflatten_axis(self, axis: Axis, new_axes: Sequence[Axis]) -> "NamedArray": - return haliax.unflatten_axis(self, axis=axis, new_axes=new_axes) - - def unbind(self, axis: Axis) -> Sequence["NamedArray"]: - return haliax.unbind(self, axis=axis) - - def rename(self, renames: Mapping[Axis, Axis]) -> "NamedArray": - return haliax.rename(self, renames=renames) - - # def squeeze(self, axis: Optional[AxisSpec] = None) -> Any: - # return haliax.squeeze(self, axis=axis) + def sort(self, axis: Axis, kind="quicksort") -> Any: + return haliax.sort(self, axis=axis, kind=kind) def std( self, axis: Optional[AxisSpec] = None, + *, dtype=None, - out=None, ddof=0, keepdims=False, - *, where=None, ) -> "NamedArray": return haliax.std( self, axis=axis, dtype=dtype, - out=out, ddof=ddof, keepdims=keepdims, where=where, @@ -262,8 +266,8 @@ class NamedArray: def sum( self, axis: Optional[AxisSpec] = None, + *, dtype=None, - out=None, keepdims=None, initial=None, where=None, @@ -272,76 +276,179 @@ class NamedArray: self, axis=axis, dtype=dtype, - out=out, keepdims=keepdims, initial=initial, where=where, ) - def take(self, axis: Axis, index: Union[int, "NamedArray"]) -> "NamedArray": - return haliax.take(self, axis=axis, index=index) - def tobytes(self, order="C") -> Any: return self.array.tobytes(order=order) def tolist(self) -> Any: return self.array.tolist() - # def trace(self, offset=0, axis1: int = 0, axis2: int = 1, dtype=None, - # out=None) -> Any: + def trace(self, axis1: Axis, axis2: Axis, offset=0, dtype=None) -> "NamedArray": + return haliax.trace(self, offset=offset, axis1=axis1, axis2=axis2, dtype=dtype) def var( self, axis: Optional[AxisSpec] = None, dtype=None, - out=None, ddof=0, keepdims=False, *, where=None, - ) -> Any: + ) -> "NamedArray": return haliax.var( self, axis=axis, dtype=dtype, - out=out, ddof=ddof, keepdims=keepdims, where=where, ) # operators - def __add__(self, other) -> Any: - # TODO: check shape and broadcast - raise NotImplementedError - def __mul__(self, other): - if jnp.isscalar(other): - return NamedArray(self.array * other, self.axes) + # Comparisons + def __lt__(self, other) -> "NamedArray": + return haliax.less(self, other) + + def __le__(self, other) -> "NamedArray": + return haliax.less_equal(self, other) + + def __eq__(self, other): + return haliax.equal(self, other) + + def __ne__(self, other): + return haliax.not_equal(self, other) + + def __gt__(self, other) -> "NamedArray": + return haliax.greater(self, other) + + def __ge__(self, other) -> "NamedArray": + return haliax.greater_equal(self, other) - raise NotImplementedError + # Unary arithmetic - def __rmul__(self, other): - return self.__mul__(other) + def __neg__(self) -> "NamedArray": + return haliax.negative(self) - def __truediv__(self, other): - if jnp.isscalar(other): - return NamedArray(self.array / other, self.axes) + def __pos__(self) -> "NamedArray": + return haliax.positive(self) - raise NotImplementedError + def __abs__(self) -> "NamedArray": + return haliax.absolute(self) - def __rtruediv__(self, other): - if jnp.isscalar(other): - return NamedArray(other / self.array, self.axes) + def __invert__(self) -> "NamedArray": + return haliax.invert(self) - raise NotImplementedError + # Binary arithmetic + + def __add__(self, other) -> "NamedArray": + return haliax.add(self, other) + + def __sub__(self, other) -> "NamedArray": + return haliax.subtract(self, other) + + def __mul__(self, other) -> "NamedArray": + return haliax.multiply(self, other) + + def __matmul__(self, other) -> "NamedArray": + raise ValueError("matmul is too ambiguous with NamedArrays. Use dot instead.") + + def __truediv__(self, other) -> "NamedArray": + return haliax.true_divide(self, other) + + def __floordiv__(self, other) -> "NamedArray": + return haliax.floor_divide(self, other) + + def __mod__(self, other) -> "NamedArray": + return haliax.mod(self, other) + + def __divmod__(self, other) -> "NamedArray": + return haliax.divmod(self, other) + + def __pow__(self, other) -> "NamedArray": + return haliax.power(self, other) + + def __lshift__(self, other) -> "NamedArray": + return haliax.left_shift(self, other) + + def __rshift__(self, other) -> "NamedArray": + return haliax.right_shift(self, other) + + def __and__(self, other) -> "NamedArray": + return haliax.bitwise_and(self, other) + + def __xor__(self, other) -> "NamedArray": + return haliax.bitwise_xor(self, other) + + def __or__(self, other) -> "NamedArray": + return haliax.bitwise_or(self, other) + + def __radd__(self, other) -> "NamedArray": + return haliax.add(other, self) + + def __rsub__(self, other) -> "NamedArray": + return haliax.subtract(other, self) + + def __rmul__(self, other) -> "NamedArray": + return haliax.multiply(other, self) + + def __rmatmul__(self, other): + raise ValueError("Matrix multiplication is too ambiguous with NamedArrays. Use dot instead.") + + def __rtruediv__(self, other) -> "NamedArray": + return haliax.true_divide(other, self) + + def __rfloordiv__(self, other) -> "NamedArray": + return haliax.floor_divide(other, self) + + def __rmod__(self, other) -> "NamedArray": + return haliax.mod(other, self) + + def __rdivmod__(self, other) -> "NamedArray": + return haliax.divmod(other, self) + + def __rpow__(self, other) -> "NamedArray": + return haliax.power(other, self) + + def __rlshift__(self, other) -> "NamedArray": + return haliax.left_shift(other, self) + + def __rrshift__(self, other) -> "NamedArray": + return haliax.right_shift(other, self) + + def __rand__(self, other) -> "NamedArray": + return haliax.bitwise_and(other, self) + + def __rxor__(self, other) -> "NamedArray": + return haliax.bitwise_xor(other, self) + + def __ror__(self, other) -> "NamedArray": + return haliax.bitwise_or(other, self) + + def __bool__(self) -> bool: + return bool(self.array) + + def __complex__(self) -> complex: + return complex(self.array) + + def __int__(self) -> int: + return int(self.array) + + def __float__(self) -> float: + return float(self.array) def take(array: NamedArray, axis: Axis, index: Union[int, NamedArray]) -> NamedArray: """ Selects elements from an array along an axis, by an index or by another named array + + if index is a NamedArray, then those axes are added to the output array """ - axis_index = array.lookup_indices(axis) + axis_index = array._lookup_indices(axis) if axis_index is None: raise ValueError(f"axis {axis} not found in {array}") if isinstance(index, int): @@ -402,7 +509,7 @@ def split(a: NamedArray, axis: Axis, new_axes: Sequence[Axis]) -> Sequence[Named if total_len != axis.size: raise ValueError(f"The total length of the new axes {total_len} does not match the length of the axis {axis}") - index = a.lookup_indices(axis) + index = a._lookup_indices(axis) # now we can split the array offsets = np.cumsum([0] + [x.size for x in new_axes])[1:-1] @@ -451,7 +558,7 @@ def rearrange(array: NamedArray, axes: Sequence[Union[Axis, EllipsisType]]): ellipsis_pos = len(permute_spec) - 1 else: assert isinstance(ax, Axis) # please mypy - index = array.lookup_indices(ax) + index = array._lookup_indices(ax) if index is None: raise ValueError(f"Axis {ax} not found in {array}") if used_indices[index]: @@ -477,7 +584,7 @@ def unbind(array: NamedArray, axis: Axis) -> List[NamedArray]: """ Unbind an array along an axis, returning a list of NamedArrays. Analogous to torch.unbind or np.rollaxis """ - axis_index = array.lookup_indices(axis) + axis_index = array._lookup_indices(axis) if axis_index is None: raise ValueError(f"axis {axis} not found in {array}") new_axes = array.axes[:axis_index] + array.axes[axis_index + 1 :] @@ -518,7 +625,7 @@ def unflatten_axis(array: NamedArray, axis: Axis, new_axes: Sequence[Axis]) -> N """ Split an axis into a sequence of axes. The old axis must have the same size as the product of the new axes. """ - old_index = array.lookup_indices(axis) + old_index = array._lookup_indices(axis) if old_index is None: raise ValueError(f"Axis {axis} not found in {array}") @@ -569,6 +676,126 @@ def concat_axis_specs(a1: AxisSpec, a2: AxisSpec) -> AxisSpec: return a1 + a2 +# Broadcasting Support +def _broadcast_order(a: NamedArray, b: NamedArray, require_subset: bool = True) -> Tuple[Axis, ...]: + """ + Returns an ordering of axes for broadcasting a and b. + + If require_subset is True, then one of the array's axes must be a subset of the other's. This requirement is + a bit stricter than a straightforward generalization of numpy's broadcasting rules, but I've been bitten by + numpy's rules too many times. + """ + broadcasted = _broadcast_axes(a.axes, b.axes, require_subset) + if broadcasted is None: + # TODO: decide under which conditions we want to allow broadcasting both arrays + # maybe just add a context manager to allow it? + raise ValueError( + f"Cannot broadcast {a} and {b}: no subset relationship. " + "If you want to broadcast anyway, use the broadcast_axis function to explicitly add axes" + ) + return broadcasted + + +def _broadcast_axes( + a_axes: Tuple[Axis, ...], b_axes: Tuple[Axis, ...], require_subset: bool = True +) -> Optional[Tuple[Axis, ...]]: + if a_axes == b_axes: + return a_axes + if len(a_axes) == 0: + return b_axes + if len(b_axes) == 0: + return a_axes + + if require_subset: + # check if one is a subset of the other + if set(a_axes).issubset(set(b_axes)): + return b_axes + elif set(b_axes).issubset(set(a_axes)): + return a_axes + else: + return None + + a_size = prod(ax.size for ax in a_axes) + b_size = prod(ax.size for ax in b_axes) + if a_size < b_size: + a_axes, b_axes = b_axes, a_axes + + # we want to order the axes in such a way that we minimize movement, or at least allow + # large blocks to be memcpy'd when possible. + # In particular, we'd like to avoid the case of reordering [Y, Z] + [X, Y, Z] -> [Y, Z, X] or other major reshuffles + + # here's what we do: we try to preserve the order of axes in the bigger array, and then stick the axes from the + # other array on the front (because everything is row major) + # this ensures we only have to move one array around + + return tuple(x for x in b_axes if x not in a_axes) + a_axes + + +def broadcast_to(a: NamedArray, axes: Tuple[Axis, ...], ensure_order: bool = True) -> NamedArray: + """ + Broadcasts a to the given axes. If ensure_order is True (default), then the returned array will have the same axes + in the same order as the given axes. Otherwise, the axes may not be moved + """ + if a.axes == axes: + return a + + to_add = tuple(ax for ax in axes if ax not in a.axes) + + # broadcast whatever we need to the front and reorder + a_array = jnp.broadcast_to(a.array, [ax.size for ax in to_add] + [ax.size for ax in a.axes]) + a = NamedArray(a_array, to_add + a.axes) + + if ensure_order: + a = rearrange(a, axes) + + return a + + +def broadcast_arrays( + *arrays: NamedArray, require_subset: bool = True, ensure_order: bool = True +) -> Tuple[NamedArray, ...]: + """ + Broadcasts a sequence of arrays to a common set of axes. + + Parameters + ---------- + arrays: NamedArray + The arrays to broadcast + require_subset: bool + If True, then one of the arrays must be a subset of the other. This is a bit stricter than numpy's broadcasting + rules, but I've been bitten by numpy's rules too many times. If False is looser than numpy's rules, and allows + broadcasting any pair of arrays (so long as the axes don't overtly conflict with different sizes for the same + name.) + ensure_order: bool + If True, then the returned arrays will have the same axes in the same order as the given axes. Otherwise, the + axes may not be moved. + """ + if len(arrays) == 0: + return () + + # sort the arrays by size, so that we use the biggest ones to broadcast the others + # need to hold on to the order so we can return the arrays in the same order + size_order = sorted(range(len(arrays)), key=lambda i: arrays[i].size, reverse=True) + all_axes = [arrays[i].axes for i in size_order] + full_axes = ft.reduce(lambda a, b: _broadcast_axes(a, b, require_subset) if a is not None else None, all_axes) # type: ignore + if full_axes is None: + raise ValueError(f"Cannot broadcast arrays {arrays}: no subset relationship") + + return tuple(broadcast_to(a, full_axes, ensure_order=ensure_order) for a in arrays) + + +def broadcast_axis(a: NamedArray, axis: AxisSpec) -> NamedArray: + """ + Broadcasts a, ensuring that it has all the axes in axis + """ + if isinstance(axis, Axis) and axis in a.axes: + return a + + axis = ensure_tuple(axis) + new_axes = tuple(ax for ax in axis if ax not in a.axes) + return broadcast_to(a, new_axes + a.axes) + + __all__ = [ "Axis", "AxisSpec", @@ -582,4 +809,8 @@ __all__ = [ "flatten_axes", "unflatten_axis", "unbind", + "_broadcast_order", + "broadcast_to", + "broadcast_axis", + "broadcast_arrays", ] diff --git a/src/haliax/nn.py b/src/haliax/nn/__init__.py similarity index 56% rename from src/haliax/nn.py rename to src/haliax/nn/__init__.py index 400204b..f619769 100644 --- a/src/haliax/nn.py +++ b/src/haliax/nn/__init__.py @@ -1,6 +1,13 @@ +import functools + import jax.nn as jnn +import jax.numpy as jnp -from .wrap import wrap_elemwise_unary, wrap_normalization_call, wrap_reduction_call +from ..core import Axis, NamedArray +from ..wrap import wrap_axiswise_call, wrap_elemwise_unary, wrap_reduction_call +from .dropout import Dropout +from .linear import Linear +from .normalization import LayerNorm relu = wrap_elemwise_unary(jnn.relu) @@ -20,11 +27,20 @@ elu = wrap_elemwise_unary(jnn.elu) celu = wrap_elemwise_unary(jnn.celu) selu = wrap_elemwise_unary(jnn.selu) gelu = wrap_elemwise_unary(jnn.gelu) +# TODO: glu = wrap_elemwise_unary(jnn.gelu) logsumexp = wrap_reduction_call(jnn.logsumexp) -softmax = wrap_normalization_call(jnn.softmax, False) -log_softmax = wrap_normalization_call(jnn.log_softmax, False) +softmax = wrap_axiswise_call(jnn.softmax, False) +# TODO: standardize has optional "mean" and "variance" arguments we need to support +# standardize = wrap_normalization_call(jnn.standardize, False) +log_softmax = wrap_axiswise_call(jnn.log_softmax, False) + + +@functools.wraps(jnn.one_hot) +def one_hot(x: NamedArray, class_axis: Axis, *, dtype=jnp.float_) -> NamedArray: + array = jnn.one_hot(x.array, num_classes=class_axis.size, dtype=dtype) + return NamedArray(array, x.axes + (class_axis,)) __all__ = [ @@ -48,4 +64,8 @@ __all__ = [ "logsumexp", "softmax", "log_softmax", + "one_hot", + "Dropout", + "LayerNorm", + "Linear", ] diff --git a/src/haliax/nn/dropout.py b/src/haliax/nn/dropout.py new file mode 100644 index 0000000..26537ea --- /dev/null +++ b/src/haliax/nn/dropout.py @@ -0,0 +1,72 @@ +from typing import Optional + +import equinox as eqx +import jax + +import haliax +from haliax.core import AxisSpec, NamedArray +from haliax.util import ensure_tuple + + +class Dropout(eqx.Module): + """Applies dropout. + + Attributes: + pdrop: The fraction of entries to set to zero. + broadcast_axes: The dimensions to broadcast the dropout mask over. If set, these axes will share the same mask + """ + + # key difference from equinox: these are static fields + pdrop: float = eqx.static_field() + broadcast_axes: Optional[AxisSpec] = eqx.static_field() + + def __init__( + self, + pdrop: float = 0.5, + broadcast_axes: Optional[AxisSpec] = None, + ): + self.pdrop = pdrop + self.broadcast_axes = broadcast_axes + + def __call__( + self, + x: NamedArray, + *, + inference: bool, + key: Optional["jax.random.PRNGKey"] = None, + ) -> NamedArray: + """**Arguments:** + + - `x`: An any-dimensional JAX array to dropout. + - `key`: A `jax.random.PRNGKey` used to provide randomness for calculating + which elements to dropout. (Keyword only argument.) + - `inference`: As per [`equinox.nn.Dropout.__init__`][]. If `True` or + `False` then it will take priority over `self.inference`. If `None` + then the value from `self.inference` will be used. + - `deterministic`: Deprecated alternative to `inference`. + """ + + if isinstance(self.pdrop, (int, float)) and self.pdrop == 0: + return x + elif self.pdrop == 1: + return haliax.zeros_like(x) + elif inference: + return x + elif key is None: + raise RuntimeError("Dropout requires a key when running in non-deterministic mode.") + else: + with jax.named_scope(name="dropout"): + + if self.broadcast_axes is None: + shape_to_generate = x.axes + else: + axes = ensure_tuple(self.broadcast_axes) + shape_to_generate = tuple(ax for ax in x.axes if ax not in axes) + + q = 1 - self.pdrop + q = x.dtype.type(q) + mask = haliax.random.bernoulli(key, q, shape_to_generate) + + out = haliax.where(mask, x / q, haliax.zeros_like(x)) # type: ignore + assert out.dtype == x.dtype + return out diff --git a/src/haliax/nn/linear.py b/src/haliax/nn/linear.py new file mode 100644 index 0000000..0db07aa --- /dev/null +++ b/src/haliax/nn/linear.py @@ -0,0 +1,40 @@ +from typing import Optional + +import equinox as eqx +import jax +import jmp + +import haliax as hax + +from ..core import AxisSpec, NamedArray + + +class Linear(eqx.Module): + """A named Linear layer. This module allows you to specify multiple named axes for both input + and output, which is occasionally useful.""" + + weight: NamedArray + bias: Optional[NamedArray] + + In: AxisSpec = eqx.static_field() + Out: AxisSpec = eqx.static_field() + mp: jmp.Policy = eqx.static_field() + + def __init__(self, In: AxisSpec, Out: AxisSpec, *, key, mp: jmp.Policy, include_bias=True): + joint_spec = hax.concat_axis_specs(In, Out) + self.weight = hax.random.normal(key, joint_spec, dtype=mp.param_dtype) * 0.02 + self.bias = hax.zeros(Out, dtype=mp.param_dtype) if include_bias else None + + self.In = In + self.Out = Out + self.mp = mp + + @jax.named_scope(name="linear") + def __call__(self, inputs): + q = inputs.dot(self.In, self.weight) + q = self.mp.cast_to_compute(q) + + if self.bias is not None: + q = q + self.bias + + return q diff --git a/src/haliax/nn/normalization.py b/src/haliax/nn/normalization.py new file mode 100644 index 0000000..7645bed --- /dev/null +++ b/src/haliax/nn/normalization.py @@ -0,0 +1,37 @@ +from typing import Optional + +import equinox as eqx + +import haliax as hax + +from ..core import AxisSpec, NamedArray + + +class LayerNorm(eqx.Module): + r""" + Normalises the input along the specified axis (or axes), using the mean and variance of the + input along that axis. This is equivalent to the following code: + """ + axis: AxisSpec = eqx.static_field() + eps: float = eqx.static_field() + + weight: Optional[NamedArray] + bias: Optional[NamedArray] + + def __init__(self, axis: AxisSpec, eps: float = 1e-5, elementwise_affine: bool = True): + self.axis = axis + self.eps = eps + + if elementwise_affine: + self.weight = hax.ones(axis) + self.bias = hax.zeros(axis) + + def __call__(self, x: NamedArray) -> NamedArray: + mean = x.mean(self.axis) + var = x.var(self.axis) + inv = hax.rsqrt(var + self.eps) + out = (x - mean) * inv + + if self.weight is not None: + out = self.weight * out + self.bias + return out diff --git a/src/haliax/ops.py b/src/haliax/ops.py new file mode 100644 index 0000000..d1deb87 --- /dev/null +++ b/src/haliax/ops.py @@ -0,0 +1,54 @@ +from typing import Union + +import jax +import jax.numpy as jnp + +import haliax + +from .core import Axis, NamedArray, broadcast_arrays + + +def trace(array: NamedArray, axis1: Axis, axis2: Axis, offset=0, dtype=None) -> NamedArray: + """Compute the trace of an array along two named axes.""" + a1_index = array._lookup_indices(axis1) + a2_index = array._lookup_indices(axis2) + + if a1_index is None: + raise ValueError(f"Axis {axis1} not found in array. Available axes: {array.axes}") + if a2_index is None: + raise ValueError(f"Axis {axis2} not found in array. Available axes: {array.axes}") + + if a1_index == a2_index: + raise ValueError(f"Cannot trace along the same axis. Got {axis1} and {axis2}") + + inner = jnp.trace(array.array, offset=offset, axis1=a1_index, axis2=a2_index, dtype=dtype) + # remove the two indices + axes = tuple(a for i, a in enumerate(array.axes) if i not in (a1_index, a2_index)) + return NamedArray(inner, axes) + + +def where(condition: Union[NamedArray, bool], x: NamedArray, y: NamedArray) -> NamedArray: + """Like jnp.where, but with named axes. This version currently only accepts the three argument form.""" + + # TODO: support the one argument form + # if (x is None) != (y is None): + # raise ValueError("Must either specify both x and y, or neither") + + if jnp.isscalar(condition): + if x is None: + raise ValueError("Must specify x and y when condition is a scalar") + return jax.lax.cond(condition, lambda _: x, lambda _: y, None) + + assert isinstance(condition, NamedArray) + + if jnp.isscalar(x): + x = haliax.full_like(condition, x) + + if jnp.isscalar(y): + y = haliax.full_like(condition, y) + + condition, x, y = broadcast_arrays(condition, x, y) + return NamedArray(jnp.where(condition.array, x.array, y.array), condition.axes) + + +__all__ = ["trace", "where"] diff --git a/src/haliax/random.py b/src/haliax/random.py index 75d0ee1..06f6fe0 100644 --- a/src/haliax/random.py +++ b/src/haliax/random.py @@ -1,11 +1,13 @@ """Wrappers around jax.random functions.""" import functools +import inspect +from typing import Sequence import jax.random as jrandom # TODO: handle broadcasting of array args to random functions (e.g. minval and maxval for uniform) -from haliax.core import Axis, AxisSpec, NamedArray +from haliax.core import Axis, NamedArray from haliax.util import ensure_tuple @@ -13,14 +15,26 @@ def _wrap_random_function(func): """Wrap a jax random function to return a NamedArray and takes axes as inputs""" @functools.wraps(func) - def wrapper(key: jrandom.KeyArray, shape: AxisSpec, *args, **kwargs): - if isinstance(shape, Axis): - return NamedArray(func(key, shape.size, *args, **kwargs), (shape,)) + def wrapper(key: jrandom.KeyArray, *args, **kwargs): + sig: inspect.BoundArguments = inspect.signature(func).bind(key, *args, **kwargs) + sig.apply_defaults() + + # get shape + orig_shape = sig.arguments["shape"] + orig_shape = ensure_tuple(orig_shape) + if isinstance(orig_shape, Sequence): + is_haliax = len(orig_shape) == 0 or any(isinstance(s, Axis) for s in orig_shape) + shape = tuple(axis.size if isinstance(axis, Axis) else axis for axis in orig_shape) else: - shape = ensure_tuple(shape) - lens = [ax.size for ax in shape] + is_haliax = False + + if is_haliax: + sig.arguments["shape"] = shape - return NamedArray(func(key, lens, *args, **kwargs), shape) + # now invoke + out = func(**sig.arguments) + if is_haliax: + return NamedArray(out, orig_shape) return wrapper diff --git a/src/haliax/wrap.py b/src/haliax/wrap.py index f113add..f849349 100644 --- a/src/haliax/wrap.py +++ b/src/haliax/wrap.py @@ -3,7 +3,7 @@ from typing import Optional import jax.numpy as jnp -from haliax.core import AxisSpec, NamedArray +from haliax.core import AxisSpec, NamedArray, _broadcast_order, broadcast_to from haliax.util import ensure_tuple @@ -37,7 +37,7 @@ def wrap_reduction_call(fn): return NamedArray(result, ()) else: axis = ensure_tuple(axis) - indices = a.lookup_indices(axis) + indices = a._lookup_indices(axis) if indices is None or any(x is None for x in indices): raise ValueError(f"axis {axis} is not in {a.axes}") new_axes = a.axes if keepdims else [ax for ax in a.axes if ax not in axis] @@ -60,14 +60,14 @@ def wrap_reduction_call(fn): return wrapper -def wrap_normalization_call(fn, single_axis_only: bool): +def wrap_axiswise_call(fn, single_axis_only: bool): @functools.wraps(fn) def wrapper(a, axis: Optional[AxisSpec] = None, **kwargs): if isinstance(a, NamedArray): if axis is None: - return NamedArray(fn(a.array, axis=None, **kwargs), ()) + return NamedArray(fn(a.array, axis=None, **kwargs), a.axes) else: - indices = ensure_tuple(a.lookup_indices(axis)) + indices = ensure_tuple(a._lookup_indices(axis)) if any(x is None for x in indices): raise ValueError(f"axis {axis} is not in {a.axes}") if len(indices) == 1: @@ -82,7 +82,7 @@ def wrap_normalization_call(fn, single_axis_only: bool): wrapper.__doc__ = ( """ - This function augments the behavior of `{fn}` to support NamedArrays, so that axis is a NamedArray. + This function augments the behavior of `{fn}` to support NamedArrays, so that axis is an Axis of sequence of axes. At the moment, neither `where` nor `out` are supported. ===== @@ -92,4 +92,22 @@ def wrap_normalization_call(fn, single_axis_only: bool): return wrapper -__all__ = ["wrap_elemwise_unary", "wrap_reduction_call", "wrap_normalization_call"] +def wrap_elemwise_binary(op): + @functools.wraps(op) + def binop(a, b): + if isinstance(a, NamedArray) and isinstance(b, NamedArray): + axes = _broadcast_order(a, b) + a = broadcast_to(a, axes) + b = broadcast_to(b, axes) + return NamedArray(op(a.array, b.array), axes) + elif isinstance(a, NamedArray) and jnp.isscalar(b): + return NamedArray(op(a.array, b), a.axes) + elif isinstance(b, NamedArray) and jnp.isscalar(a): + return NamedArray(op(a, b.array), b.axes) + else: + return op(a, b) + + return binop + + +__all__ = ["wrap_elemwise_unary", "wrap_reduction_call", "wrap_axiswise_call", "wrap_elemwise_binary"] diff --git a/tests/core_test.py b/tests/core_test.py new file mode 100644 index 0000000..e8ec387 --- /dev/null +++ b/tests/core_test.py @@ -0,0 +1,230 @@ +import jax +import jax.numpy as jnp +import pytest +from jax.random import PRNGKey + +import haliax as hax +from haliax import Axis, NamedArray + + +def test_dot(): + Height = Axis("Height", 2) + Width = Axis("Width", 3) + Depth = Axis("Depth", 4) + + m1 = NamedArray(jnp.ones((Height.size, Width.size, Depth.size)), (Height, Width, Depth)) + m2 = NamedArray(jnp.ones((Depth.size, Width.size, Height.size)), (Depth, Width, Height)) + + assert jnp.all(jnp.equal(hax.dot(Height, m1, m2).array, jnp.einsum("ijk,kji->jk", m1.array, m2.array))) + assert jnp.all( + jnp.equal( + hax.dot((Height, Width), m1, m2).array, + jnp.einsum("ijk,kji->k", m1.array, m2.array), + ) + ) + assert jnp.all( + jnp.equal( + hax.dot((Height, Width, Depth), m1, m2).array, + jnp.einsum("ijk,kji->", m1.array, m2.array), + ) + ) + + +def test_unary_np_functions(): + Height = Axis("Height", 2) + Width = Axis("Width", 3) + Depth = Axis("Depth", 4) + + m1 = NamedArray(jnp.ones((Height.size, Width.size, Depth.size)), (Height, Width, Depth)) + + assert jnp.all(jnp.equal(hax.abs(m1).array, jnp.abs(m1.array))) + assert jnp.all(jnp.equal(hax.absolute(m1).array, jnp.absolute(m1.array))) + assert jnp.all(jnp.equal(hax.angle(m1).array, jnp.angle(m1.array))) + assert jnp.all(jnp.equal(hax.arccos(m1).array, jnp.arccos(m1.array))) + assert jnp.all(jnp.equal(hax.arccosh(m1).array, jnp.arccosh(m1.array))) + assert jnp.all(jnp.equal(hax.arcsin(m1).array, jnp.arcsin(m1.array))) + assert jnp.all(jnp.equal(hax.arcsinh(m1).array, jnp.arcsinh(m1.array))) + assert jnp.all(jnp.equal(hax.arctan(m1).array, jnp.arctan(m1.array))) + assert jnp.all(jnp.equal(hax.arctanh(m1).array, jnp.arctanh(m1.array))) + assert jnp.all(jnp.equal(hax.around(m1).array, jnp.around(m1.array))) + assert jnp.all(jnp.equal(hax.cbrt(m1).array, jnp.cbrt(m1.array))) + + +def test_reduction_functions(): + Height = Axis("Height", 2) + Width = Axis("Width", 3) + Depth = Axis("Depth", 4) + + rand_m = jax.random.uniform(PRNGKey(0), (Height.size, Width.size, Depth.size)) + + m1 = NamedArray(rand_m, (Height, Width, Depth)) + + # sum out everything + assert jnp.all(jnp.equal(hax.sum(m1).array, jnp.sum(m1.array))) + # ensure it's a scalar + + assert jnp.all(jnp.equal(hax.sum(m1, axis=Height).array, jnp.sum(m1.array, axis=0))) + assert jnp.all(jnp.equal(hax.sum(m1, axis=Width).array, jnp.sum(m1.array, axis=1))) + + # sum out two axes + assert jnp.all(jnp.equal(hax.sum(m1, axis=(Height, Width)).array, jnp.sum(m1.array, axis=(0, 1)))) + assert jnp.all(jnp.equal(hax.sum(m1, axis=(Width, Height)).array, jnp.sum(m1.array, axis=(1, 0)))) + assert jnp.all(jnp.equal(hax.sum(m1, axis=(Height, Depth)).array, jnp.sum(m1.array, axis=(0, 2)))) + + # sum out three axes + assert jnp.all( + jnp.equal( + hax.sum(m1, axis=(Height, Width, Depth)).array, + jnp.sum(m1.array, axis=(0, 1, 2)), + ) + ) + assert jnp.all( + jnp.equal( + hax.sum(m1, axis=(Width, Height, Depth)).array, + jnp.sum(m1.array, axis=(1, 0, 2)), + ) + ) + + +def test_split(): + Height = Axis("Height", 2) + Width = Axis("Width", 3) + Depth = Axis("Depth", 4) + + D10 = Axis("Depth", Depth.size * 10) + + rand_m = hax.random.uniform(PRNGKey(0), (Height, Width, D10)) + m = rand_m.array + + splits = hax.split(rand_m, axis=D10, new_axes=[Depth] * 10) + + assert splits[0].axes == (Height, Width, Depth) + assert len(splits) == 10 + + usplits = jnp.split(m, 10, axis=2) + + for i in range(10): + assert jnp.all(jnp.equal(splits[i].array, usplits[i])) + + +def test_take(): + Height = Axis("Height", 2) + Width = Axis("Width", 3) + Depth = Axis("Depth", 4) + named1 = hax.random.uniform(PRNGKey(0), (Height, Width, Depth)) + + assert jnp.all(jnp.equal(hax.take(named1, Height, 0).array, named1.array[0])) + + Index = Axis("Index", 5) + indices = hax.ones(Index, dtype=jnp.int32) + + named2 = hax.take(named1, Height, indices) + assert named2.axes == (Index, Width, Depth) + + named2 = hax.take(named1, Width, indices) + assert named2.axes == (Height, Index, Depth) + + named2 = hax.take(named1, Depth, indices) + assert named2.axes == (Height, Width, Index) + + Index2 = Axis("Index2", 3) + + indices2 = hax.ones((Index, Index2), dtype=jnp.int32) + + named2 = hax.take(named1, Height, indices2) + assert named2.axes == (Index, Index2, Width, Depth) + + named2 = hax.take(named1, Width, indices2) + assert named2.axes == (Height, Index, Index2, Depth) + + named2 = hax.take(named1, Depth, indices2) + assert named2.axes == (Height, Width, Index, Index2) + + +def test_cumsum_etc(): + Height = Axis("Height", 2) + Width = Axis("Width", 3) + Depth = Axis("Depth", 4) + + named1 = hax.random.uniform(PRNGKey(0), (Height, Width, Depth)) + + assert jnp.all(jnp.equal(hax.cumsum(named1, axis=Height).array, jnp.cumsum(named1.array, axis=0))) + assert hax.cumsum(named1, axis=Height).axes == (Height, Width, Depth) + + assert jnp.all(jnp.equal(hax.cumsum(named1, axis=Width).array, jnp.cumsum(named1.array, axis=1))) + assert hax.cumsum(named1, axis=Width).axes == (Height, Width, Depth) + + assert jnp.all(jnp.equal(hax.cumsum(named1, axis=Depth).array, jnp.cumsum(named1.array, axis=2))) + assert hax.cumsum(named1, axis=Depth).axes == (Height, Width, Depth) + + assert jnp.all(jnp.equal(hax.cumprod(named1, axis=Height).array, jnp.cumprod(named1.array, axis=0))) + assert hax.cumprod(named1, axis=Height).axes == (Height, Width, Depth) + + assert jnp.all(jnp.equal(hax.cumprod(named1, axis=Width).array, jnp.cumprod(named1.array, axis=1))) + assert hax.cumprod(named1, axis=Width).axes == (Height, Width, Depth) + + assert jnp.all(jnp.equal(hax.cumprod(named1, axis=Depth).array, jnp.cumprod(named1.array, axis=2))) + assert hax.cumprod(named1, axis=Depth).axes == (Height, Width, Depth) + + +def test_rearrange(): + H = Axis("Height", 2) + W = Axis("Width", 3) + D = Axis("Depth", 4) + C = Axis("Channel", 5) + + named1 = hax.random.uniform(PRNGKey(0), (H, W, D, C)) + + assert jnp.all(jnp.equal(hax.rearrange(named1, (C, W, D, H)).array, jnp.transpose(named1.array, (3, 1, 2, 0)))) + assert hax.rearrange(named1, (C, W, D, H)).axes == (C, W, D, H) + + # test ellipsis + assert jnp.all(jnp.equal(hax.rearrange(named1, (C, ..., D)).array, jnp.transpose(named1.array, (3, 0, 1, 2)))) + + # test errors for double ellipsis + with pytest.raises(ValueError): + hax.rearrange(named1, (C, ..., ...)) + + # test errors for multiply specified axes + with pytest.raises(ValueError): + hax.rearrange(named1, (C, W, W, H)) + + # test errors for unknown axes + with pytest.raises(ValueError): + X = Axis("X", 6) + hax.rearrange(named1, (C, X, D, H)) + + # test for missing axes + with pytest.raises(ValueError): + hax.rearrange(named1, (C, W, D)) + + +def test_rearrange_unused_ellipsis(): + # Make sure we just ignore the ellipsis if all axes are specified in addition + H = Axis("Height", 2) + W = Axis("Width", 3) + D = Axis("Depth", 4) + + named1 = hax.random.uniform(PRNGKey(0), (H, W, D)) + + assert jnp.all(jnp.equal(hax.rearrange(named1, (H, W, D, ...)).array, named1.array)) + assert hax.rearrange(named1, (H, W, D, ...)).axes == (H, W, D) + + assert jnp.all(jnp.equal(hax.rearrange(named1, (H, ..., W, D)).array, named1.array)) + assert hax.rearrange(named1, (H, ..., W, D)).axes == (H, W, D) + + assert jnp.all(jnp.equal(hax.rearrange(named1, (D, ..., W, H)).array, jnp.transpose(named1.array, (2, 1, 0)))) + assert hax.rearrange(named1, (D, ..., W, H)).axes == (D, W, H) + + +def test_arange(): + H = Axis("Height", 10) + + assert jnp.all(jnp.equal(hax.arange(H).array, jnp.arange(10))) + assert hax.arange(H).axes == (H,) + + # test stride + assert jnp.all(jnp.equal(hax.arange(H, step=2).array, jnp.arange(0, 20, 2))) + + # test start and stride + assert jnp.all(jnp.equal(hax.arange(H, start=2, step=2).array, jnp.arange(2, 22, 2))) diff --git a/tests/test_hof.py b/tests/test_hof.py new file mode 100644 index 0000000..b054aca --- /dev/null +++ b/tests/test_hof.py @@ -0,0 +1,71 @@ +import jax.numpy as jnp +from jax.random import PRNGKey + +import haliax as hax +from haliax import Axis, NamedArray + + +def test_scan(): + Height = Axis("Height", 10) + Width = Axis("Width", 3) + Depth = Axis("Depth", 4) + named1 = hax.random.uniform(PRNGKey(0), (Height, Width, Depth)) + + def scan_fun(acc, x): + return acc + jnp.sum(x.array), x.take(Width, 2) + + total, selected = hax.scan(scan_fun, Height, 0.0, named1) + + assert jnp.all(jnp.isclose(total, jnp.sum(named1.array, axis=(0, 1, 2)))) + assert jnp.all(jnp.equal(selected.array, named1.take(Width, 2).array)) + + +def test_scan_not_0th_axis(): + Height = Axis("Height", 10) + Width = Axis("Width", 3) + Depth = Axis("Depth", 4) + named1 = hax.random.uniform(PRNGKey(0), (Height, Width, Depth)) + + def scan_fun(acc, x): + return acc + jnp.sum(x.array), x.take(Width, 2) + + total, selected = hax.scan(scan_fun, Depth, 0.0, named1) + + assert jnp.all(jnp.isclose(total, jnp.sum(named1.array, axis=(0, 1, 2)))) + assert jnp.all(jnp.equal(selected.array, named1.take(Width, 2).rearrange(selected.axes).array)) + + +def test_reduce(): + + Height = Axis("Height", 10) + Width = Axis("Width", 3) + Depth = Axis("Depth", 4) + named1 = hax.random.uniform(PRNGKey(0), (Height, Width, Depth)) + + def fold_fun(acc, x): + # TODO: implement binary ops! + return NamedArray(acc.array + x.rearrange(acc.axes).array, acc.axes) + + acc = hax.zeros((Height, Width)) + + total = hax.reduce(fold_fun, Depth, acc, named1) + + assert jnp.all(jnp.isclose(total.rearrange(acc.axes).array, jnp.sum(named1.array, axis=2))) + + +def test_vmap(): + Batch = Axis("Batch", 10) + Width = Axis("Width", 3) + Depth = Axis("Depth", 4) + named1 = hax.random.uniform(PRNGKey(0), (Width, Depth)) + + def vmap_fun(x): + return x.take(Width, 2) + + selected = hax.vmap(vmap_fun, Batch)(named1) + + expected_jax = jnp.array([named1.take(Width, 2).array for _ in range(Batch.size)]) + expected_names = (Batch, Depth) + + assert jnp.all(jnp.equal(selected.array, expected_jax)) + assert selected.axes == expected_names diff --git a/tests/test_nn.py b/tests/test_nn.py new file mode 100644 index 0000000..b460e60 --- /dev/null +++ b/tests/test_nn.py @@ -0,0 +1,64 @@ +import equinox as eqx +import jax.random as jrandom +from jax import numpy as jnp + +import haliax as hax +from haliax import Axis, NamedArray + + +def _compare_eqx_and_haliax(hax_mod: eqx.Module, eqx_mod: eqx.Module): + def f(x: NamedArray, *args, **kwargs): + unnamed_x = x.array + hax_out = hax_mod(x, *args, **kwargs) # type: ignore + eqx_out = eqx_mod(unnamed_x, *args, **kwargs) # type: ignore + + assert jnp.allclose(hax_out.array, eqx_out) + return hax_out + + return f + + +def test_layer_norm(): + H = hax.Axis("H", 10) + hax_ln = hax.nn.LayerNorm(H) + eqx_ln = eqx.nn.LayerNorm(shape=(H.size,)) + + f = _compare_eqx_and_haliax(hax_ln, eqx_ln) + out = f(hax.random.uniform(jrandom.PRNGKey(0), (H,))) + + assert out.axes == (H,) + + +def test_dropout(): + H = hax.Axis("H", 10) + key = jrandom.PRNGKey(0) + hax_dropout = hax.nn.Dropout(0.5) + eqx_dropout = eqx.nn.Dropout(0.5) + + f = _compare_eqx_and_haliax(hax_dropout, eqx_dropout) + out = f(hax.random.uniform(jrandom.PRNGKey(0), (H,)), key=key, inference=False) + + assert out.axes == (H,) + + +def test_one_hot(): + i = Axis("i", 3) + c = Axis("c", 3) + actual = hax.nn.one_hot(hax.NamedArray(jnp.array([0, 1, 2]), (i,)), c) + expected = jnp.array([[1.0, 0.0, 0.0], [0.0, 1.0, 0.0], [0.0, 0.0, 1.0]]) + + assert actual.axes == (i, c) + assert jnp.all(jnp.isclose(actual.array, expected)) + + actual = hax.nn.one_hot(hax.NamedArray(jnp.array([1, 2, 0]), (i,)), c) + expected = jnp.array([[0.0, 1.0, 0.0], [0.0, 0.0, 1.0], [1.0, 0.0, 0.0]]) + assert actual.axes == (i, c) + assert jnp.all(jnp.isclose(actual.array, expected)) + + +def test_one_hot_out_of_bound(): + i = Axis("i", 2) + c = Axis("c", 3) + actual = hax.nn.one_hot(hax.NamedArray(jnp.array([-1, 3]), (i,)), c) + expected = jnp.array([[0.0, 0.0, 0.0], [0.0, 0.0, 0.0]]) + assert jnp.all(jnp.isclose(actual.array, expected)) diff --git a/tests/test_ops.py b/tests/test_ops.py new file mode 100644 index 0000000..85d7a4f --- /dev/null +++ b/tests/test_ops.py @@ -0,0 +1,111 @@ +import jax.numpy as jnp +import pytest +from jax.random import PRNGKey + +import haliax as hax +from haliax import Axis + + +def test_trace(): + Width = Axis("Width", 3) + Depth = Axis("Depth", 4) + named1 = hax.random.uniform(PRNGKey(0), (Width, Depth)) + trace1 = hax.trace(named1, Width, Depth) + assert jnp.all(jnp.isclose(trace1.array, jnp.trace(named1.array))) + assert len(trace1.axes) == 0 + + Height = Axis("Height", 10) + named2 = hax.random.uniform(PRNGKey(0), (Height, Width, Depth)) + trace2 = hax.trace(named2, Width, Depth) + assert jnp.all(jnp.isclose(trace2.array, jnp.trace(named2.array, axis1=1, axis2=2))) + assert trace2.axes == (Height,) + + +def test_add(): + Height = Axis("Height", 10) + Width = Axis("Width", 3) + Depth = Axis("Depth", 4) + + named1 = hax.random.uniform(PRNGKey(0), (Height, Width, Depth)) + named2 = hax.random.uniform(PRNGKey(1), (Height, Width, Depth)) + + named3 = named1 + named2 + assert jnp.all(jnp.isclose(named3.array, named1.array + named2.array)) + + named2_reorder = named2.rearrange((Width, Height, Depth)) + named4 = named1 + named2_reorder + named4 = named4.rearrange((Height, Width, Depth)) + assert jnp.all(jnp.isclose(named4.array, named1.array + named2.array)) + + +def test_add_broadcasting(): + Height = Axis("Height", 10) + Width = Axis("Width", 3) + Depth = Axis("Depth", 4) + + named1 = hax.random.uniform(PRNGKey(0), (Height, Width, Depth)) + named2 = hax.random.uniform(PRNGKey(1), (Width, Depth)) + + named3 = named1 + named2 + assert jnp.all(jnp.isclose(named3.array, named1.array + named2.array)) + + named2_reorder = named2.rearrange((Depth, Width)) + named4 = named1 + named2_reorder + named4 = named4.rearrange((Height, Width, Depth)) + + assert jnp.all(jnp.isclose(named4.array, named1.array + named2.array)) + + # now for the broadcasting we don't like + named5 = hax.random.uniform(PRNGKey(1), (Height, Depth)) + named6 = hax.random.uniform(PRNGKey(2), (Width, Depth)) + + with pytest.raises(ValueError): + _ = named5 + named6 + + +def test_add_scalar(): + Height = Axis("Height", 10) + Width = Axis("Width", 3) + Depth = Axis("Depth", 4) + + named1 = hax.random.uniform(PRNGKey(0), (Height, Width, Depth)) + named2 = named1 + 1.0 + assert jnp.all(jnp.isclose(named2.array, named1.array + 1.0)) + + named3 = 1.0 + named1 + assert jnp.all(jnp.isclose(named3.array, named1.array + 1.0)) + + +# TODO: tests for other ops + + +def test_where(): + Height = Axis("Height", 10) + Width = Axis("Width", 3) + Depth = Axis("Depth", 4) + + named1 = hax.random.uniform(PRNGKey(0), (Height, Width, Depth)) + named2 = hax.random.uniform(PRNGKey(1), (Height, Width, Depth)) + + named3 = hax.where(named1 > named2, named1, named2) + assert jnp.all(jnp.isclose(named3.array, jnp.where(named1.array > named2.array, named1.array, named2.array))) + + named2_reorder = named2.rearrange((Width, Height, Depth)) + named4 = hax.where(named1 > named2_reorder, named1, named2_reorder) + named4 = named4.rearrange((Height, Width, Depth)) + assert jnp.all(jnp.isclose(named4.array, jnp.where(named1.array > named2.array, named1.array, named2.array))) + + # now some broadcasting + named5 = hax.random.uniform(PRNGKey(1), (Height, Width)) + named6 = hax.random.uniform(PRNGKey(2), Width) + + named7 = hax.where(named5 > named6, named5, named6) + named7 = named7.rearrange((Height, Width)) + assert jnp.all(jnp.isclose(named7.array, jnp.where(named5.array > named6.array, named5.array, named6.array))) + + # now for the broadcasting we don't like + named5 = hax.random.uniform(PRNGKey(1), (Height, Depth)) + named6 = hax.random.uniform(PRNGKey(2), (Width, Depth)) + + with pytest.raises(ValueError): + _ = hax.where(named5 > named6, named5, named6) commit e10432f78a491b796b48908b51d265d05dd111a6 Date: 2022-09-07T14:50:26-07:00 forgot to check dropout first diff --git a/src/haliax/nn/dropout.py b/src/haliax/nn/dropout.py index 26537ea..6253c8a 100644 --- a/src/haliax/nn/dropout.py +++ b/src/haliax/nn/dropout.py @@ -58,7 +58,10 @@ class Dropout(eqx.Module): with jax.named_scope(name="dropout"): if self.broadcast_axes is None: - shape_to_generate = x.axes + if isinstance(x, NamedArray): + shape_to_generate = x.axes + else: + shape_to_generate = x.shape else: axes = ensure_tuple(self.broadcast_axes) shape_to_generate = tuple(ax for ax in x.axes if ax not in axes) @@ -67,6 +70,6 @@ class Dropout(eqx.Module): q = x.dtype.type(q) mask = haliax.random.bernoulli(key, q, shape_to_generate) - out = haliax.where(mask, x / q, haliax.zeros_like(x)) # type: ignore + out = haliax.where(mask, x / q, x.dtype.type(0)) # type: ignore assert out.dtype == x.dtype return out commit 137d0a3f6c7857af312cba1b608a547ba7964c61 Date: 2022-09-07T15:25:40-07:00 add some asserts to figure out what's going on with dtypes diff --git a/src/haliax/nn/dropout.py b/src/haliax/nn/dropout.py index 6253c8a..e435cb9 100644 --- a/src/haliax/nn/dropout.py +++ b/src/haliax/nn/dropout.py @@ -56,7 +56,6 @@ class Dropout(eqx.Module): raise RuntimeError("Dropout requires a key when running in non-deterministic mode.") else: with jax.named_scope(name="dropout"): - if self.broadcast_axes is None: if isinstance(x, NamedArray): shape_to_generate = x.axes commit 46e822f49dd92f31eb899b414ce5d450e3aeb375 Date: 2022-09-07T15:47:00-07:00 python will be the death of me diff --git a/src/haliax/__init__.py b/src/haliax/__init__.py index a4267c8..47281ba 100644 --- a/src/haliax/__init__.py +++ b/src/haliax/__init__.py @@ -29,11 +29,15 @@ from .wrap import wrap_axiswise_call, wrap_elemwise_binary, wrap_elemwise_unary, # creation routines def zeros(shape: AxisSpec, dtype=None) -> NamedArray: """Creates a NamedArray with all elements set to 0""" + if dtype is None: + dtype = jnp.float32 return full(shape, 0, dtype) def ones(shape: AxisSpec, dtype=None) -> NamedArray: """Creates a NamedArray with all elements set to 1""" + if dtype is None: + dtype = jnp.float32 return full(shape, 1, dtype) commit 3e49b95d04303862230e9a0537853028bfbb72a9 Date: 2022-09-12T14:01:38-07:00 i strongly suspect we need this extra cast to avoid serious problems diff --git a/src/haliax/nn/linear.py b/src/haliax/nn/linear.py index 0db07aa..c674b03 100644 --- a/src/haliax/nn/linear.py +++ b/src/haliax/nn/linear.py @@ -36,5 +36,6 @@ class Linear(eqx.Module): if self.bias is not None: q = q + self.bias + q = self.mp.cast_to_compute(q) return q commit 0bb10e997bb3925fa4b726157c4b92f187b0acd6 Date: 2022-09-13T15:39:04-07:00 Faster dropout (#24) * faster dropout? * let's try this! * what about this? * once more? * ok so it is dropout. let's see if this fixes * double check that this is the problem. * what about this? * ok i guess we fixed this for now? * cleanup my mess * cleanup the scalar branch a bit diff --git a/src/haliax/core.py b/src/haliax/core.py index 5649ea5..a87a823 100644 --- a/src/haliax/core.py +++ b/src/haliax/core.py @@ -24,6 +24,9 @@ class Axis: AxisSpec = Union[Axis, Sequence[Axis]] +Scalar = Union[float, int] +NamedNumeric = Union[Scalar, "NamedArray"] + @jax.tree_util.register_pytree_node_class @dataclass(frozen=True) @@ -752,7 +755,9 @@ def broadcast_to(a: NamedArray, axes: Tuple[Axis, ...], ensure_order: bool = Tru def broadcast_arrays( - *arrays: NamedArray, require_subset: bool = True, ensure_order: bool = True + *arrays: NamedArray, + require_subset: bool = True, + ensure_order: bool = True, ) -> Tuple[NamedArray, ...]: """ Broadcasts a sequence of arrays to a common set of axes. diff --git a/src/haliax/nn/dropout.py b/src/haliax/nn/dropout.py index e435cb9..aa5c790 100644 --- a/src/haliax/nn/dropout.py +++ b/src/haliax/nn/dropout.py @@ -48,7 +48,7 @@ class Dropout(eqx.Module): if isinstance(self.pdrop, (int, float)) and self.pdrop == 0: return x - elif self.pdrop == 1: + elif isinstance(self.pdrop, (int, float)) and self.pdrop == 1: return haliax.zeros_like(x) elif inference: return x @@ -66,9 +66,9 @@ class Dropout(eqx.Module): shape_to_generate = tuple(ax for ax in x.axes if ax not in axes) q = 1 - self.pdrop - q = x.dtype.type(q) mask = haliax.random.bernoulli(key, q, shape_to_generate) + q = x.dtype.type(q) - out = haliax.where(mask, x / q, x.dtype.type(0)) # type: ignore + out = haliax.where(mask, x / q, 0) assert out.dtype == x.dtype return out diff --git a/src/haliax/ops.py b/src/haliax/ops.py index d1deb87..6b4538b 100644 --- a/src/haliax/ops.py +++ b/src/haliax/ops.py @@ -3,9 +3,7 @@ from typing import Union import jax import jax.numpy as jnp -import haliax - -from .core import Axis, NamedArray, broadcast_arrays +from .core import Axis, NamedArray, NamedNumeric, broadcast_arrays def trace(array: NamedArray, axis1: Axis, axis2: Axis, offset=0, dtype=None) -> NamedArray: @@ -27,7 +25,7 @@ def trace(array: NamedArray, axis1: Axis, axis2: Axis, offset=0, dtype=None) -> return NamedArray(inner, axes) -def where(condition: Union[NamedArray, bool], x: NamedArray, y: NamedArray) -> NamedArray: +def where(condition: Union[NamedNumeric, bool], x: NamedNumeric, y: NamedNumeric) -> NamedArray: """Like jnp.where, but with named axes. This version currently only accepts the three argument form.""" # TODO: support the one argument form @@ -42,12 +40,12 @@ def where(condition: Union[NamedArray, bool], x: NamedArray, y: NamedArray) -> N assert isinstance(condition, NamedArray) if jnp.isscalar(x): - x = haliax.full_like(condition, x) + x = NamedArray(jnp.broadcast_to(x, condition.array.shape), condition.axes) if jnp.isscalar(y): - y = haliax.full_like(condition, y) + y = NamedArray(jnp.broadcast_to(y, condition.array.shape), condition.axes) - condition, x, y = broadcast_arrays(condition, x, y) + condition, x, y = broadcast_arrays(condition, x, y) # type: ignore return NamedArray(jnp.where(condition.array, x.array, y.array), condition.axes) commit 1a63b798143784fbb61db04d2ab5734fe7c4f9cd Date: 2022-09-15T05:13:39+00:00 wip always cast diff --git a/src/haliax/nn/linear.py b/src/haliax/nn/linear.py index c674b03..a8b74c2 100644 --- a/src/haliax/nn/linear.py +++ b/src/haliax/nn/linear.py @@ -32,10 +32,8 @@ class Linear(eqx.Module): @jax.named_scope(name="linear") def __call__(self, inputs): q = inputs.dot(self.In, self.weight) - q = self.mp.cast_to_compute(q) if self.bias is not None: q = q + self.bias - q = self.mp.cast_to_compute(q) return q commit fda3aa3800e03a0ff091752c9553a288fb810124 Date: 2022-09-15T00:42:17-07:00 no longer need to thread jmp through everywhere diff --git a/src/haliax/nn/linear.py b/src/haliax/nn/linear.py index a8b74c2..ce767cc 100644 --- a/src/haliax/nn/linear.py +++ b/src/haliax/nn/linear.py @@ -2,7 +2,6 @@ from typing import Optional import equinox as eqx import jax -import jmp import haliax as hax @@ -18,16 +17,14 @@ class Linear(eqx.Module): In: AxisSpec = eqx.static_field() Out: AxisSpec = eqx.static_field() - mp: jmp.Policy = eqx.static_field() - def __init__(self, In: AxisSpec, Out: AxisSpec, *, key, mp: jmp.Policy, include_bias=True): + def __init__(self, In: AxisSpec, Out: AxisSpec, *, key, include_bias=True): joint_spec = hax.concat_axis_specs(In, Out) - self.weight = hax.random.normal(key, joint_spec, dtype=mp.param_dtype) * 0.02 - self.bias = hax.zeros(Out, dtype=mp.param_dtype) if include_bias else None + self.weight = hax.random.normal(key, joint_spec) * 0.02 + self.bias = hax.zeros(Out) if include_bias else None self.In = In self.Out = Out - self.mp = mp @jax.named_scope(name="linear") def __call__(self, inputs): commit 510f22cfe4e2d65b252ac757e90352ac09e539bd Date: 2022-09-15T16:43:32-07:00 Add tril and triu, update gpt2 to use it. (#25) * add tril and triu to hax * use haliax tril in gpt2 * fully hax-ified gpt2 * infer experiment root * support argmax, argmin, remove keepdims because i hate it * add some todos for vmap diff --git a/src/haliax/__init__.py b/src/haliax/__init__.py index 47281ba..014a096 100644 --- a/src/haliax/__init__.py +++ b/src/haliax/__init__.py @@ -22,7 +22,7 @@ from .core import ( unflatten_axis, ) from .hof import reduce, scan, vmap -from .ops import trace, where +from .ops import trace, tril, triu, where from .wrap import wrap_axiswise_call, wrap_elemwise_binary, wrap_elemwise_unary, wrap_reduction_call @@ -139,8 +139,8 @@ trunc = wrap_elemwise_unary(jnp.trunc) all = wrap_reduction_call(jnp.all) amax = wrap_reduction_call(jnp.amax) any = wrap_reduction_call(jnp.any) -# argmax = wrap_reduction_call(jnp.argmax) -# argmin = wrap_reduction_call(jnp.argmin) +argmax = wrap_reduction_call(jnp.argmax, single_axis_only=True) +argmin = wrap_reduction_call(jnp.argmin, single_axis_only=True) max = wrap_reduction_call(jnp.max) mean = wrap_reduction_call(jnp.mean) min = wrap_reduction_call(jnp.min) @@ -157,6 +157,7 @@ cumsum = wrap_axiswise_call(jnp.cumsum, True) cumprod = wrap_axiswise_call(jnp.cumprod, True) cumproduct = wrap_axiswise_call(jnp.cumproduct, True) sort = wrap_axiswise_call(jnp.sort, True) +argsort = wrap_axiswise_call(jnp.argsort, True) # elemwise binary ops add = wrap_elemwise_binary(jnp.add) @@ -283,6 +284,8 @@ __all__ = [ "all", "amax", "any", + "argmax", + "argmin", "max", "mean", "min", @@ -302,6 +305,8 @@ __all__ = [ "vmap", "trace", "where", + "tril", + "triu", "add", "arctan2", "bitwise_and", diff --git a/src/haliax/core.py b/src/haliax/core.py index a87a823..ee74eb6 100644 --- a/src/haliax/core.py +++ b/src/haliax/core.py @@ -114,28 +114,21 @@ class NamedArray: return haliax.take(self, axis=axis, index=index) # np.ndarray methods: - def all(self, axis: Optional[AxisSpec] = None, *, keepdims=None) -> "NamedArray": - return haliax.all(self, axis=axis, keepdims=keepdims) + def all(self, axis: Optional[AxisSpec] = None) -> "NamedArray": + return haliax.all(self, axis=axis) - def any(self, axis: Optional[AxisSpec] = None, *, keepdims=None) -> "NamedArray": - return haliax.any(self, axis=axis, keepdims=keepdims) + def any(self, axis: Optional[AxisSpec] = None) -> "NamedArray": + return haliax.any(self, axis=axis) - # def select(self, axis: Axis, index: Union[int, 'NamedArray', jnp.ndarray]) -> Any: - # if isinstance(index, NamedArray): - # index = index.array + # TODO: test + def argmax(self, axis: Axis) -> "NamedArray": + return haliax.argmax(self, axis=axis) - # TODO - # def argmax(self, axis: Optional[int] = None, keepdims=None) -> Any: - # ... - # - # def argmin(self, axis: Optional[int] = None, keepdims=None) -> Any: - # ... - # - # def argpartition(self, kth, axis=-1, kind='introselect', order=None) -> Any: - # ... - # - # def argsort(self, axis: Optional[int] = -1, kind='quicksort', order=None) -> Any: - # ... + def argmin(self, axis: Axis) -> "NamedArray": + return haliax.argmin(self, axis=axis) + + def argsort(self, axis: Axis) -> "NamedArray": + return haliax.argsort(self, axis=axis) def astype(self, dtype) -> "NamedArray": return NamedArray(self.array.astype(dtype), self.axes) @@ -176,31 +169,28 @@ class NamedArray: self, axis: Optional[AxisSpec] = None, *, - keepdims=None, initial=None, where=None, ) -> "NamedArray": - return haliax.max(self, axis=axis, keepdims=keepdims, initial=initial, where=where) + return haliax.max(self, axis=axis, initial=initial, where=where) def mean( self, axis: Optional[AxisSpec] = None, *, dtype=None, - keepdims=False, where=None, ) -> "NamedArray": - return haliax.mean(self, axis=axis, dtype=dtype, keepdims=keepdims, where=where) + return haliax.mean(self, axis=axis, dtype=dtype, where=where) def min( self, axis: Optional[AxisSpec] = None, *, - keepdims=None, initial=None, where=None, ) -> "NamedArray": - return haliax.min(self, axis=axis, keepdims=keepdims, initial=initial, where=where) + return haliax.min(self, axis=axis, initial=initial, where=where) # TODO # def nonzero(self, *, size=None, fill_value=None) -> Any: @@ -211,7 +201,6 @@ class NamedArray: axis: Optional[AxisSpec] = None, *, dtype=None, - keepdims=None, initial=None, where=None, ) -> "NamedArray": @@ -219,7 +208,6 @@ class NamedArray: self, axis=axis, dtype=dtype, - keepdims=keepdims, initial=initial, where=where, ) @@ -254,7 +242,6 @@ class NamedArray: *, dtype=None, ddof=0, - keepdims=False, where=None, ) -> "NamedArray": return haliax.std( @@ -262,7 +249,6 @@ class NamedArray: axis=axis, dtype=dtype, ddof=ddof, - keepdims=keepdims, where=where, ) @@ -271,7 +257,6 @@ class NamedArray: axis: Optional[AxisSpec] = None, *, dtype=None, - keepdims=None, initial=None, where=None, ) -> "NamedArray": @@ -279,7 +264,6 @@ class NamedArray: self, axis=axis, dtype=dtype, - keepdims=keepdims, initial=initial, where=where, ) @@ -298,7 +282,6 @@ class NamedArray: axis: Optional[AxisSpec] = None, dtype=None, ddof=0, - keepdims=False, *, where=None, ) -> "NamedArray": @@ -307,7 +290,6 @@ class NamedArray: axis=axis, dtype=dtype, ddof=ddof, - keepdims=keepdims, where=where, ) @@ -652,7 +634,7 @@ def unflatten_axis(array: NamedArray, axis: Axis, new_axes: Sequence[Axis]) -> N def named(a: jnp.ndarray, axis: AxisSpec) -> NamedArray: """Creates a NamedArray from a numpy array and a list of axes""" if isinstance(axis, Axis): - if jnp.shape(a) != axis.size: + if jnp.shape(a) != (axis.size,): raise ValueError(f"Shape of array {jnp.shape(a)} does not match size of axis {axis.size}") return NamedArray(a, (axis,)) else: diff --git a/src/haliax/hof.py b/src/haliax/hof.py index 83cb352..08698fa 100644 --- a/src/haliax/hof.py +++ b/src/haliax/hof.py @@ -161,12 +161,12 @@ def vmap( # TODO: allow specifying spmd axis name and/or inferring it from resource_mapping # TODO: allow other axes to be mapped over # TODO: maybe implement equinox-style filtering vmap + # TODO: tests to exercise this more @wraps(fn) def wrapped_vmap_fn(*args): # TODO: this probably results in a lot of compilation misses. Need to think about it. mapped_axes = [] chilled_args = [] - # TODO: have to figure out element structure, but not relevant today for i, arg in enumerate(args): if i in unmmapped_argnums: diff --git a/src/haliax/nn/__init__.py b/src/haliax/nn/__init__.py index f619769..21572bf 100644 --- a/src/haliax/nn/__init__.py +++ b/src/haliax/nn/__init__.py @@ -29,7 +29,7 @@ selu = wrap_elemwise_unary(jnn.selu) gelu = wrap_elemwise_unary(jnn.gelu) # TODO: glu = wrap_elemwise_unary(jnn.gelu) -logsumexp = wrap_reduction_call(jnn.logsumexp) +logsumexp = wrap_reduction_call(jnn.logsumexp, False) softmax = wrap_axiswise_call(jnn.softmax, False) # TODO: standardize has optional "mean" and "variance" arguments we need to support diff --git a/src/haliax/ops.py b/src/haliax/ops.py index 6b4538b..33d2be9 100644 --- a/src/haliax/ops.py +++ b/src/haliax/ops.py @@ -49,4 +49,20 @@ def where(condition: Union[NamedNumeric, bool], x: NamedNumeric, y: NamedNumeric return NamedArray(jnp.where(condition.array, x.array, y.array), condition.axes) -__all__ = ["trace", "where"] +def tril(array: NamedArray, axis1: Axis, axis2: Axis, k=0) -> NamedArray: + """Compute the lower triangular part of an array along two named axes.""" + array = array.rearrange((..., axis1, axis2)) + + inner = jnp.tril(array.array, k=k) + return NamedArray(inner, array.axes) + + +def triu(array: NamedArray, axis1: Axis, axis2: Axis, k=0) -> NamedArray: + """Compute the upper triangular part of an array along two named axes.""" + array = array.rearrange((..., axis1, axis2)) + + inner = jnp.triu(array.array, k=k) + return NamedArray(inner, array.axes) + + +__all__ = ["trace", "where", "tril", "triu"] diff --git a/src/haliax/wrap.py b/src/haliax/wrap.py index f849349..61f29eb 100644 --- a/src/haliax/wrap.py +++ b/src/haliax/wrap.py @@ -20,33 +20,40 @@ def wrap_elemwise_unary(f): return wrapper -def wrap_reduction_call(fn): +def wrap_reduction_call(fn, single_axis_only: bool = False): @functools.wraps(fn) - def wrapper(a, axis: Optional[AxisSpec] = None, keepdims=False, **kwargs): + def wrapper(a, axis: Optional[AxisSpec] = None, **kwargs): if kwargs.get("where", None) is not None: raise ValueError("where is not supported yet for NamedArray") if kwargs.get("out", None) is not None: - raise ValueError("where is not supported yet for NamedArray") + raise ValueError("out is not supported yet for NamedArray") + if kwargs.get("keepdims", False): + raise ValueError("keepdims is not supported for NamedArray") if isinstance(a, NamedArray): if axis is None: - result = fn(a.array, axis=None, keepdims=keepdims, **kwargs) + result = fn(a.array, axis=None, **kwargs) if jnp.isscalar(result): return result else: return NamedArray(result, ()) else: axis = ensure_tuple(axis) + if single_axis_only and len(axis) > 1: + raise ValueError(f"{fn.__name__} only supports a single axis") indices = a._lookup_indices(axis) if indices is None or any(x is None for x in indices): raise ValueError(f"axis {axis} is not in {a.axes}") - new_axes = a.axes if keepdims else [ax for ax in a.axes if ax not in axis] - result = fn(a.array, axis=indices, keepdims=keepdims, **kwargs) + new_axes = [ax for ax in a.axes if ax not in axis] + if single_axis_only: + result = fn(a.array, axis=indices[0], **kwargs) + else: + result = fn(a.array, axis=indices, **kwargs) if jnp.isscalar(result): return result - return NamedArray(fn(a.array, axis=indices, keepdims=keepdims, **kwargs), tuple(new_axes)) + return NamedArray(result, tuple(new_axes)) else: - return fn(a, axis=axis, keepdims=keepdims, **kwargs) + return fn(a, axis=axis, **kwargs) wrapper.__doc__ = ( """ diff --git a/tests/core_test.py b/tests/core_test.py index e8ec387..9874098 100644 --- a/tests/core_test.py +++ b/tests/core_test.py @@ -85,6 +85,10 @@ def test_reduction_functions(): ) ) + # argmax + assert jnp.all(jnp.equal(hax.argmax(m1).array, jnp.argmax(m1.array))) + assert jnp.all(jnp.equal(hax.argmax(m1, axis=Height).array, jnp.argmax(m1.array, axis=0))) + def test_split(): Height = Axis("Height", 2) @@ -166,6 +170,12 @@ def test_cumsum_etc(): assert jnp.all(jnp.equal(hax.cumprod(named1, axis=Depth).array, jnp.cumprod(named1.array, axis=2))) assert hax.cumprod(named1, axis=Depth).axes == (Height, Width, Depth) + assert jnp.all(jnp.equal(hax.argsort(named1, axis=Height).array, jnp.argsort(named1.array, axis=0))) + assert hax.argsort(named1, axis=Height).axes == (Height, Width, Depth) + + assert jnp.all(jnp.equal(hax.argsort(named1, axis=Width).array, jnp.argsort(named1.array, axis=1))) + assert hax.argsort(named1, axis=Width).axes == (Height, Width, Depth) + def test_rearrange(): H = Axis("Height", 2) diff --git a/tests/test_ops.py b/tests/test_ops.py index 85d7a4f..4a3bdba 100644 --- a/tests/test_ops.py +++ b/tests/test_ops.py @@ -109,3 +109,24 @@ def test_where(): with pytest.raises(ValueError): _ = hax.where(named5 > named6, named5, named6) + + +def test_tril_triu(): + Height = Axis("Height", 10) + Width = Axis("Width", 3) + Depth = Axis("Depth", 4) + + for hax_fn, jnp_fn in [(hax.tril, jnp.tril), (hax.triu, jnp.triu)]: + named1 = hax.random.uniform(PRNGKey(0), (Height, Width, Depth)) + named2 = hax_fn(named1, Width, Depth) + assert jnp.all(jnp.isclose(named2.array, jnp_fn(named1.array))) + + named3 = hax_fn(named1, Width, Depth, k=1) + assert jnp.all(jnp.isclose(named3.array, jnp_fn(named1.array, k=1))) + + named4 = hax_fn(named1, Width, Depth, k=-1) + assert jnp.all(jnp.isclose(named4.array, jnp_fn(named1.array, k=-1))) + + named5 = hax_fn(named1, Height, Depth) + expected5 = jnp_fn(named1.array.transpose([1, 0, 2])) + assert jnp.all(jnp.isclose(named5.array, expected5)) commit 03f399bb9b7ca72a9f7d24723e4e1156e65954d1 Date: 2022-09-15T16:47:06-07:00 Haliax partitioning (#26) * make named_pjit more decorator-y * add a context manager for timing * switch to equinox filter_vmap * misc minor cleanup * move all of the logical axis mapping stuff to haliax diff --git a/src/haliax/partitioning.py b/src/haliax/partitioning.py index cce5cbf..ebb26e4 100644 --- a/src/haliax/partitioning.py +++ b/src/haliax/partitioning.py @@ -1,15 +1,17 @@ import contextlib +import functools import threading +import typing from typing import List, Mapping, Optional, Sequence, TypeVar, Union import jax from equinox import is_array from equinox.custom_types import PyTree -from jax.experimental import pjit +from jax.experimental.pjit import pjit, with_sharding_constraint from jax.interpreters.pxla import PartitionSpec from .core import NamedArray -from .util import ensure_tuple, is_named_array +from .util import StringHolderEnum, ensure_tuple, is_named_array LogicalAxisName = str @@ -19,6 +21,13 @@ ResourceMapping = Mapping[LogicalAxisName, PhysicalAxisSpec] """Mapping from logical axis names to physical axis names""" +class ResourceAxis(StringHolderEnum): + """Standard names for physical axes""" + + MODEL = "model" + DATA = "data" + + class _ResourceMappingHolder: """Global resource mapping, used with a context manager to give dynamic scoping to resource mappings""" @@ -81,5 +90,87 @@ def logically_sharded(x: T, logical_axes: Optional[PyTree] = None) -> T: else: pspec = jax.tree_util.tree_map(_as_pspec, x, logical_axes, is_leaf=is_named_array) - print(x, pspec) - return pjit.with_sharding_constraint(x, pspec) + return with_sharding_constraint(x, pspec) + + +def infer_resource_partitions(tree: PyTree) -> PyTree: + """ + Infer the resource partitions for a module, to be used with pjit. + The basic idea is to tree all NamedArrays as leaves for the purposes of this function, + and to create PartitionSpecs from those names plus the contextual resource_mapping. + """ + + def named_array_is_leaf(x): + return isinstance(x, NamedArray) + + axis_resources = _mapping_holder.thread_data.resource_mapping + + if axis_resources is None: + raise ValueError("No resource mapping found") + + def partition_spec(node: typing.Any): + if isinstance(node, NamedArray): + return NamedArray( + PartitionSpec(*tuple(axis_resources.get(axis.name, None) for axis in node.axes)), node.axes + ) + else: + return None + + return jax.tree_util.tree_map(partition_spec, tree, is_leaf=named_array_is_leaf) + + +def eval_resource_partitions(fn): + """ + Similar to jax.eval_shape but for resource partitions. It returns a PyTree of PartitionSpecs. + """ + + def f(*args, **kwargs): + out_shape = jax.eval_shape(fn, *args, **kwargs) + return infer_resource_partitions(out_shape) + + return f + + +def named_pjit_init(cls: typing.Type[T], **pjit_args): + """Uses NamedArrays to infer the resource partitions for a module when creating it""" + + @functools.wraps(cls.__new__) + def init(*args, **kwargs): + inst = cls(*args, **kwargs) + return inst + + return named_pjit(init, **pjit_args) + + +def named_pjit(fn=None, **pjit_args): + """ + Uses NamedArrays to infer the resource partitions for calling a function + """ + + if fn is None: + return functools.partial(named_pjit, **pjit_args) + + @functools.wraps(fn) + def f(*args, **kwargs): + in_resources = infer_resource_partitions((args, kwargs)) + shapes = jax.eval_shape(fn, *args, **kwargs) + out_resources = infer_resource_partitions(shapes) + + return pjit(lambda args, kwargs: fn(*args, **kwargs), in_resources, out_resources, **pjit_args)(args, kwargs) + + return f + + +__all__ = [ + "LogicalAxisName", + "PhysicalAxis", + "PhysicalAxisSpec", + "ResourceAxis", + "ResourceMapping", + "resource_mapping", + "logically_sharded", + "infer_resource_partitions", + "eval_resource_partitions", + "named_pjit_init", + "named_pjit", +] diff --git a/src/haliax/util.py b/src/haliax/util.py index c437482..038f48d 100644 --- a/src/haliax/util.py +++ b/src/haliax/util.py @@ -15,3 +15,20 @@ def ensure_tuple(x: Union[Sequence[T], T]) -> Tuple[T, ...]: if isinstance(x, Sequence): return tuple(x) return (x,) + + +class StringHolderEnum(type): + """Like a python enum but just holds string constants, as opposed to wrapped string constants""" + + # https://stackoverflow.com/questions/62881486/a-group-of-constants-in-python + + def __new__(cls, name, bases, members): + # this just iterates through the class dict and removes + # all the dunder methods + cls.members = [v for k, v in members.items() if not k.startswith("__") and not callable(v)] + return super().__new__(cls, name, bases, members) + + # giving your class an __iter__ method gives you membership checking + # and the ability to easily convert to another iterable + def __iter__(cls): + yield from cls.members diff --git a/tests/test_partitioning.py b/tests/test_partitioning.py new file mode 100644 index 0000000..9fdf155 --- /dev/null +++ b/tests/test_partitioning.py @@ -0,0 +1,115 @@ +import equinox as eqx +import jax +import jax.numpy as jnp +import numpy as np +from equinox.custom_types import Array +from jax.interpreters import pxla +from jax.interpreters.pxla import PartitionSpec, Replicated, ShardedAxis +from utils import skip_if_not_enough_devices + +import haliax as hax +from haliax import Axis, NamedArray +from haliax.partitioning import ResourceAxis, infer_resource_partitions, named_pjit_init, resource_mapping + + +class MyModule(eqx.Module): + named: NamedArray + unnamed1: Array + static_field: int = eqx.static_field() + + +Dim1 = Axis("dim1", 8) +Dim2 = Axis("dim2", 16) +Dim3 = Axis("dim3", 32) + +resource_map = { + "dim2": ResourceAxis.DATA, + "dim3": ResourceAxis.MODEL, +} + + +def test_infer_named_axes(): + with resource_mapping(resource_map): + mod = MyModule(named=hax.ones((Dim1, Dim2, Dim3)), unnamed1=jnp.ones(Dim2.size), static_field=1) + + axes: MyModule = infer_resource_partitions(mod) + + assert axes.named.array == PartitionSpec(None, ResourceAxis.DATA, ResourceAxis.MODEL) + assert axes.unnamed1 is None + + +class MyModuleInit(eqx.Module): + named: NamedArray + unnamed1: Array + named2: NamedArray + static_field: int = eqx.static_field() + + def __init__(self): + self.named = hax.ones((Dim2, Dim3)) + self.unnamed1 = jnp.ones(()) + self.named2 = hax.ones(Dim3) + self.static_field = 1 + + +@skip_if_not_enough_devices(4) +def test_pjit_class_init(): + with resource_mapping(resource_map): + devices = jax.devices() + with pxla.Mesh(np.array(devices).reshape(-1, 2), (ResourceAxis.DATA, ResourceAxis.MODEL)): + mod = named_pjit_init(MyModuleInit)() + + assert mod.named.array.shape == (Dim2.size, Dim3.size) + assert mod.named.array.sharding_spec.mesh_mapping == ( + ShardedAxis(0), + ShardedAxis(1), + ) + + assert mod.unnamed1.shape == () + assert mod.unnamed1.sharding_spec.mesh_mapping == ( + Replicated(len(devices) // 2), + Replicated(2), + ) + assert mod.named2.array.shape == (Dim3.size,) + assert mod.named2.array.sharding_spec.mesh_mapping == ( + Replicated(len(devices) // 2), + ShardedAxis(0), + ) + + +@skip_if_not_enough_devices(4) +def test_pjit_class_nested_init(): + with resource_mapping(resource_map): + + class Mod2(eqx.Module): + inner: MyModuleInit + + def __init__(self): + self.inner = MyModuleInit() + + devices = jax.devices() + with pxla.Mesh(np.array(devices).reshape(-1, 2), (ResourceAxis.DATA, ResourceAxis.MODEL)): + mod2 = named_pjit_init(Mod2)() + + mod = mod2.inner + assert mod.named.array.shape == (Dim2.size, Dim3.size) + assert mod.unnamed1.shape == () + assert mod.named2.array.shape == (Dim3.size,) + + +def test_pjit_class_init_with_args(): + with resource_mapping(resource_map): + + class ModWithArgs(eqx.Module): + array: NamedArray + array2: NamedArray + + def __init__(self, in_array: NamedArray): + self.array = in_array + self.array2 = hax.zeros(Dim3) + + devices = jax.devices() + with pxla.Mesh(np.array(devices).reshape(-1, 1), (ResourceAxis.DATA, ResourceAxis.MODEL)): + mod = named_pjit_init(ModWithArgs)(hax.ones((Dim1, Dim2))) + assert isinstance(mod, ModWithArgs) + assert mod.array.array.shape == (Dim1.size, Dim2.size) + assert mod.array2.array.shape == (Dim3.size,) commit a3df4aa73cb05b7516130464937db1aa79e3cd76 Date: 2022-09-15T17:14:55-07:00 move resource mappings to config file diff --git a/src/haliax/partitioning.py b/src/haliax/partitioning.py index ebb26e4..4ae81a4 100644 --- a/src/haliax/partitioning.py +++ b/src/haliax/partitioning.py @@ -40,7 +40,7 @@ _mapping_holder = _ResourceMappingHolder() @contextlib.contextmanager -def resource_mapping(mapping: ResourceMapping, **kwargs): +def axis_mapping(mapping: ResourceMapping, **kwargs): """Context manager for setting the global resource mapping""" if len(kwargs): mapping = dict(mapping) @@ -167,7 +167,7 @@ __all__ = [ "PhysicalAxisSpec", "ResourceAxis", "ResourceMapping", - "resource_mapping", + "axis_mapping", "logically_sharded", "infer_resource_partitions", "eval_resource_partitions", diff --git a/tests/test_partitioning.py b/tests/test_partitioning.py index 9fdf155..19be12d 100644 --- a/tests/test_partitioning.py +++ b/tests/test_partitioning.py @@ -9,7 +9,7 @@ from utils import skip_if_not_enough_devices import haliax as hax from haliax import Axis, NamedArray -from haliax.partitioning import ResourceAxis, infer_resource_partitions, named_pjit_init, resource_mapping +from haliax.partitioning import ResourceAxis, axis_mapping, infer_resource_partitions, named_pjit_init class MyModule(eqx.Module): @@ -29,7 +29,7 @@ resource_map = { def test_infer_named_axes(): - with resource_mapping(resource_map): + with axis_mapping(resource_map): mod = MyModule(named=hax.ones((Dim1, Dim2, Dim3)), unnamed1=jnp.ones(Dim2.size), static_field=1) axes: MyModule = infer_resource_partitions(mod) @@ -53,7 +53,7 @@ class MyModuleInit(eqx.Module): @skip_if_not_enough_devices(4) def test_pjit_class_init(): - with resource_mapping(resource_map): + with axis_mapping(resource_map): devices = jax.devices() with pxla.Mesh(np.array(devices).reshape(-1, 2), (ResourceAxis.DATA, ResourceAxis.MODEL)): mod = named_pjit_init(MyModuleInit)() @@ -78,7 +78,7 @@ def test_pjit_class_init(): @skip_if_not_enough_devices(4) def test_pjit_class_nested_init(): - with resource_mapping(resource_map): + with axis_mapping(resource_map): class Mod2(eqx.Module): inner: MyModuleInit @@ -97,7 +97,7 @@ def test_pjit_class_nested_init(): def test_pjit_class_init_with_args(): - with resource_mapping(resource_map): + with axis_mapping(resource_map): class ModWithArgs(eqx.Module): array: NamedArray commit 506a6e919d7a499935f620caae684d31ef6003e0 Date: 2022-09-16T10:26:28-07:00 factor our initialization to its own file, use furl for managing url-type things instead of Path diff --git a/requirements.txt b/requirements.txt index 47b40f2..4d36557 100644 --- a/requirements.txt +++ b/requirements.txt @@ -11,3 +11,4 @@ gcsfs braceexpand git+https://github.com/deepmind/jmp#260e5ba01f46b10c579a61393e6c7e546aeae93e fsspec==2022.7.1 # pin this to make gcsfs happy +furl commit 4a6994735d01fb7fd0a51cf258f40b1c4d981422 Date: 2022-09-16T12:43:06-07:00 move named_call to haliax and use it to wrap random diff --git a/src/haliax/random.py b/src/haliax/random.py index 06f6fe0..f4bb5da 100644 --- a/src/haliax/random.py +++ b/src/haliax/random.py @@ -8,12 +8,13 @@ import jax.random as jrandom # TODO: handle broadcasting of array args to random functions (e.g. minval and maxval for uniform) from haliax.core import Axis, NamedArray -from haliax.util import ensure_tuple +from haliax.util import ensure_tuple, named_call def _wrap_random_function(func): """Wrap a jax random function to return a NamedArray and takes axes as inputs""" + @named_call(name=func.__name__) @functools.wraps(func) def wrapper(key: jrandom.KeyArray, *args, **kwargs): sig: inspect.BoundArguments = inspect.signature(func).bind(key, *args, **kwargs) diff --git a/src/haliax/util.py b/src/haliax/util.py index 038f48d..2c6376f 100644 --- a/src/haliax/util.py +++ b/src/haliax/util.py @@ -1,4 +1,6 @@ -from typing import Sequence, Tuple, TypeVar, Union +from typing import Optional, Sequence, Tuple, TypeVar, Union + +import jax T = TypeVar("T") @@ -32,3 +34,24 @@ class StringHolderEnum(type): # and the ability to easily convert to another iterable def __iter__(cls): yield from cls.members + + +def _UNSPECIFIED(): + raise ValueError("unspecified") + + +def named_call(f=_UNSPECIFIED, name: Optional[str] = None): + if f is _UNSPECIFIED: + return lambda f: named_call(f, name) # type: ignore + else: + if name is None: + name = f.__name__ + if name == "__call__": + if hasattr(f, "__self__"): + name = f.__self__.__class__.__name__ # type: ignore + else: + name = f.__qualname__.rsplit(".", maxsplit=1)[0] # type: ignore + else: + name = f.__qualname__ + + return jax.named_scope(name)(f) commit 43f7e2761b4b043ec606ac5218b9d12aa17d1c20 Date: 2022-09-19T13:55:21-07:00 auto-shard prng keys in haliax random (#27) * improve comments * fix empty shape for random diff --git a/src/haliax/hof.py b/src/haliax/hof.py index 08698fa..fd81aa9 100644 --- a/src/haliax/hof.py +++ b/src/haliax/hof.py @@ -7,6 +7,7 @@ import jax import jax.lax as lax from .core import Axis, NamedArray +from .partitioning import physical_axis_name from .util import ensure_tuple, is_named_array @@ -183,7 +184,11 @@ def vmap( chilled = jax.tree_util.tree_map(_chill_named_arrays, r, is_leaf=is_named_array) return chilled - result = jax.vmap(wrapped_fn, in_axes=mapped_axes, out_axes=0, axis_size=axis.size)(*args) + spmd_axis_name = physical_axis_name(axis) + + result = jax.vmap( + wrapped_fn, in_axes=mapped_axes, out_axes=0, axis_size=axis.size, spmd_axis_name=spmd_axis_name + )(*args) result = jax.tree_util.tree_map(partial(_unchill_named_arrays, axis), result, is_leaf=_is_chill_array) return result diff --git a/src/haliax/jax_utils.py b/src/haliax/jax_utils.py new file mode 100644 index 0000000..0555270 --- /dev/null +++ b/src/haliax/jax_utils.py @@ -0,0 +1,32 @@ +from typing import Optional, Sequence, Union + +import numpy as np +from chex import PRNGKey +from jax import numpy as jnp +from jax import random as jrandom + + +def shaped_rng_split(key, split_shape: Union[int, Sequence[int]] = 2) -> jrandom.KeyArray: + if isinstance(split_shape, int): + num_splits = split_shape + split_shape = (num_splits,) + key.shape + else: + num_splits = np.prod(split_shape) + split_shape = tuple(split_shape) + key.shape + + if num_splits == 1: + return jnp.reshape(key, split_shape) + + unshaped = maybe_rng_split(key, num_splits) + return jnp.reshape(unshaped, split_shape) + + +def maybe_rng_split(key: Optional[PRNGKey], num: int = 2): + """Splits a random key into multiple random keys. If the key is None, then it replicates the None. Also handles + num == 1 case""" + if key is None: + return [None] * num + elif num == 1: + return jnp.reshape(key, (1,) + key.shape) + else: + return jrandom.split(key, num) diff --git a/src/haliax/partitioning.py b/src/haliax/partitioning.py index 4ae81a4..f0fd602 100644 --- a/src/haliax/partitioning.py +++ b/src/haliax/partitioning.py @@ -10,7 +10,7 @@ from equinox.custom_types import PyTree from jax.experimental.pjit import pjit, with_sharding_constraint from jax.interpreters.pxla import PartitionSpec -from .core import NamedArray +from .core import Axis, AxisSpec, NamedArray from .util import StringHolderEnum, ensure_tuple, is_named_array @@ -156,11 +156,30 @@ def named_pjit(fn=None, **pjit_args): shapes = jax.eval_shape(fn, *args, **kwargs) out_resources = infer_resource_partitions(shapes) - return pjit(lambda args, kwargs: fn(*args, **kwargs), in_resources, out_resources, **pjit_args)(args, kwargs) + @functools.wraps(fn) + def fn_to_call(args, kwargs): + return fn(*args, **kwargs) + + return pjit(fn_to_call, in_resources, out_resources, **pjit_args)(args, kwargs) return f +def physical_axis_name(axis: Axis) -> Optional[PhysicalAxis]: + """Get the physical axis name for a logical axis""" + mapping = _mapping_holder.thread_data.resource_mapping + if mapping is None: + return None + else: + return mapping.get(axis.name, None) + + +def pspec_for_axis(axis: AxisSpec) -> PartitionSpec: + """Get the PartitionSpec for a single axis""" + axis = ensure_tuple(axis) + return PartitionSpec(*(physical_axis_name(a) for a in axis)) + + __all__ = [ "LogicalAxisName", "PhysicalAxis", @@ -173,4 +192,6 @@ __all__ = [ "eval_resource_partitions", "named_pjit_init", "named_pjit", + "physical_axis_name", + "pspec_for_axis", ] diff --git a/src/haliax/random.py b/src/haliax/random.py index f4bb5da..3d0db1a 100644 --- a/src/haliax/random.py +++ b/src/haliax/random.py @@ -4,12 +4,15 @@ import functools import inspect from typing import Sequence +import jax import jax.random as jrandom # TODO: handle broadcasting of array args to random functions (e.g. minval and maxval for uniform) from haliax.core import Axis, NamedArray from haliax.util import ensure_tuple, named_call +from .partitioning import pspec_for_axis + def _wrap_random_function(func): """Wrap a jax random function to return a NamedArray and takes axes as inputs""" @@ -30,12 +33,43 @@ def _wrap_random_function(func): is_haliax = False if is_haliax: - sig.arguments["shape"] = shape - # now invoke - out = func(**sig.arguments) - if is_haliax: - return NamedArray(out, orig_shape) + # this is a bit tricky but, for sharded models, we sometimes want to split the random key so that we only + # need to generate the random numbers for the local shard. We do this because the RNG can't actually + # auto-shard, meaning that if you want to generate a [1024] vector across 4 devices, each one actually + # generates all 1024 numbers, and then only uses 256 of them. This is a waste of time, especially when it's + # not a [1024] vector but a [1600, 6400] matrix (for say, gpt-2). So we split the key here, and then let + # vmap hopefully only generate the random numbers for the local shard. + # + # However, we don't want to oversplit or it kind of ruins the whole point since we have to split the key on + # every node... So instead we just split along the *largest* axis that is sharded + # TODO: we won't need to do this when they add better splitting for random numbers + # (froystig is maybe going to do this?) + + # what we do is we take the biggest axis that is sharded and split on it, ties going to the first axis + pspec = pspec_for_axis(orig_shape) + if pspec: + biggest_axis, biggest_physical = max(zip(orig_shape, pspec), key=lambda x: x[0].size if x[1] else 0) + else: + biggest_axis = biggest_physical = None + + if biggest_physical and biggest_axis.size > 1: + index_of_biggest_axis = orig_shape.index(biggest_axis) + shape = shape[:index_of_biggest_axis] + shape[index_of_biggest_axis + 1 :] + sig.arguments["shape"] = shape + keys = jrandom.split(key, biggest_axis.size) + + def fn(key): + return func(key, *sig.args[1:], **sig.kwargs) + + out = jax.vmap(fn, in_axes=(0,), out_axes=index_of_biggest_axis)(keys) + return NamedArray(out, orig_shape) + else: + sig.arguments["shape"] = shape + out = func(**sig.arguments) + return NamedArray(out, orig_shape) + else: + return func(**sig.arguments) return wrapper diff --git a/tests/test_random.py b/tests/test_random.py new file mode 100644 index 0000000..c43ea67 --- /dev/null +++ b/tests/test_random.py @@ -0,0 +1,8 @@ +import jax + +import haliax as hax + + +def test_empty_shape(): + key = jax.random.PRNGKey(0) + hax.random.uniform(key, shape=()) commit 58289f8859eb31404f46b88f8cc693fd3ea38e73 Date: 2022-09-19T13:57:07-07:00 rename _ScannedArrayResult to _PassiveNamedArray and reorganize hof.py diff --git a/src/haliax/hof.py b/src/haliax/hof.py index fd81aa9..bce7019 100644 --- a/src/haliax/hof.py +++ b/src/haliax/hof.py @@ -1,5 +1,5 @@ import dataclasses -from functools import partial, wraps +from functools import wraps from typing import Any, Callable, Sequence, Tuple, TypeVar, Union import equinox @@ -16,29 +16,6 @@ X = TypeVar("X") Y = TypeVar("Y") -@jax.tree_util.register_pytree_node_class -@dataclasses.dataclass(frozen=True) -class _ScannedArrayResult: - """With scan in NamedArray, we can't just have the scan tree prepend the scanned axis to the result, because - we don't have a way to feed it the name of the scanned axis. This class is a 'chill' version of NamedArray - that doesn't check invariants until we're ready to create the result - """ - - array: jax.numpy.ndarray - main_axes: Tuple[Axis, ...] - - def to_named_array(self, scan_axis: Axis): - return NamedArray(self.array, (scan_axis,) + self.main_axes) - - def tree_flatten(self) -> Any: - return ((self.array,), self.main_axes) - - @classmethod - def tree_unflatten(cls, aux, tree: Any) -> Any: - assert len(tree) == 1 - return cls(tree[0], main_axes=aux) - - def scan(f: Callable[[Carry, X], Tuple[Carry, Y]], axis: Axis, init: Carry, xs: X, reverse=False, unroll=1): """ Scan over a named axis. Arrays that are not part of a named axis will have their 0th dim scanned over @@ -51,59 +28,27 @@ def scan(f: Callable[[Carry, X], Tuple[Carry, Y]], axis: Axis, init: Carry, xs: # but don't yet have the scanned axis as ones of `axes`, so we use _ScannedArrayResult that doesn't check # invariants until we're ready to create the result. - axis_first_xs = jax.tree_util.tree_map(partial(_ensure_first, axis), xs, is_leaf=is_named_array) + axis_first_xs = jax.tree_util.tree_map(_ensure_first(axis), xs, is_leaf=is_named_array) # now get a template of an element of "X" - x_elem = jax.tree_util.tree_map(partial(_select_0th, axis), axis_first_xs, is_leaf=is_named_array) + x_elem = jax.tree_util.tree_map(_select_0th(axis), axis_first_xs, is_leaf=is_named_array) x_elem_structure = jax.tree_util.tree_structure(x_elem) # now we can fold over the axis + @wraps(f) def wrapped_fn(carry, x): x = jax.tree_util.tree_unflatten(x_elem_structure, x) carry, y = f(carry, x) - y = jax.tree_util.tree_map(_chill_named_arrays, y, is_leaf=is_named_array) + y = jax.tree_util.tree_map(_pacify_named_arrays, y, is_leaf=is_named_array) return carry, y leaves = jax.tree_util.tree_leaves(axis_first_xs) carry, ys = lax.scan(wrapped_fn, init, leaves, reverse=reverse, unroll=unroll) - ys = jax.tree_util.tree_map(partial(_unchill_named_arrays, axis), ys, is_leaf=_is_chill_array) + ys = jax.tree_util.tree_map(_to_active_named_array(axis), ys, is_leaf=_is_passive_array) return carry, ys -def _is_chill_array(arr): - return isinstance(arr, _ScannedArrayResult) - - -def _unchill_named_arrays(axis, leaf): - if isinstance(leaf, _ScannedArrayResult): - return leaf.to_named_array(axis) - else: - return leaf - - -def _chill_named_arrays(leaf): - if isinstance(leaf, NamedArray): - return _ScannedArrayResult(leaf.array, leaf.axes) - else: - return leaf - - -def _select_0th(axis, leaf): - if isinstance(leaf, NamedArray): - return leaf.take(axis, 0) - else: - # other leaves don't matter - return leaf - - -def _ensure_first(axis, leaf): - if isinstance(leaf, NamedArray): - return leaf.rearrange((axis, ...)) - else: - return leaf - - def reduce( fn: Callable[[Carry, X], Carry], axis: Axis, init: Carry, xs: X, reverse: bool = False, unroll: int = 1 ) -> Carry: @@ -122,13 +67,14 @@ def reduce( # but don't yet have the scanned axis as ones of `axes`, so we use _ScannedArrayResult that doesn't check # invariants until we're ready to create the result. - axis_first_xs = jax.tree_util.tree_map(partial(_ensure_first, axis), xs, is_leaf=is_named_array) + axis_first_xs = jax.tree_util.tree_map(_ensure_first(axis), xs, is_leaf=is_named_array) # now get a template for where we fold over the axis in question - x_elem = jax.tree_util.tree_map(partial(_select_0th, axis), axis_first_xs, is_leaf=is_named_array) + x_elem = jax.tree_util.tree_map(_select_0th(axis), axis_first_xs, is_leaf=is_named_array) x_elem_structure = jax.tree_util.tree_structure(x_elem) # now we can fold over the axis + @wraps(fn) def wrapped_fn(carry, x): x = jax.tree_util.tree_unflatten(x_elem_structure, x) return fn(carry, x), None @@ -173,15 +119,15 @@ def vmap( if i in unmmapped_argnums: mapped_axes.append(None) else: - chilled_arg = jax.tree_util.tree_map(_chill_named_arrays, arg, is_leaf=is_named_array) + chilled_arg = jax.tree_util.tree_map(_pacify_named_arrays, arg, is_leaf=is_named_array) chilled_args.append(chilled_arg) - mapped_axis = jax.tree_util.tree_map(_index_of_batch_axis, chilled_arg, is_leaf=_is_chill_array) + mapped_axis = jax.tree_util.tree_map(_index_of_batch_axis, chilled_arg, is_leaf=_is_passive_array) mapped_axes.append(mapped_axis) def wrapped_fn(*args): - unchilled_args = jax.tree_util.tree_map(partial(_unchill_named_arrays, axis), args, is_leaf=is_named_array) + unchilled_args = jax.tree_util.tree_map(_to_active_named_array(axis), args, is_leaf=is_named_array) r = fn(*unchilled_args) - chilled = jax.tree_util.tree_map(_chill_named_arrays, r, is_leaf=is_named_array) + chilled = jax.tree_util.tree_map(_pacify_named_arrays, r, is_leaf=is_named_array) return chilled spmd_axis_name = physical_axis_name(axis) @@ -189,10 +135,85 @@ def vmap( result = jax.vmap( wrapped_fn, in_axes=mapped_axes, out_axes=0, axis_size=axis.size, spmd_axis_name=spmd_axis_name )(*args) - result = jax.tree_util.tree_map(partial(_unchill_named_arrays, axis), result, is_leaf=_is_chill_array) + result = jax.tree_util.tree_map(_to_active_named_array(axis), result, is_leaf=_is_passive_array) return result return wrapped_vmap_fn +@jax.tree_util.register_pytree_node_class +@dataclasses.dataclass(frozen=True) +class _PassiveNamedArray: + """For some higher-order jax manipulations, jax will insert/remove an axis at the beginning of the array (or + sometimes elsewhere). Jax doesn't know about our NamedArray wrapper, so we need a variant of NamedArray + that doesn't care about the axis names. This is that variant.This class is a 'chill' version of NamedArray + that doesn't check invariants until we're ready to create the result + + For example, with scan in NamedArray, we can't just have the scan tree prepend the scanned axis to the result, + because we don't have a way to feed it the name of the scanned axis. + """ + + array: jax.numpy.ndarray + main_axes: Tuple[Axis, ...] + + def as_scanned_result(self, scan_axis: Axis): + return NamedArray(self.array, (scan_axis,) + self.main_axes) + + def tree_flatten(self) -> Any: + return ((self.array,), self.main_axes) + + @classmethod + def tree_unflatten(cls, aux, tree: Any) -> Any: + assert len(tree) == 1 + return cls(tree[0], main_axes=aux) + + +def _is_passive_array(arr): + return isinstance(arr, _PassiveNamedArray) + + +def _to_active_named_array(leading_axis): + def to_active_named_array(leaf): + if isinstance(leaf, _PassiveNamedArray): + return leaf.as_scanned_result(leading_axis) + else: + return leaf + + return to_active_named_array + + +def _pacify_named_arrays(leaf): + if isinstance(leaf, NamedArray): + return _PassiveNamedArray(leaf.array, leaf.axes) + elif isinstance(leaf, _PassiveNamedArray): + assert False, "PassiveNamedArray should not be present in the tree" + else: + return leaf + + +def _select_0th(axis): + def select_0th(leaf): + if isinstance(leaf, NamedArray): + return leaf.take(axis, 0) + elif isinstance(leaf, _PassiveNamedArray): + assert False, "PassiveNamedArray should not be present in the tree" + else: + # other leaves don't matter + return leaf + + return select_0th + + +def _ensure_first(axis): + def ensure_first(leaf): + if isinstance(leaf, NamedArray): + return leaf.rearrange((axis, ...)) + elif isinstance(leaf, _PassiveNamedArray): + assert False, "PassiveNamedArray should not be present in the tree" + else: + return leaf + + return ensure_first + + __all__ = ["scan", "reduce", "vmap"] commit 76fc6f358f2e0c2dec6769fa5f2d5eab8b7327fa Date: 2022-09-19T14:23:34-07:00 factor out logic for rounding an axis size to fit partitioning diff --git a/src/haliax/partitioning.py b/src/haliax/partitioning.py index f0fd602..e3a3d9d 100644 --- a/src/haliax/partitioning.py +++ b/src/haliax/partitioning.py @@ -2,6 +2,7 @@ import contextlib import functools import threading import typing +from math import prod from typing import List, Mapping, Optional, Sequence, TypeVar, Union import jax @@ -174,12 +175,42 @@ def physical_axis_name(axis: Axis) -> Optional[PhysicalAxis]: return mapping.get(axis.name, None) +def physical_axis_size(axis: Axis) -> Optional[int]: + """Get the physical axis size for a logical axis. This is the product of the size of all physical axes + that this logical axis is mapped to.""" + # TODO: shouldn't be accessing this internal api, but... + from jax.experimental.maps import thread_resources + + try: + mesh_shape = thread_resources.env.shape + except AttributeError: + raise ValueError("No resource mapping found") + + name: Union[None, str, Sequence[str]] = physical_axis_name(axis) + if name is None: + return None + elif isinstance(name, str): + name = (name,) + + return prod([mesh_shape[n] for n in name]) + + def pspec_for_axis(axis: AxisSpec) -> PartitionSpec: """Get the PartitionSpec for a single axis""" axis = ensure_tuple(axis) return PartitionSpec(*(physical_axis_name(a) for a in axis)) +def round_axis_for_partitioning(axis: Axis) -> Axis: + """Round an axis so that it's divisible by the size of the partition it's on""" + size = physical_axis_size(axis) + if size is None: + return axis + else: + new_size = (axis.size + size - 1) // size * size + return Axis(axis.name, new_size) + + __all__ = [ "LogicalAxisName", "PhysicalAxis", commit e7bd2914f9096006936b3dc2397d4426f35b19a5 Date: 2022-09-20T14:55:26-07:00 refactor gradient accumulation and simplify data loading (#28) * add merging to resource_mapping * remove two properties we don't use from trainer config * make hax reductions be pytree aware. * introduce explicitly sharded gradient accumulation * tweak test * hoist the mean out of the compute_loss for training * ok looks like that was a bad idea... * cleanup diff --git a/src/haliax/__init__.py b/src/haliax/__init__.py index 014a096..06b56bf 100644 --- a/src/haliax/__init__.py +++ b/src/haliax/__init__.py @@ -23,6 +23,7 @@ from .core import ( ) from .hof import reduce, scan, vmap from .ops import trace, tril, triu, where +from .partitioning import axis_mapping, logically_sharded from .wrap import wrap_axiswise_call, wrap_elemwise_binary, wrap_elemwise_unary, wrap_reduction_call @@ -342,4 +343,6 @@ __all__ = [ "right_shift", "subtract", "true_divide", + "logically_sharded", + "axis_mapping", ] diff --git a/src/haliax/partitioning.py b/src/haliax/partitioning.py index e3a3d9d..1c2ab04 100644 --- a/src/haliax/partitioning.py +++ b/src/haliax/partitioning.py @@ -41,13 +41,17 @@ _mapping_holder = _ResourceMappingHolder() @contextlib.contextmanager -def axis_mapping(mapping: ResourceMapping, **kwargs): +def axis_mapping(mapping: ResourceMapping, *, merge: bool = True, **kwargs): """Context manager for setting the global resource mapping""" + mapping = dict(mapping) + + old_mapping = _mapping_holder.thread_data.resource_mapping + if merge: + mapping.update(old_mapping or {}) + if len(kwargs): - mapping = dict(mapping) mapping.update(kwargs) - old_mapping = _mapping_holder.thread_data.resource_mapping _mapping_holder.thread_data.resource_mapping = mapping yield _mapping_holder.thread_data.resource_mapping = old_mapping diff --git a/src/haliax/wrap.py b/src/haliax/wrap.py index 61f29eb..21df9ef 100644 --- a/src/haliax/wrap.py +++ b/src/haliax/wrap.py @@ -1,6 +1,7 @@ import functools from typing import Optional +import jax import jax.numpy as jnp from haliax.core import AxisSpec, NamedArray, _broadcast_order, broadcast_to @@ -30,30 +31,34 @@ def wrap_reduction_call(fn, single_axis_only: bool = False): if kwargs.get("keepdims", False): raise ValueError("keepdims is not supported for NamedArray") - if isinstance(a, NamedArray): - if axis is None: - result = fn(a.array, axis=None, **kwargs) - if jnp.isscalar(result): - return result + def reduce_one_leaf(a): + nonlocal axis + if isinstance(a, NamedArray): + if axis is None: + result = fn(a.array, axis=None, **kwargs) + if jnp.isscalar(result): + return result + else: + return NamedArray(result, ()) else: - return NamedArray(result, ()) + axis = ensure_tuple(axis) + if single_axis_only and len(axis) > 1: + raise ValueError(f"{fn.__name__} only supports a single axis") + indices = a._lookup_indices(axis) + if indices is None or any(x is None for x in indices): + raise ValueError(f"axis {axis} is not in {a.axes}") + new_axes = [ax for ax in a.axes if ax not in axis] + if single_axis_only: + result = fn(a.array, axis=indices[0], **kwargs) + else: + result = fn(a.array, axis=indices, **kwargs) + if jnp.isscalar(result): + return result + return NamedArray(result, tuple(new_axes)) else: - axis = ensure_tuple(axis) - if single_axis_only and len(axis) > 1: - raise ValueError(f"{fn.__name__} only supports a single axis") - indices = a._lookup_indices(axis) - if indices is None or any(x is None for x in indices): - raise ValueError(f"axis {axis} is not in {a.axes}") - new_axes = [ax for ax in a.axes if ax not in axis] - if single_axis_only: - result = fn(a.array, axis=indices[0], **kwargs) - else: - result = fn(a.array, axis=indices, **kwargs) - if jnp.isscalar(result): - return result - return NamedArray(result, tuple(new_axes)) - else: - return fn(a, axis=axis, **kwargs) + return fn(a, axis=axis, **kwargs) + + return jax.tree_util.tree_map(reduce_one_leaf, a, is_leaf=lambda x: isinstance(x, NamedArray)) wrapper.__doc__ = ( """ commit 0d8ac124873c84ef9eaa595813de1cd52ea9f597 Date: 2022-09-24T16:30:02-07:00 update to use jaxtyping instead of removed eqx aliases diff --git a/src/haliax/partitioning.py b/src/haliax/partitioning.py index 1c2ab04..f79b501 100644 --- a/src/haliax/partitioning.py +++ b/src/haliax/partitioning.py @@ -7,9 +7,9 @@ from typing import List, Mapping, Optional, Sequence, TypeVar, Union import jax from equinox import is_array -from equinox.custom_types import PyTree from jax.experimental.pjit import pjit, with_sharding_constraint from jax.interpreters.pxla import PartitionSpec +from jaxtyping import PyTree from .core import Axis, AxisSpec, NamedArray from .util import StringHolderEnum, ensure_tuple, is_named_array diff --git a/tests/test_partitioning.py b/tests/test_partitioning.py index 19be12d..a6fb117 100644 --- a/tests/test_partitioning.py +++ b/tests/test_partitioning.py @@ -2,9 +2,9 @@ import equinox as eqx import jax import jax.numpy as jnp import numpy as np -from equinox.custom_types import Array from jax.interpreters import pxla from jax.interpreters.pxla import PartitionSpec, Replicated, ShardedAxis +from jaxtyping import Array from utils import skip_if_not_enough_devices import haliax as hax commit 483a838801f4b04f2f099ea64e8ff686dcbdfc55 Date: 2022-10-05T15:56:50-07:00 use a.shape instead of jnp.shape because the latter sometimes doesn't do what we want with jax's weirdness diff --git a/src/haliax/core.py b/src/haliax/core.py index ee74eb6..b875379 100644 --- a/src/haliax/core.py +++ b/src/haliax/core.py @@ -634,7 +634,7 @@ def unflatten_axis(array: NamedArray, axis: Axis, new_axes: Sequence[Axis]) -> N def named(a: jnp.ndarray, axis: AxisSpec) -> NamedArray: """Creates a NamedArray from a numpy array and a list of axes""" if isinstance(axis, Axis): - if jnp.shape(a) != (axis.size,): + if a.shape != (axis.size,): raise ValueError(f"Shape of array {jnp.shape(a)} does not match size of axis {axis.size}") return NamedArray(a, (axis,)) else: commit 78cf556cdc2c6af696aa718c8d0f206926805e16 Date: 2022-10-05T16:14:43-07:00 generalize what we check for shape match diff --git a/src/haliax/core.py b/src/haliax/core.py index b875379..d31588d 100644 --- a/src/haliax/core.py +++ b/src/haliax/core.py @@ -7,10 +7,9 @@ from typing import Any, Dict, List, Mapping, Optional, Sequence, Tuple, Union, c import jax import jax.numpy as jnp import numpy as np -from jaxlib.xla_extension import DeviceArray import haliax -from haliax.util import ensure_tuple +from haliax.util import ensure_tuple, is_jax_array_like @dataclass(frozen=True) @@ -47,7 +46,7 @@ class NamedArray: if len(set(a.name for a in self.axes)) != len(self.axes): raise ValueError(f"Axes must be unique, but {self.axes} are not") - if isinstance(self.array, jax.core.Tracer) or isinstance(self.array, DeviceArray): + if is_jax_array_like(self.array): s = jnp.shape(self.array) if s != tuple(a.size for a in self.axes): raise ValueError(f"Shape of underlying array {s} does not match shape of axes {self.axes}") diff --git a/src/haliax/util.py b/src/haliax/util.py index 2c6376f..0e44160 100644 --- a/src/haliax/util.py +++ b/src/haliax/util.py @@ -19,6 +19,10 @@ def ensure_tuple(x: Union[Sequence[T], T]) -> Tuple[T, ...]: return (x,) +def is_jax_array_like(x): + return hasattr(x, "shape") and hasattr(x, "dtype") + + class StringHolderEnum(type): """Like a python enum but just holds string constants, as opposed to wrapped string constants""" commit 30c406e28d5a1ad12b5553e70fb107736a75cce1 Date: 2022-09-23T16:35:13-07:00 remove done todo diff --git a/src/haliax/hof.py b/src/haliax/hof.py index bce7019..9589ac2 100644 --- a/src/haliax/hof.py +++ b/src/haliax/hof.py @@ -105,7 +105,6 @@ def vmap( return None # TODO: do fancier things with kwargs and signature and such - # TODO: allow specifying spmd axis name and/or inferring it from resource_mapping # TODO: allow other axes to be mapped over # TODO: maybe implement equinox-style filtering vmap # TODO: tests to exercise this more commit c5fe6ed749d341a0203127ba37ea3a4ef00bf036 Date: 2022-10-05T10:10:15-07:00 use TensorStore for serialization, which will let us do distributed serialization diff --git a/requirements.txt b/requirements.txt index 4d36557..404f427 100644 --- a/requirements.txt +++ b/requirements.txt @@ -1,7 +1,6 @@ equinox transformers optax -einops wandb pyrallis pyarrow @@ -12,3 +11,4 @@ braceexpand git+https://github.com/deepmind/jmp#260e5ba01f46b10c579a61393e6c7e546aeae93e fsspec==2022.7.1 # pin this to make gcsfs happy furl +tensorstore commit 4603a895f6563c38ea659839f7f95799e98904f2 Date: 2022-09-26T13:31:31-07:00 rename logically_sharded -> auto_sharded diff --git a/src/haliax/__init__.py b/src/haliax/__init__.py index 06b56bf..ba56391 100644 --- a/src/haliax/__init__.py +++ b/src/haliax/__init__.py @@ -23,7 +23,7 @@ from .core import ( ) from .hof import reduce, scan, vmap from .ops import trace, tril, triu, where -from .partitioning import axis_mapping, logically_sharded +from .partitioning import auto_sharded, axis_mapping from .wrap import wrap_axiswise_call, wrap_elemwise_binary, wrap_elemwise_unary, wrap_reduction_call @@ -343,6 +343,6 @@ __all__ = [ "right_shift", "subtract", "true_divide", - "logically_sharded", + "auto_sharded", "axis_mapping", ] diff --git a/src/haliax/partitioning.py b/src/haliax/partitioning.py index f79b501..f837fe3 100644 --- a/src/haliax/partitioning.py +++ b/src/haliax/partitioning.py @@ -60,10 +60,10 @@ def axis_mapping(mapping: ResourceMapping, *, merge: bool = True, **kwargs): T = TypeVar("T", bound=PyTree) -def logically_sharded(x: T, logical_axes: Optional[PyTree] = None) -> T: +def auto_sharded(x: T) -> T: """ Shard a PyTree using the global resource mapping. NamedArrays in the PyTree are sharded using the resource mapping - and the names in the tree. Non-NamedArrays are sharded using the logical_axes argument, if provided. + and the names in the tree. If there is no global resource mapping, this function is a no-op. """ @@ -72,13 +72,22 @@ def logically_sharded(x: T, logical_axes: Optional[PyTree] = None) -> T: if mapping is None: return x - def _as_pspec(x, logical_axis=None): + return shard_with_resources(x, mapping) + + +def shard_with_resources(x: T, mapping: ResourceMapping) -> T: + """ + Shard a PyTree using the provided axis mapping. NamedArrays in the PyTree are sharded using the axis mapping. + Other arrays are not sharded. + + :param x: + :param mapping: + :return: + """ + + def _as_pspec(x): if isinstance(x, NamedArray): physical_names: List[Optional[PhysicalAxisSpec]] = [mapping.get(a.name, None) for a in x.axes] - elif logical_axis is not None: - physical_names: List[Optional[PhysicalAxisSpec]] = [ - mapping.get(a, None) for a in ensure_tuple(logical_axis) - ] elif is_array(x): physical_names = [None] * len(x.shape) else: @@ -89,12 +98,7 @@ def logically_sharded(x: T, logical_axes: Optional[PyTree] = None) -> T: ) return spec - if logical_axes is None: - # TODO: support logical_axes as a tree prefix. jax doesn't seem to have a good utility for this. - pspec = jax.tree_util.tree_map(_as_pspec, x, is_leaf=is_named_array) - else: - pspec = jax.tree_util.tree_map(_as_pspec, x, logical_axes, is_leaf=is_named_array) - + pspec = jax.tree_util.tree_map(_as_pspec, x, is_leaf=is_named_array) return with_sharding_constraint(x, pspec) @@ -222,7 +226,7 @@ __all__ = [ "ResourceAxis", "ResourceMapping", "axis_mapping", - "logically_sharded", + "auto_sharded", "infer_resource_partitions", "eval_resource_partitions", "named_pjit_init", commit f2ba4895203aa9f48c3e702038863c527e44ff13 Date: 2022-10-05T20:34:48-07:00 ZeRO-style parameter and gradient partitioning Introduces ZeRO-style parameter and gradient partitioning using accumulate_gradients_sharded and pjit diff --git a/src/haliax/partitioning.py b/src/haliax/partitioning.py index f837fe3..ac002c6 100644 --- a/src/haliax/partitioning.py +++ b/src/haliax/partitioning.py @@ -62,20 +62,20 @@ T = TypeVar("T", bound=PyTree) def auto_sharded(x: T) -> T: """ - Shard a PyTree using the global resource mapping. NamedArrays in the PyTree are sharded using the resource mapping + Shard a PyTree using the global axis mapping. NamedArrays in the PyTree are sharded using the axis mapping and the names in the tree. - If there is no global resource mapping, this function is a no-op. + If there is no axis mapping, the global axis mapping, this function is a no-op. """ mapping = _mapping_holder.thread_data.resource_mapping if mapping is None: return x - return shard_with_resources(x, mapping) + return shard_with_axis_mapping(x, mapping) -def shard_with_resources(x: T, mapping: ResourceMapping) -> T: +def shard_with_axis_mapping(x: T, mapping: ResourceMapping) -> T: """ Shard a PyTree using the provided axis mapping. NamedArrays in the PyTree are sharded using the axis mapping. Other arrays are not sharded. @@ -102,30 +102,31 @@ def shard_with_resources(x: T, mapping: ResourceMapping) -> T: return with_sharding_constraint(x, pspec) -def infer_resource_partitions(tree: PyTree) -> PyTree: +def infer_resource_partitions(tree: PyTree, resource_mapping: Optional[ResourceMapping] = None) -> PyTree: """ Infer the resource partitions for a module, to be used with pjit. The basic idea is to tree all NamedArrays as leaves for the purposes of this function, - and to create PartitionSpecs from those names plus the contextual resource_mapping. - """ - - def named_array_is_leaf(x): - return isinstance(x, NamedArray) + and to create PartitionSpecs from those names plus the resource_mapping. - axis_resources = _mapping_holder.thread_data.resource_mapping + If resource_mapping is not provided, this function attempts to use the global resource mapping. + """ + if resource_mapping is None: + resource_mapping = _mapping_holder.thread_data.resource_mapping - if axis_resources is None: + if resource_mapping is None: raise ValueError("No resource mapping found") + _resource_mapping = typing.cast(ResourceMapping, resource_mapping) # for mypy + def partition_spec(node: typing.Any): if isinstance(node, NamedArray): return NamedArray( - PartitionSpec(*tuple(axis_resources.get(axis.name, None) for axis in node.axes)), node.axes + PartitionSpec(*tuple(_resource_mapping.get(axis.name, None) for axis in node.axes)), node.axes ) else: return None - return jax.tree_util.tree_map(partition_spec, tree, is_leaf=named_array_is_leaf) + return jax.tree_util.tree_map(partition_spec, tree, is_leaf=is_named_array) def eval_resource_partitions(fn): commit d54cca2fc0ca4c650e2da44fa30d5786af14a7ea Date: 2022-10-06T16:43:28-07:00 Tweak grad accumulation, fix random initialization when doing large models to shard over largest physical axis size (#30) * log model resources * log sharding info too to figure out what's going on * let's try this less fancy version of grad accumulation? * just double check this? * add zero3 to 7b * tweaks to randomness to improve how it works on gpt7b * set config for 7b to best known values diff --git a/src/haliax/random.py b/src/haliax/random.py index 3d0db1a..32d1526 100644 --- a/src/haliax/random.py +++ b/src/haliax/random.py @@ -11,7 +11,7 @@ import jax.random as jrandom from haliax.core import Axis, NamedArray from haliax.util import ensure_tuple, named_call -from .partitioning import pspec_for_axis +from .partitioning import pspec_for_axis, auto_sharded, physical_axis_size def _wrap_random_function(func): @@ -42,14 +42,14 @@ def _wrap_random_function(func): # vmap hopefully only generate the random numbers for the local shard. # # However, we don't want to oversplit or it kind of ruins the whole point since we have to split the key on - # every node... So instead we just split along the *largest* axis that is sharded + # every node... So instead we just split along the *largest* physical axis # TODO: we won't need to do this when they add better splitting for random numbers # (froystig is maybe going to do this?) # what we do is we take the biggest axis that is sharded and split on it, ties going to the first axis pspec = pspec_for_axis(orig_shape) if pspec: - biggest_axis, biggest_physical = max(zip(orig_shape, pspec), key=lambda x: x[0].size if x[1] else 0) + biggest_axis, biggest_physical = max(zip(orig_shape, pspec), key=lambda x: (physical_axis_size(x[0]) or 0) if x[1] else 0) else: biggest_axis = biggest_physical = None commit 98a2ff3858ded2334a9f69c448bbfd5ffb25c61c Date: 2022-08-04T23:25:15-07:00 update to new equinox diff --git a/src/haliax/partitioning.py b/src/haliax/partitioning.py index 4ae81a4..405fa7a 100644 --- a/src/haliax/partitioning.py +++ b/src/haliax/partitioning.py @@ -6,9 +6,9 @@ from typing import List, Mapping, Optional, Sequence, TypeVar, Union import jax from equinox import is_array -from equinox.custom_types import PyTree from jax.experimental.pjit import pjit, with_sharding_constraint from jax.interpreters.pxla import PartitionSpec +from jaxtyping import PyTree from .core import NamedArray from .util import StringHolderEnum, ensure_tuple, is_named_array commit 273bb404b2370488e1efad99aaa9159291717ca0 Date: 2022-10-07T16:07:11-07:00 fix test_partitioning.py imports diff --git a/tests/test_partitioning.py b/tests/test_partitioning.py index 19be12d..a6fb117 100644 --- a/tests/test_partitioning.py +++ b/tests/test_partitioning.py @@ -2,9 +2,9 @@ import equinox as eqx import jax import jax.numpy as jnp import numpy as np -from equinox.custom_types import Array from jax.interpreters import pxla from jax.interpreters.pxla import PartitionSpec, Replicated, ShardedAxis +from jaxtyping import Array from utils import skip_if_not_enough_devices import haliax as hax commit 41cad4fdc1e22c5c871d5b4e49ba823202e41618 Date: 2022-10-08T00:12:09-07:00 improve named_pjit to make it fully eqx-like, and use it for all uses of pjit in gpt2_example (#31) * improve named_pjit to make it fully equinox-like, and use it for all uses of pjit in gpt2_example * fix test with removal of named_pjit_init * remove frozendict since we didn't use it * remove inadvertent log_compiles diff --git a/src/haliax/jax_utils.py b/src/haliax/jax_utils.py index 0555270..dba5af8 100644 --- a/src/haliax/jax_utils.py +++ b/src/haliax/jax_utils.py @@ -1,10 +1,16 @@ -from typing import Optional, Sequence, Union +import functools as ft +from typing import Callable, Optional, Sequence, Union +import equinox as eqx +import jax import numpy as np from chex import PRNGKey +from equinox.compile_utils import Static from jax import numpy as jnp from jax import random as jrandom +from haliax.util import is_jax_array_like + def shaped_rng_split(key, split_shape: Union[int, Sequence[int]] = 2) -> jrandom.KeyArray: if isinstance(split_shape, int): @@ -30,3 +36,20 @@ def maybe_rng_split(key: Optional[PRNGKey], num: int = 2): return jnp.reshape(key, (1,) + key.shape) else: return jrandom.split(key, num) + + +def filter_eval_shape(fun: Callable, *args, **kwargs): + """As `jax.eval_shape`, but allows any Python object as inputs and outputs, including + GlobalDeviceArrays (which equinox.filter_eval_shape does not support). + """ + # TODO: file a bug + + def _fn(_static, _dynamic): + _args, _kwargs = eqx.combine(_static, _dynamic) + _out = fun(*_args, **_kwargs) + _dynamic_out, _static_out = eqx.partition(_out, is_jax_array_like) + return _dynamic_out, Static(_static_out) + + dynamic, static = eqx.partition((args, kwargs), is_jax_array_like) + dynamic_out, static_out = jax.eval_shape(ft.partial(_fn, static), dynamic) + return eqx.combine(dynamic_out, static_out.value) diff --git a/src/haliax/partitioning.py b/src/haliax/partitioning.py index ac002c6..dc0e827 100644 --- a/src/haliax/partitioning.py +++ b/src/haliax/partitioning.py @@ -5,14 +5,18 @@ import typing from math import prod from typing import List, Mapping, Optional, Sequence, TypeVar, Union +import equinox as eqx import jax from equinox import is_array -from jax.experimental.pjit import pjit, with_sharding_constraint +from equinox.compile_utils import compile_cache, get_fun_names, hashable_combine, hashable_partition +from jax.experimental.global_device_array import GlobalDeviceArray +from jax.experimental.pjit import FROM_GDA, pjit, with_sharding_constraint from jax.interpreters.pxla import PartitionSpec from jaxtyping import PyTree from .core import Axis, AxisSpec, NamedArray -from .util import StringHolderEnum, ensure_tuple, is_named_array +from .jax_utils import filter_eval_shape +from .util import StringHolderEnum, ensure_tuple, is_jax_array_like, is_named_array LogicalAxisName = str @@ -123,6 +127,9 @@ def infer_resource_partitions(tree: PyTree, resource_mapping: Optional[ResourceM return NamedArray( PartitionSpec(*tuple(_resource_mapping.get(axis.name, None) for axis in node.axes)), node.axes ) + elif isinstance(node, GlobalDeviceArray): + return FROM_GDA + # TODO: jax.Array else: return None @@ -141,39 +148,139 @@ def eval_resource_partitions(fn): return f -def named_pjit_init(cls: typing.Type[T], **pjit_args): - """Uses NamedArrays to infer the resource partitions for a module when creating it""" +# This is more or less copy-pasted from Equinox's similar functions (pmap, vmap, etc), but +# it's not really explained there so we'll explain it here. +# Many jax functions work by compiling functions to XLA. The compilation process is expensive, +# so we want to cache the compiled functions. However, the compiled functions are tied to the +# "static" arguments to the functions. This is particularly important for a library like Equinox, +# which Haliax is built on top of, because Equinox uses pytrees extensively for modules, and mixes "static" +# configuration with "dynamic" data. +# Thus we need to carefully partition the arguments to the function into "static" and "dynamic" arguments, +# and cache our compiled functions based on the static arguments. +# In Equinox conceptually there are three types of "arguments": positional, named, and the function itself. +# All of these are pytrees, and we need to partition them into static and dynamic arguments. +# Inside the function, we then combine the arguments into a single pytree, and pass that to the original function. +# With pjit we also have "donated" arguments, which are arguments that we promise not to use after the function +# returns. This is useful for conserving memory, but we also have to splice them back in. +# Also recall that a "pytree" can split into leaves and a "treedef", which can then be reconstructed. +@compile_cache +def _named_pjit_cache(fun_names, **jitkwargs): + def fun_wrapped(dynamic_donated, dynamic_reserved, static): + dynamic = eqx.combine(dynamic_donated, dynamic_reserved) + dynamic_fun, dynamic_spec = dynamic + + ( + static_fun_treedef, + static_fun_leaves, + static_spec_treedef, + static_spec_leaves, + ) = static + + fun = hashable_combine(dynamic_fun, static_fun_leaves, static_fun_treedef) + args, kwargs = hashable_combine(dynamic_spec, static_spec_leaves, static_spec_treedef) + out = fun(*args, **kwargs) + return out + + fun_name, fun_qualname = fun_names + fun_wrapped.__name__ = fun_name + fun_wrapped.__qualname__ = fun_qualname + + return pjit(fun_wrapped, static_argnums=2, donate_argnums=0, **jitkwargs) + + +def named_pjit( + fn=None, + axis_resources: Optional[ResourceMapping] = None, + *, + in_axis_resources: Optional[ResourceMapping] = None, + out_axis_resources: Optional[ResourceMapping] = None, + donate_args: Optional[PyTree] = None, + donate_kwargs: Optional[PyTree] = None, + **pjit_args, +): + """ + A version of pjit that uses NamedArrays, GlobalDeviceArrays, and the provided resource mapping to infer the + resource partitions. + + If no resource mapping is provided, this function attempts to use the global resource mapping. + If either of in_axis_resources or out_axis_resources is provided, then both must be provided. + If axis_resources is provided, then in_axis_resources and out_axis_resources must not be provided. + + :param fn: The function to be pjit'd + :param axis_resources: A mapping from logical axis names to physical axis names + :param in_axis_resources: A mapping from logical axis names to physical axis names for the input + :param out_axis_resources: A mapping from logical axis names to physical axis names for the output + :param donate_args: A PyTree of booleans or function leaf->bool, indicating whether to donate arguments to the + computation + :param donate_kwargs: A PyTree of booleans or function leaf->bool, indicating whether to donate keyword arguments to + the computation + """ + # TODO: support jax.Array - @functools.wraps(cls.__new__) - def init(*args, **kwargs): - inst = cls(*args, **kwargs) - return inst + if in_axis_resources is not None or out_axis_resources is not None: + if axis_resources is not None: + raise ValueError("Cannot provide both axis_resources and in_axis_resources/out_axis_resources") + if in_axis_resources is None or out_axis_resources is None: + raise ValueError("Must provide both in_axis_resources and out_axis_resources") - return named_pjit(init, **pjit_args) + if fn is None: + return functools.partial( + named_pjit, + axis_resources=axis_resources, + in_axis_resources=in_axis_resources, + out_axis_resources=out_axis_resources, + donate_args=donate_args, + donate_kwargs=donate_kwargs, + **pjit_args, + ) + if axis_resources is None and in_axis_resources is None: + axis_resources = _mapping_holder.thread_data.resource_mapping -def named_pjit(fn=None, **pjit_args): - """ - Uses NamedArrays to infer the resource partitions for calling a function - """ + if axis_resources is not None: + in_axis_resources = axis_resources + out_axis_resources = axis_resources - if fn is None: - return functools.partial(named_pjit, **pjit_args) + if in_axis_resources is None or out_axis_resources is None: + raise ValueError( + "Must provide in_axis_resources and out_axis_resources, or axis_resources, or have a global " + "mapping vis axis_mapping" + ) + + dynamic_fun, static_fun_leaves, static_fun_def = hashable_partition(fn, is_jax_array_like) @functools.wraps(fn) def f(*args, **kwargs): - in_resources = infer_resource_partitions((args, kwargs)) - shapes = jax.eval_shape(fn, *args, **kwargs) - out_resources = infer_resource_partitions(shapes) + dynamic_argspec, static_argspec, static_arg_def = hashable_partition((args, kwargs), is_jax_array_like) + dynamic = (dynamic_fun, dynamic_argspec) - @functools.wraps(fn) - def fn_to_call(args, kwargs): - return fn(*args, **kwargs) + if donate_args is not None or donate_kwargs is not None: + dargs = donate_args or (False,) * len(args) + dkwargs = donate_kwargs or {k: False for k in kwargs} + dynamic_donated, dynamic_reserved = eqx.partition(dynamic, (False, (dargs, dkwargs))) + else: + dynamic_donated = jax.tree_util.tree_map(lambda _: None, dynamic) + dynamic_reserved = dynamic + + static = ( + static_fun_def, + static_fun_leaves, + static_arg_def, + static_argspec, + ) - return pjit(fn_to_call, in_resources, out_resources, **pjit_args)(args, kwargs) + in_resources = infer_resource_partitions((dynamic_donated, dynamic_reserved), in_axis_resources) + shapes = filter_eval_shape(fn, *args, **kwargs) + out_resources = infer_resource_partitions(shapes, out_axis_resources) - return f + my_pjit_args = dict(**pjit_args) + my_pjit_args["in_axis_resources"] = in_resources + my_pjit_args["out_axis_resources"] = out_resources + cached_pjitted_fun = _named_pjit_cache(get_fun_names(fn), **my_pjit_args) + + return cached_pjitted_fun(dynamic_donated, dynamic_reserved, static) + return f def physical_axis_name(axis: Axis) -> Optional[PhysicalAxis]: """Get the physical axis name for a logical axis""" @@ -230,8 +337,8 @@ __all__ = [ "auto_sharded", "infer_resource_partitions", "eval_resource_partitions", - "named_pjit_init", "named_pjit", "physical_axis_name", "pspec_for_axis", + "round_axis_for_partitioning", ] diff --git a/tests/test_partitioning.py b/tests/test_partitioning.py index a6fb117..2175e4a 100644 --- a/tests/test_partitioning.py +++ b/tests/test_partitioning.py @@ -9,7 +9,7 @@ from utils import skip_if_not_enough_devices import haliax as hax from haliax import Axis, NamedArray -from haliax.partitioning import ResourceAxis, axis_mapping, infer_resource_partitions, named_pjit_init +from haliax.partitioning import ResourceAxis, axis_mapping, infer_resource_partitions, named_pjit class MyModule(eqx.Module): @@ -56,7 +56,7 @@ def test_pjit_class_init(): with axis_mapping(resource_map): devices = jax.devices() with pxla.Mesh(np.array(devices).reshape(-1, 2), (ResourceAxis.DATA, ResourceAxis.MODEL)): - mod = named_pjit_init(MyModuleInit)() + mod = named_pjit(MyModuleInit)() assert mod.named.array.shape == (Dim2.size, Dim3.size) assert mod.named.array.sharding_spec.mesh_mapping == ( @@ -88,7 +88,7 @@ def test_pjit_class_nested_init(): devices = jax.devices() with pxla.Mesh(np.array(devices).reshape(-1, 2), (ResourceAxis.DATA, ResourceAxis.MODEL)): - mod2 = named_pjit_init(Mod2)() + mod2 = named_pjit(Mod2)() mod = mod2.inner assert mod.named.array.shape == (Dim2.size, Dim3.size) @@ -109,7 +109,7 @@ def test_pjit_class_init_with_args(): devices = jax.devices() with pxla.Mesh(np.array(devices).reshape(-1, 1), (ResourceAxis.DATA, ResourceAxis.MODEL)): - mod = named_pjit_init(ModWithArgs)(hax.ones((Dim1, Dim2))) + mod = named_pjit(ModWithArgs)(hax.ones((Dim1, Dim2))) assert isinstance(mod, ModWithArgs) assert mod.array.array.shape == (Dim1.size, Dim2.size) assert mod.array2.array.shape == (Dim3.size,) commit 1ebc8cd37d2575f5b582a83162ec63bc0056fc35 Date: 2022-10-08T00:19:43-07:00 fix issue when using GDAs with model_axis_size==1 (#32) diff --git a/src/haliax/partitioning.py b/src/haliax/partitioning.py index dc0e827..24cc645 100644 --- a/src/haliax/partitioning.py +++ b/src/haliax/partitioning.py @@ -124,9 +124,14 @@ def infer_resource_partitions(tree: PyTree, resource_mapping: Optional[ResourceM def partition_spec(node: typing.Any): if isinstance(node, NamedArray): - return NamedArray( - PartitionSpec(*tuple(_resource_mapping.get(axis.name, None) for axis in node.axes)), node.axes - ) + if isinstance(node.array, GlobalDeviceArray): + # TODO: should probably check for compatibility + return FROM_GDA + else: + return NamedArray( + PartitionSpec(*tuple(_resource_mapping.get(axis.name, None) for axis in node.axes)), # type: ignore + node.axes, + ) elif isinstance(node, GlobalDeviceArray): return FROM_GDA # TODO: jax.Array @@ -282,6 +287,7 @@ def named_pjit( return f + def physical_axis_name(axis: Axis) -> Optional[PhysicalAxis]: """Get the physical axis name for a logical axis""" mapping = _mapping_holder.thread_data.resource_mapping diff --git a/tests/test_partitioning.py b/tests/test_partitioning.py index 2175e4a..f603b26 100644 --- a/tests/test_partitioning.py +++ b/tests/test_partitioning.py @@ -113,3 +113,28 @@ def test_pjit_class_init_with_args(): assert isinstance(mod, ModWithArgs) assert mod.array.array.shape == (Dim1.size, Dim2.size) assert mod.array2.array.shape == (Dim3.size,) + + +def test_infer_resource_partition_gda_bug(): + devices = jax.devices() + with pxla.Mesh(np.array(devices).reshape(-1, 1), (ResourceAxis.DATA, ResourceAxis.MODEL)): + jax.config.update("jax_parallel_functions_output_gda", True) + try: + + def foo(): + return hax.zeros((Dim1, Dim2, Dim3)) + + pjit_foo = named_pjit(foo, resource_map) + r = pjit_foo() + assert r.axes == (Dim1, Dim2, Dim3) + + def bar(x): + return x + + # this won't work with GDAs + pjit_bar = named_pjit(bar, resource_map) + r = pjit_bar(r) + assert r.axes == (Dim1, Dim2, Dim3) + + finally: + jax.config.update("jax_parallel_functions_output_gda", False) commit 230a74547a02087b1ee708b5949d7d03df337ae2 Date: 2022-10-11T13:47:47-07:00 Merge branch 'stable_v1' commit 0aef8012ec314594792e45375d6fdc7b2e63be2a Date: 2022-10-13T12:08:19-07:00 clean up zero-y grad accum a bit, Fix major perf regression in named_pjit (#36) * pretty sure this is more like fsdp? * see if we can fix weird regression * ok so this part fixes * wip diagnosing what's going on with perf regression * fix significant perf issue with named_pjit * fix parameter counts with gda (again?!?) * clean up gpt2_example back to how it should be * bring back the fsdp-y * remove unneeded debugging method diff --git a/src/haliax/hof.py b/src/haliax/hof.py index 9589ac2..79d6d8a 100644 --- a/src/haliax/hof.py +++ b/src/haliax/hof.py @@ -7,7 +7,7 @@ import jax import jax.lax as lax from .core import Axis, NamedArray -from .partitioning import physical_axis_name +from .partitioning import auto_sharded, physical_axis_name from .util import ensure_tuple, is_named_array @@ -38,8 +38,10 @@ def scan(f: Callable[[Carry, X], Tuple[Carry, Y]], axis: Axis, init: Carry, xs: @wraps(f) def wrapped_fn(carry, x): x = jax.tree_util.tree_unflatten(x_elem_structure, x) + x = auto_sharded(x) carry, y = f(carry, x) y = jax.tree_util.tree_map(_pacify_named_arrays, y, is_leaf=is_named_array) + y = auto_sharded(y) return carry, y leaves = jax.tree_util.tree_leaves(axis_first_xs) @@ -63,10 +65,6 @@ def reduce( # This implementation is a bit tricky. # First we have to hoist the axis we're scanning over to the front of the array. # Then we have to scan over the 0th dim of the arrays (as flattened non-pytrees) - # We have to be careful that we don't try to create NamedArrays that have the shape of the scanned result - # but don't yet have the scanned axis as ones of `axes`, so we use _ScannedArrayResult that doesn't check - # invariants until we're ready to create the result. - axis_first_xs = jax.tree_util.tree_map(_ensure_first(axis), xs, is_leaf=is_named_array) # now get a template for where we fold over the axis in question @@ -77,6 +75,7 @@ def reduce( @wraps(fn) def wrapped_fn(carry, x): x = jax.tree_util.tree_unflatten(x_elem_structure, x) + x = auto_sharded(x) return fn(carry, x), None leaves = jax.tree_util.tree_leaves(axis_first_xs) diff --git a/src/haliax/partitioning.py b/src/haliax/partitioning.py index 24cc645..1d5e604 100644 --- a/src/haliax/partitioning.py +++ b/src/haliax/partitioning.py @@ -124,14 +124,14 @@ def infer_resource_partitions(tree: PyTree, resource_mapping: Optional[ResourceM def partition_spec(node: typing.Any): if isinstance(node, NamedArray): - if isinstance(node.array, GlobalDeviceArray): - # TODO: should probably check for compatibility - return FROM_GDA - else: - return NamedArray( - PartitionSpec(*tuple(_resource_mapping.get(axis.name, None) for axis in node.axes)), # type: ignore - node.axes, - ) + # if isinstance(node.array, GlobalDeviceArray): + # TODO: should probably check for compatibility + # return FROM_GDA + # else: + return NamedArray( + PartitionSpec(*tuple(_resource_mapping.get(axis.name, None) for axis in node.axes)), # type: ignore + node.axes, + ) elif isinstance(node, GlobalDeviceArray): return FROM_GDA # TODO: jax.Array @@ -141,58 +141,6 @@ def infer_resource_partitions(tree: PyTree, resource_mapping: Optional[ResourceM return jax.tree_util.tree_map(partition_spec, tree, is_leaf=is_named_array) -def eval_resource_partitions(fn): - """ - Similar to jax.eval_shape but for resource partitions. It returns a PyTree of PartitionSpecs. - """ - - def f(*args, **kwargs): - out_shape = jax.eval_shape(fn, *args, **kwargs) - return infer_resource_partitions(out_shape) - - return f - - -# This is more or less copy-pasted from Equinox's similar functions (pmap, vmap, etc), but -# it's not really explained there so we'll explain it here. -# Many jax functions work by compiling functions to XLA. The compilation process is expensive, -# so we want to cache the compiled functions. However, the compiled functions are tied to the -# "static" arguments to the functions. This is particularly important for a library like Equinox, -# which Haliax is built on top of, because Equinox uses pytrees extensively for modules, and mixes "static" -# configuration with "dynamic" data. -# Thus we need to carefully partition the arguments to the function into "static" and "dynamic" arguments, -# and cache our compiled functions based on the static arguments. -# In Equinox conceptually there are three types of "arguments": positional, named, and the function itself. -# All of these are pytrees, and we need to partition them into static and dynamic arguments. -# Inside the function, we then combine the arguments into a single pytree, and pass that to the original function. -# With pjit we also have "donated" arguments, which are arguments that we promise not to use after the function -# returns. This is useful for conserving memory, but we also have to splice them back in. -# Also recall that a "pytree" can split into leaves and a "treedef", which can then be reconstructed. -@compile_cache -def _named_pjit_cache(fun_names, **jitkwargs): - def fun_wrapped(dynamic_donated, dynamic_reserved, static): - dynamic = eqx.combine(dynamic_donated, dynamic_reserved) - dynamic_fun, dynamic_spec = dynamic - - ( - static_fun_treedef, - static_fun_leaves, - static_spec_treedef, - static_spec_leaves, - ) = static - - fun = hashable_combine(dynamic_fun, static_fun_leaves, static_fun_treedef) - args, kwargs = hashable_combine(dynamic_spec, static_spec_leaves, static_spec_treedef) - out = fun(*args, **kwargs) - return out - - fun_name, fun_qualname = fun_names - fun_wrapped.__name__ = fun_name - fun_wrapped.__qualname__ = fun_qualname - - return pjit(fun_wrapped, static_argnums=2, donate_argnums=0, **jitkwargs) - - def named_pjit( fn=None, axis_resources: Optional[ResourceMapping] = None, @@ -274,9 +222,9 @@ def named_pjit( static_argspec, ) + output_shape = _cached_filter_eval_shape(fn, *args, **kwargs) in_resources = infer_resource_partitions((dynamic_donated, dynamic_reserved), in_axis_resources) - shapes = filter_eval_shape(fn, *args, **kwargs) - out_resources = infer_resource_partitions(shapes, out_axis_resources) + out_resources = infer_resource_partitions(output_shape, out_axis_resources) my_pjit_args = dict(**pjit_args) my_pjit_args["in_axis_resources"] = in_resources @@ -288,8 +236,65 @@ def named_pjit( return f +# This is more or less copy-pasted from Equinox's similar functions (pmap, vmap, etc), but +# it's not really explained there so we'll explain it here. +# Many jax functions work by compiling functions to XLA. The compilation process is expensive, +# so we want to cache the compiled functions. However, the compiled functions are tied to the +# "static" arguments to the functions. This is particularly important for a library like Equinox, +# which Haliax is built on top of, because Equinox uses pytrees extensively for modules, and mixes "static" +# configuration with "dynamic" data. +# Thus we need to carefully partition the arguments to the function into "static" and "dynamic" arguments, +# and cache our compiled functions based on the static arguments. +# In Equinox conceptually there are three types of "arguments": positional, named, and the function itself. +# All of these are pytrees, and we need to partition them into static and dynamic arguments. +# Inside the function, we then combine the arguments into a single pytree, and pass that to the original function. +# With pjit we also have "donated" arguments, which are arguments that we promise not to use after the function +# returns. This is useful for conserving memory, but we also have to splice them back in. +# Also recall that a "pytree" can split into leaves and a "treedef", which can then be reconstructed. +@compile_cache +def _named_pjit_cache(fun_names, **jitkwargs): + def fun_wrapped(dynamic_donated, dynamic_reserved, static): + dynamic = eqx.combine(dynamic_donated, dynamic_reserved) + dynamic_fun, dynamic_spec = dynamic + + ( + static_fun_treedef, + static_fun_leaves, + static_spec_treedef, + static_spec_leaves, + ) = static + + fun = hashable_combine(dynamic_fun, static_fun_leaves, static_fun_treedef) + args, kwargs = hashable_combine(dynamic_spec, static_spec_leaves, static_spec_treedef) + out = fun(*args, **kwargs) + return out + + fun_name, fun_qualname = fun_names + fun_wrapped.__name__ = fun_name + fun_wrapped.__qualname__ = fun_qualname + + return pjit(fun_wrapped, donate_argnums=0, static_argnums=2, **jitkwargs) + + +_eval_shape_cache = {} + + +def _cached_filter_eval_shape(fun, *args, **kwargs): + """ + eval_shape is surprisingly expensive, so we cache it. We use this for named_pjit for evaluating resource partitions + of the output. + """ + dynamic, static, treedef = hashable_partition((fun, args, kwargs), is_jax_array_like) + key = (static, treedef) + + if key not in _eval_shape_cache: + _eval_shape_cache[key] = filter_eval_shape(fun, *args, **kwargs) + + return _eval_shape_cache[key] + + def physical_axis_name(axis: Axis) -> Optional[PhysicalAxis]: - """Get the physical axis name for a logical axis""" + """Get the physical axis name for a logical axis from the global mapping. Returns none if the axis is not mapped.""" mapping = _mapping_holder.thread_data.resource_mapping if mapping is None: return None @@ -342,7 +347,6 @@ __all__ = [ "axis_mapping", "auto_sharded", "infer_resource_partitions", - "eval_resource_partitions", "named_pjit", "physical_axis_name", "pspec_for_axis", commit 0a6f6a91597aec9d726a29968dc643ee15ea9577 Date: 2022-10-19T15:22:10-07:00 refactor haliax.vmap to be more equinox-like, support static args by … (#39) * refactor haliax.vmap to be more equinox-like, support static args by default, etc. * add a bunch of comments b/c the code is less than clear diff --git a/src/haliax/core.py b/src/haliax/core.py index d31588d..d25ae05 100644 --- a/src/haliax/core.py +++ b/src/haliax/core.py @@ -9,7 +9,8 @@ import jax.numpy as jnp import numpy as np import haliax -from haliax.util import ensure_tuple, is_jax_array_like +from haliax.jax_utils import is_jax_array_like +from haliax.util import ensure_tuple @dataclass(frozen=True) diff --git a/src/haliax/hof.py b/src/haliax/hof.py index 79d6d8a..fe8b189 100644 --- a/src/haliax/hof.py +++ b/src/haliax/hof.py @@ -1,14 +1,16 @@ import dataclasses +import inspect from functools import wraps -from typing import Any, Callable, Sequence, Tuple, TypeVar, Union +from typing import Any, Callable, Tuple, TypeVar, Union -import equinox import jax import jax.lax as lax +from jaxtyping import PyTree from .core import Axis, NamedArray +from .jax_utils import broadcast_prefix, is_jax_array_like from .partitioning import auto_sharded, physical_axis_name -from .util import ensure_tuple, is_named_array +from .util import is_named_array Carry = TypeVar("Carry") @@ -46,7 +48,7 @@ def scan(f: Callable[[Carry, X], Tuple[Carry, Y]], axis: Axis, init: Carry, xs: leaves = jax.tree_util.tree_leaves(axis_first_xs) carry, ys = lax.scan(wrapped_fn, init, leaves, reverse=reverse, unroll=unroll) - ys = jax.tree_util.tree_map(_to_active_named_array(axis), ys, is_leaf=_is_passive_array) + ys = jax.tree_util.tree_map(_prepend_named_batch_axis(axis), ys, is_leaf=_is_passive_array) return carry, ys @@ -84,56 +86,128 @@ def reduce( return carry +ResolvedUnnamedAxisSpec = Union[int, None] +UnnamedAxisSpec = Union[ResolvedUnnamedAxisSpec, Callable[[Any], ResolvedUnnamedAxisSpec]] + + +def _zero_if_array_else_none(x: Any) -> ResolvedUnnamedAxisSpec: + return 0 if is_jax_array_like(x) else None + + def vmap( fn, axis: Axis, - unmapped_argnums: Union[int, Sequence[int]] = (), + *, + default: PyTree[UnnamedAxisSpec] = _zero_if_array_else_none, + args: PyTree[UnnamedAxisSpec] = (), + kwargs: PyTree[UnnamedAxisSpec] = None, ): """ - NamedArray aware version of jax.vmap. Normal arrays are mapped over the 0th axis. - unmapped_argnums are the argnums of the function that are not batched over the axis. + NamedArray aware version of jax.vmap. Normal arrays are mapped according to the specs as in equinox.filter_vmap, + except that the output axis is always 0 b/c it's annoying to make anything else work + + Because of NamedArrays, vmap is typically less useful than in vanilla jax, but it is sometimes + useful for initializing modules that will be scanned over. + + default: how to handle (unnamed) arrays by default. Should be either an integer or None, or a callable that takes a PyTree leaf + and returns an integer or None, or a PyTree prefix of the same. If an integer, the array will be mapped over that axis. If None, the array will not be mapped over. + args: optional per-argument overrides for how to handle arrays. Should be a PyTree prefix of the same type as default. + kwargs: optional per-keyword-argument overrides for how to handle arrays. Should be a PyTree prefix of the same type as default. + out: optional override for how to handle the output. Should be a PyTree prefix of the same type as default. Defaults + to 0 if the output is an unnamed array, and the Axis otherwise. """ - unmmapped_argnums = ensure_tuple(unmapped_argnums) - def _index_of_batch_axis(array): + if kwargs is None: + kwargs = {} + + signature = inspect.signature(fn) + + # this mirrors equinox's filter_vmap, but it's not really documented there so: + # we use inspect.signature to align args/kwargs specified in vmap to what actually gets passed in + # axis_spec_bound_sig's job is to hold that mapping + signature_default = signature.replace( + parameters=[ + p + if p.kind in (inspect.Parameter.VAR_POSITIONAL, inspect.Parameter.VAR_KEYWORD) + else p.replace(default=default) + for p in signature.parameters.values() + ] + ) + axis_spec_bound_sig = signature_default.bind_partial(*args, **kwargs) + axis_spec_bound_sig.apply_defaults() + del args, kwargs + + def _index_of_batch_axis(array, default): if isinstance(array, NamedArray): - return array.axes.index(axis) - elif equinox.is_array(array): - return 0 + return array._lookup_indices(axis) + elif callable(default): + return default(array) else: - return None + return default - # TODO: do fancier things with kwargs and signature and such - # TODO: allow other axes to be mapped over - # TODO: maybe implement equinox-style filtering vmap # TODO: tests to exercise this more @wraps(fn) - def wrapped_vmap_fn(*args): + def wrapped_vmap_fn(*args, **kwargs): # TODO: this probably results in a lot of compilation misses. Need to think about it. - mapped_axes = [] - chilled_args = [] + actual_bound = signature.bind(*args, **kwargs) + actual_bound.apply_defaults() - for i, arg in enumerate(args): - if i in unmmapped_argnums: - mapped_axes.append(None) - else: - chilled_arg = jax.tree_util.tree_map(_pacify_named_arrays, arg, is_leaf=is_named_array) - chilled_args.append(chilled_arg) - mapped_axis = jax.tree_util.tree_map(_index_of_batch_axis, chilled_arg, is_leaf=_is_passive_array) - mapped_axes.append(mapped_axis) - - def wrapped_fn(*args): - unchilled_args = jax.tree_util.tree_map(_to_active_named_array(axis), args, is_leaf=is_named_array) - r = fn(*unchilled_args) - chilled = jax.tree_util.tree_map(_pacify_named_arrays, r, is_leaf=is_named_array) + # now that we have args, we can figure out what the axis spec is for each arg + padded_spec_args = axis_spec_bound_sig.args + (default,) * ( + len(actual_bound.args) - len(axis_spec_bound_sig.args) + ) + + # want to support padded_spec_args being a tree prefix of the actual args, which this enables + padded_spec_args = broadcast_prefix(padded_spec_args, actual_bound.args, is_leaf=is_named_array) + + arg_axis_specs = jax.tree_util.tree_map( + _index_of_batch_axis, actual_bound.args, padded_spec_args, is_leaf=is_named_array + ) + + padded_spec_kwargs = { + **axis_spec_bound_sig.kwargs, + **{k: default for k in actual_bound.kwargs.keys() - axis_spec_bound_sig.kwargs.keys()}, + } + + padded_spec_kwargs = broadcast_prefix(padded_spec_kwargs, actual_bound.kwargs) + + kwarg_axis_specs = jax.tree_util.tree_map( + _index_of_batch_axis, actual_bound.kwargs, padded_spec_kwargs, is_leaf=is_named_array + ) + + # now we can actually vmap. We used "pacified" versions of NamedArrays that don't check + # invariants, because intermediates creating during tracing won't have the axes right + arg_axis_specs = jax.tree_util.tree_map(_pacify_named_arrays, arg_axis_specs, is_leaf=is_named_array) + kwarg_axis_specs = jax.tree_util.tree_map(_pacify_named_arrays, kwarg_axis_specs, is_leaf=is_named_array) + + args = jax.tree_util.tree_map(_pacify_named_arrays, actual_bound.args, is_leaf=is_named_array) + kwargs = jax.tree_util.tree_map(_pacify_named_arrays, actual_bound.kwargs, is_leaf=is_named_array) + + def wrapped_fn(args, kwargs): + # the args that come in here are pacified. Their names will still have the batch axis even though the array + # itself will already have that one removed. We need to turn them back into NamedArrays by removing the axis + unchilled_args = jax.tree_util.tree_map(_to_unbatched_named_array(axis), args, is_leaf=_is_passive_array) + unchilled_kwargs = jax.tree_util.tree_map( + _to_unbatched_named_array(axis), kwargs, is_leaf=_is_passive_array + ) + + out = fn(*unchilled_args, **unchilled_kwargs) + + # now we need to pacify the output, which may include NamedArrays, and add the batch axis back at the end + chilled = jax.tree_util.tree_map(_pacify_named_arrays, out, is_leaf=is_named_array) return chilled spmd_axis_name = physical_axis_name(axis) result = jax.vmap( - wrapped_fn, in_axes=mapped_axes, out_axes=0, axis_size=axis.size, spmd_axis_name=spmd_axis_name - )(*args) - result = jax.tree_util.tree_map(_to_active_named_array(axis), result, is_leaf=_is_passive_array) + wrapped_fn, + in_axes=(arg_axis_specs, kwarg_axis_specs), + out_axes=0, + axis_size=axis.size, + spmd_axis_name=spmd_axis_name, + )(args, kwargs) + + result = jax.tree_util.tree_map(_prepend_named_batch_axis(axis), result, is_leaf=_is_passive_array) return result return wrapped_vmap_fn @@ -157,6 +231,13 @@ class _PassiveNamedArray: def as_scanned_result(self, scan_axis: Axis): return NamedArray(self.array, (scan_axis,) + self.main_axes) + def strip_axis(self, axis: Axis): + index = self.main_axes.index(axis) + return NamedArray(self.array, self.main_axes[:index] + self.main_axes[index + 1 :]) + + def to_named_array(self): + return NamedArray(self.array, self.main_axes) + def tree_flatten(self) -> Any: return ((self.array,), self.main_axes) @@ -170,7 +251,7 @@ def _is_passive_array(arr): return isinstance(arr, _PassiveNamedArray) -def _to_active_named_array(leading_axis): +def _prepend_named_batch_axis(leading_axis): def to_active_named_array(leaf): if isinstance(leaf, _PassiveNamedArray): return leaf.as_scanned_result(leading_axis) @@ -180,6 +261,19 @@ def _to_active_named_array(leading_axis): return to_active_named_array +def _to_unbatched_named_array(axis_to_strip: Axis): + def to_unbatched_named_array(leaf): + if isinstance(leaf, _PassiveNamedArray): + if axis_to_strip in leaf.main_axes: + return leaf.strip_axis(axis_to_strip) + else: + return leaf.to_named_array() + else: + return leaf + + return to_unbatched_named_array + + def _pacify_named_arrays(leaf): if isinstance(leaf, NamedArray): return _PassiveNamedArray(leaf.array, leaf.axes) diff --git a/src/haliax/jax_utils.py b/src/haliax/jax_utils.py index dba5af8..485e385 100644 --- a/src/haliax/jax_utils.py +++ b/src/haliax/jax_utils.py @@ -1,5 +1,5 @@ import functools as ft -from typing import Callable, Optional, Sequence, Union +from typing import Any, Callable, List, Optional, Sequence, Union import equinox as eqx import jax @@ -9,8 +9,6 @@ from equinox.compile_utils import Static from jax import numpy as jnp from jax import random as jrandom -from haliax.util import is_jax_array_like - def shaped_rng_split(key, split_shape: Union[int, Sequence[int]] = 2) -> jrandom.KeyArray: if isinstance(split_shape, int): @@ -53,3 +51,19 @@ def filter_eval_shape(fun: Callable, *args, **kwargs): dynamic, static = eqx.partition((args, kwargs), is_jax_array_like) dynamic_out, static_out = jax.eval_shape(ft.partial(_fn, static), dynamic) return eqx.combine(dynamic_out, static_out.value) + + +def is_jax_array_like(x): + return hasattr(x, "shape") and hasattr(x, "dtype") + + +# adapted from jax but exposed so i can use it +def broadcast_prefix(prefix_tree: Any, full_tree: Any, is_leaf: Optional[Callable[[Any], bool]] = None) -> List[Any]: + """Broadcast a prefix tree to match the structure of a full tree.""" + result = [] + num_leaves = lambda t: jax.tree_util.tree_structure(t).num_leaves # noqa: E731 + add_leaves = lambda x, subtree: result.extend([x] * num_leaves(subtree)) # noqa: E731 + jax.tree_util.tree_map(add_leaves, prefix_tree, full_tree, is_leaf=is_leaf) + full_structure = jax.tree_util.tree_structure(full_tree) + + return jax.tree_util.tree_unflatten(full_structure, result) diff --git a/src/haliax/partitioning.py b/src/haliax/partitioning.py index 1d5e604..878fe88 100644 --- a/src/haliax/partitioning.py +++ b/src/haliax/partitioning.py @@ -15,8 +15,8 @@ from jax.interpreters.pxla import PartitionSpec from jaxtyping import PyTree from .core import Axis, AxisSpec, NamedArray -from .jax_utils import filter_eval_shape -from .util import StringHolderEnum, ensure_tuple, is_jax_array_like, is_named_array +from .jax_utils import filter_eval_shape, is_jax_array_like +from .util import StringHolderEnum, ensure_tuple, is_named_array LogicalAxisName = str diff --git a/src/haliax/util.py b/src/haliax/util.py index 0e44160..2c6376f 100644 --- a/src/haliax/util.py +++ b/src/haliax/util.py @@ -19,10 +19,6 @@ def ensure_tuple(x: Union[Sequence[T], T]) -> Tuple[T, ...]: return (x,) -def is_jax_array_like(x): - return hasattr(x, "shape") and hasattr(x, "dtype") - - class StringHolderEnum(type): """Like a python enum but just holds string constants, as opposed to wrapped string constants""" diff --git a/tests/test_hof.py b/tests/test_hof.py index b054aca..208bf1e 100644 --- a/tests/test_hof.py +++ b/tests/test_hof.py @@ -53,7 +53,7 @@ def test_reduce(): assert jnp.all(jnp.isclose(total.rearrange(acc.axes).array, jnp.sum(named1.array, axis=2))) -def test_vmap(): +def test_vmap_unmapped_args(): Batch = Axis("Batch", 10) Width = Axis("Width", 3) Depth = Axis("Depth", 4) @@ -69,3 +69,56 @@ def test_vmap(): assert jnp.all(jnp.equal(selected.array, expected_jax)) assert selected.axes == expected_names + + +def test_vmap_mapped_args(): + Batch = Axis("Batch", 10) + Width = Axis("Width", 3) + Depth = Axis("Depth", 4) + named1 = hax.random.uniform(PRNGKey(0), (Batch, Width, Depth)) + + def vmap_fun(x): + return x.sum(Width) + + selected = hax.vmap(vmap_fun, Batch)(named1) + + expected_jax = jnp.array([named1.sum(Width).array for _ in range(Batch.size)]) + expected_names = (Batch, Depth) + + assert jnp.all(jnp.equal(selected.array, expected_jax)) + assert selected.axes == expected_names + + +def test_vmap_mapped_kwarg(): + Batch = Axis("Batch", 10) + Width = Axis("Width", 3) + Depth = Axis("Depth", 4) + named1 = hax.random.uniform(PRNGKey(0), (Batch, Width, Depth)) + + def vmap_fun(x): + return x.sum(Width) + + selected = hax.vmap(vmap_fun, Batch)(x=named1) + + expected_jax = jnp.array([named1.sum(Width).array for _ in range(Batch.size)]) + expected_names = (Batch, Depth) + + assert jnp.all(jnp.equal(selected.array, expected_jax)) + assert selected.axes == expected_names + + +def test_vmap_static_args(): + Batch = Axis("Batch", 10) + Width = Axis("Width", 3) + Depth = Axis("Depth", 4) + named1 = hax.random.uniform(PRNGKey(0), (Batch, Width, Depth)) + + def vmap_fun(x, y): + return x.sum(Width) if y else x + + selected = hax.vmap(vmap_fun, Batch)(named1, True) + + expected = hax.sum(named1, Width) + + assert jnp.all(jnp.equal(selected.array, expected.array)) + assert selected.axes == expected.axes commit aa1b53a1e1aa0fb1f518dd6b9fa64dccbaeef57d Date: 2022-10-19T23:06:48-07:00 refactor scan and reduce to support static/unscanned arguments, make them curried (#40) * refactor scan and reduce to support static/unscanned arguments * jax.lax.reduce is over all weaker than hax.reduce diff --git a/src/haliax/hof.py b/src/haliax/hof.py index fe8b189..e082e42 100644 --- a/src/haliax/hof.py +++ b/src/haliax/hof.py @@ -3,14 +3,16 @@ import inspect from functools import wraps from typing import Any, Callable, Tuple, TypeVar, Union +import equinox as eqx import jax import jax.lax as lax +from equinox.custom_types import BoolAxisSpec from jaxtyping import PyTree from .core import Axis, NamedArray -from .jax_utils import broadcast_prefix, is_jax_array_like +from .jax_utils import broadcast_prefix, combine, is_jax_array_like from .partitioning import auto_sharded, physical_axis_name -from .util import is_named_array +from .util import is_jax_or_hax_array_like, is_named_array Carry = TypeVar("Carry") @@ -18,72 +20,105 @@ X = TypeVar("X") Y = TypeVar("Y") -def scan(f: Callable[[Carry, X], Tuple[Carry, Y]], axis: Axis, init: Carry, xs: X, reverse=False, unroll=1): +def scan( + f: Callable[[Carry, X], Tuple[Carry, Y]], + axis: Axis, + *, + reverse=False, + unroll=1, + is_scanned: BoolAxisSpec = is_jax_or_hax_array_like, +): """ - Scan over a named axis. Arrays that are not part of a named axis will have their 0th dim scanned over + Scan over a named axis. Arrays that are not part of a NamedArray will have their 0th dim scanned over + + Unlike jax.lax.scan, this function is curried: it takes the function, axis, and configuration arguments first, and + then the initial carry and then any arguments to scan over as a separate curried function call. + + That is, scan(f, axis)(init, xs) is equivalent to jax.lax.scan(f, init, xs) + + Args: + :param f: function to scan over + :param axis: axis to scan over + :param reverse: if True, scan in reverse + :param unroll: unroll the loop by this amount + :param is_scanned: a function that takes a leaf of the tree and returns True if it should be scanned over, + False otherwise. Behaves similarly to the `default` argument in filter_jit """ - # This implementation is a bit tricky. - # First we have to hoist the axis we're scanning over to the front of the array, because that's what scan expects. - # Then we have to scan over the 0th dim of the arrays (as flattened non-pytrees) - # We have to be careful that we don't try to create NamedArrays that have the shape of the scanned result - # but don't yet have the scanned axis as ones of `axes`, so we use _ScannedArrayResult that doesn't check - # invariants until we're ready to create the result. + def scanned_f(init, *args, **kwargs): + # This implementation is a bit tricky. + + # first we want to partition the arguments into scanned and unscanned + # unscanned arguments are just passed through, essentially captured as part of a lambda + # scanned arguments are passed through the scan, which means we need to hoist the axis to the front + xs = (args, kwargs) + scanned_xs, unscanned_xs = eqx.partition(xs, is_scanned, is_leaf=is_named_array) - axis_first_xs = jax.tree_util.tree_map(_ensure_first(axis), xs, is_leaf=is_named_array) + # Next we have to hoist the axis we're scanning over to the front of the array, because that's what scan + # expects. Then we have to scan over the 0th dim of the arrays (as flattened non-pytrees) + # We have to be careful that we don't try to create NamedArrays that have the shape of the scanned result + # but don't yet have the scanned axis as ones of `axes`, so we use _ScannedArrayResult that doesn't check + # invariants until we're ready to create the result. + axis_first_xs = jax.tree_util.tree_map(_ensure_first(axis), scanned_xs, is_leaf=is_named_array) - # now get a template of an element of "X" - x_elem = jax.tree_util.tree_map(_select_0th(axis), axis_first_xs, is_leaf=is_named_array) - x_elem_structure = jax.tree_util.tree_structure(x_elem) + # now get a template of an element of "X" + x_elem = jax.tree_util.tree_map(_select_0th(axis), axis_first_xs, is_leaf=is_named_array) + x_elem_structure = jax.tree_util.tree_structure(x_elem) - # now we can fold over the axis - @wraps(f) - def wrapped_fn(carry, x): - x = jax.tree_util.tree_unflatten(x_elem_structure, x) - x = auto_sharded(x) - carry, y = f(carry, x) - y = jax.tree_util.tree_map(_pacify_named_arrays, y, is_leaf=is_named_array) - y = auto_sharded(y) - return carry, y + # now we can fold over the axis + @wraps(f) + def wrapped_fn(carry, scanned_x_leaves): + scanned_x = jax.tree_util.tree_unflatten(x_elem_structure, scanned_x_leaves) + # this part is the most delicate: combining the scanned x with the unscanned x + scanned_x = combine(scanned_x, unscanned_xs, is_leaf=is_named_array) + scanned_x = auto_sharded(scanned_x) + args, kwargs = scanned_x + carry, y = f(carry, *args, **kwargs) + y = jax.tree_util.tree_map(_pacify_named_arrays, y, is_leaf=is_named_array) + y = auto_sharded(y) + return carry, y - leaves = jax.tree_util.tree_leaves(axis_first_xs) - carry, ys = lax.scan(wrapped_fn, init, leaves, reverse=reverse, unroll=unroll) - ys = jax.tree_util.tree_map(_prepend_named_batch_axis(axis), ys, is_leaf=_is_passive_array) + leaves = jax.tree_util.tree_leaves(axis_first_xs) + carry, ys = lax.scan(wrapped_fn, init, leaves, reverse=reverse, unroll=unroll) + ys = jax.tree_util.tree_map(_prepend_named_batch_axis(axis), ys, is_leaf=_is_passive_array) - return carry, ys + return carry, ys + + return scanned_f def reduce( - fn: Callable[[Carry, X], Carry], axis: Axis, init: Carry, xs: X, reverse: bool = False, unroll: int = 1 -) -> Carry: + fn: Callable[[Carry, X], Carry], + axis: Axis, + *, + reverse: bool = False, + unroll: int = 1, + is_scanned: BoolAxisSpec = is_jax_or_hax_array_like, +) -> Callable[[Carry, PyTree], Carry]: """ - Slightly simpler implementation of scan that folds over the first axis of the array, not returning intermediates. - - If reverse is True, the fold is actually a fold_right + Slightly simpler implementation of scan that folds over the named axis of the array, not returning intermediates. + + As with scan, this function is curried: it takes the function, axis, and configuration arguments first, and + then the initial carry and then any arguments to scan over as a separate curried function call. + + Args: + :param fn: function to reduce over + :param axis: axis to reduce over + :param reverse: if True, reduce in reverse + :param unroll: unroll the loop by this amount + :param is_scanned: a function that takes a leaf of the tree and returns True if it should be scanned over, + False otherwise. Behaves similarly to the `default` argument in filter_jit """ - if axis.size == 0: - return init - - # This implementation is a bit tricky. - # First we have to hoist the axis we're scanning over to the front of the array. - # Then we have to scan over the 0th dim of the arrays (as flattened non-pytrees) - axis_first_xs = jax.tree_util.tree_map(_ensure_first(axis), xs, is_leaf=is_named_array) - # now get a template for where we fold over the axis in question - x_elem = jax.tree_util.tree_map(_select_0th(axis), axis_first_xs, is_leaf=is_named_array) - x_elem_structure = jax.tree_util.tree_structure(x_elem) + def scan_compatible_fn(carry, *args, **kwargs): + return fn(carry, *args, **kwargs), None - # now we can fold over the axis - @wraps(fn) - def wrapped_fn(carry, x): - x = jax.tree_util.tree_unflatten(x_elem_structure, x) - x = auto_sharded(x) - return fn(carry, x), None + scan_preconfig = scan(scan_compatible_fn, axis, reverse=reverse, unroll=unroll, is_scanned=is_scanned) - leaves = jax.tree_util.tree_leaves(axis_first_xs) - carry, _ = lax.scan(wrapped_fn, init, leaves, reverse=reverse, unroll=unroll) + def scanned_f(init, *args, **kwargs): + return scan_preconfig(init, *args, **kwargs)[0] - return carry + return scanned_f ResolvedUnnamedAxisSpec = Union[int, None] diff --git a/src/haliax/jax_utils.py b/src/haliax/jax_utils.py index 485e385..49a05d0 100644 --- a/src/haliax/jax_utils.py +++ b/src/haliax/jax_utils.py @@ -8,6 +8,7 @@ from chex import PRNGKey from equinox.compile_utils import Static from jax import numpy as jnp from jax import random as jrandom +from jaxtyping import PyTree def shaped_rng_split(key, split_shape: Union[int, Sequence[int]] = 2) -> jrandom.KeyArray: @@ -40,6 +41,7 @@ def filter_eval_shape(fun: Callable, *args, **kwargs): """As `jax.eval_shape`, but allows any Python object as inputs and outputs, including GlobalDeviceArrays (which equinox.filter_eval_shape does not support). """ + # TODO: file a bug def _fn(_static, _dynamic): @@ -67,3 +69,33 @@ def broadcast_prefix(prefix_tree: Any, full_tree: Any, is_leaf: Optional[Callabl full_structure = jax.tree_util.tree_structure(full_tree) return jax.tree_util.tree_unflatten(full_structure, result) + + +def _is_none(x): + return x is None + + +def _combine(*args): + for arg in args: + if arg is not None: + return arg + return None + + +def combine(*pytrees: PyTree, is_leaf=None) -> PyTree: + """Generalization of eqx.combine to support custom is_leaf functions + + **Returns:** + + A PyTree with the same structure as its inputs. Each leaf will be the first + non-`None` leaf found in the corresponding leaves of `pytrees` as they are + iterated over. + """ + + if is_leaf is None: + is_leaf = _is_none + else: + _orig_is_leaf = is_leaf + is_leaf = lambda x: _is_none(x) or _orig_is_leaf(x) # noqa: E731 + + return jax.tree_util.tree_map(_combine, *pytrees, is_leaf=is_leaf) diff --git a/src/haliax/util.py b/src/haliax/util.py index 2c6376f..623a081 100644 --- a/src/haliax/util.py +++ b/src/haliax/util.py @@ -2,6 +2,8 @@ from typing import Optional, Sequence, Tuple, TypeVar, Union import jax +from haliax.jax_utils import is_jax_array_like + T = TypeVar("T") @@ -55,3 +57,7 @@ def named_call(f=_UNSPECIFIED, name: Optional[str] = None): name = f.__qualname__ return jax.named_scope(name)(f) + + +def is_jax_or_hax_array_like(x): + return is_jax_array_like(x) or is_named_array(x) diff --git a/tests/test_hof.py b/tests/test_hof.py index 208bf1e..64ffcd2 100644 --- a/tests/test_hof.py +++ b/tests/test_hof.py @@ -3,6 +3,7 @@ from jax.random import PRNGKey import haliax as hax from haliax import Axis, NamedArray +from haliax.util import is_named_array def test_scan(): @@ -14,7 +15,7 @@ def test_scan(): def scan_fun(acc, x): return acc + jnp.sum(x.array), x.take(Width, 2) - total, selected = hax.scan(scan_fun, Height, 0.0, named1) + total, selected = hax.scan(scan_fun, Height)(0.0, named1) assert jnp.all(jnp.isclose(total, jnp.sum(named1.array, axis=(0, 1, 2)))) assert jnp.all(jnp.equal(selected.array, named1.take(Width, 2).array)) @@ -29,14 +30,30 @@ def test_scan_not_0th_axis(): def scan_fun(acc, x): return acc + jnp.sum(x.array), x.take(Width, 2) - total, selected = hax.scan(scan_fun, Depth, 0.0, named1) + total, selected = hax.scan(scan_fun, Depth)(0.0, named1) assert jnp.all(jnp.isclose(total, jnp.sum(named1.array, axis=(0, 1, 2)))) assert jnp.all(jnp.equal(selected.array, named1.take(Width, 2).rearrange(selected.axes).array)) -def test_reduce(): +def test_scan_static_args(): + Height = Axis("Height", 10) + Width = Axis("Width", 3) + Depth = Axis("Depth", 4) + named1 = hax.random.uniform(PRNGKey(0), (Height, Width, Depth)) + + def scan_fun(acc, x, static1, *, static2): + assert static1 is True + assert static2 is False + return acc + jnp.sum(x.array), x.take(Width, 2) + total, selected = hax.scan(scan_fun, Depth, is_scanned=is_named_array)(0.0, named1, True, static2=False) + + assert jnp.all(jnp.isclose(total, jnp.sum(named1.array, axis=(0, 1, 2)))) + assert jnp.all(jnp.equal(selected.array, named1.take(Width, 2).rearrange(selected.axes).array)) + + +def test_reduce(): Height = Axis("Height", 10) Width = Axis("Width", 3) Depth = Axis("Depth", 4) @@ -48,7 +65,25 @@ def test_reduce(): acc = hax.zeros((Height, Width)) - total = hax.reduce(fold_fun, Depth, acc, named1) + total = hax.reduce(fold_fun, Depth)(acc, named1) + + assert jnp.all(jnp.isclose(total.rearrange(acc.axes).array, jnp.sum(named1.array, axis=2))) + + +def test_reduce_static_args(): + Height = Axis("Height", 10) + Width = Axis("Width", 3) + Depth = Axis("Depth", 4) + named1 = hax.random.uniform(PRNGKey(0), (Height, Width, Depth)) + + def fold_fun(acc, x, static1, *, static2): + assert static1 is True + assert static2 is False + return NamedArray(acc.array + x.rearrange(acc.axes).array, acc.axes) + + acc = hax.zeros((Height, Width)) + + total = hax.reduce(fold_fun, Depth)(acc, named1, True, static2=False) assert jnp.all(jnp.isclose(total.rearrange(acc.axes).array, jnp.sum(named1.array, axis=2))) commit fde78a3d7d170818aa2c984d5612218cd153772d Date: 2022-10-21T10:59:37-07:00 move named_call to jax_utils diff --git a/src/haliax/jax_utils.py b/src/haliax/jax_utils.py index 49a05d0..eeb455a 100644 --- a/src/haliax/jax_utils.py +++ b/src/haliax/jax_utils.py @@ -99,3 +99,24 @@ def combine(*pytrees: PyTree, is_leaf=None) -> PyTree: is_leaf = lambda x: _is_none(x) or _orig_is_leaf(x) # noqa: E731 return jax.tree_util.tree_map(_combine, *pytrees, is_leaf=is_leaf) + + +def _UNSPECIFIED(): + raise ValueError("unspecified") + + +def named_call(f=_UNSPECIFIED, name: Optional[str] = None): + if f is _UNSPECIFIED: + return lambda f: named_call(f, name) # type: ignore + else: + if name is None: + name = f.__name__ + if name == "__call__": + if hasattr(f, "__self__"): + name = f.__self__.__class__.__name__ # type: ignore + else: + name = f.__qualname__.rsplit(".", maxsplit=1)[0] # type: ignore + else: + name = f.__qualname__ + + return jax.named_scope(name)(f) diff --git a/src/haliax/random.py b/src/haliax/random.py index 32d1526..a8fdb5f 100644 --- a/src/haliax/random.py +++ b/src/haliax/random.py @@ -9,9 +9,10 @@ import jax.random as jrandom # TODO: handle broadcasting of array args to random functions (e.g. minval and maxval for uniform) from haliax.core import Axis, NamedArray -from haliax.util import ensure_tuple, named_call +from haliax.util import ensure_tuple -from .partitioning import pspec_for_axis, auto_sharded, physical_axis_size +from .jax_utils import named_call +from .partitioning import auto_sharded, physical_axis_size, pspec_for_axis def _wrap_random_function(func): @@ -49,7 +50,9 @@ def _wrap_random_function(func): # what we do is we take the biggest axis that is sharded and split on it, ties going to the first axis pspec = pspec_for_axis(orig_shape) if pspec: - biggest_axis, biggest_physical = max(zip(orig_shape, pspec), key=lambda x: (physical_axis_size(x[0]) or 0) if x[1] else 0) + biggest_axis, biggest_physical = max( + zip(orig_shape, pspec), key=lambda x: (physical_axis_size(x[0]) or 0) if x[1] else 0 + ) else: biggest_axis = biggest_physical = None @@ -63,11 +66,11 @@ def _wrap_random_function(func): return func(key, *sig.args[1:], **sig.kwargs) out = jax.vmap(fn, in_axes=(0,), out_axes=index_of_biggest_axis)(keys) - return NamedArray(out, orig_shape) + return auto_sharded(NamedArray(out, orig_shape)) else: sig.arguments["shape"] = shape out = func(**sig.arguments) - return NamedArray(out, orig_shape) + return auto_sharded(NamedArray(out, orig_shape)) else: return func(**sig.arguments) diff --git a/src/haliax/util.py b/src/haliax/util.py index 623a081..dfc7d21 100644 --- a/src/haliax/util.py +++ b/src/haliax/util.py @@ -1,6 +1,4 @@ -from typing import Optional, Sequence, Tuple, TypeVar, Union - -import jax +from typing import Sequence, Tuple, TypeVar, Union from haliax.jax_utils import is_jax_array_like @@ -38,26 +36,5 @@ class StringHolderEnum(type): yield from cls.members -def _UNSPECIFIED(): - raise ValueError("unspecified") - - -def named_call(f=_UNSPECIFIED, name: Optional[str] = None): - if f is _UNSPECIFIED: - return lambda f: named_call(f, name) # type: ignore - else: - if name is None: - name = f.__name__ - if name == "__call__": - if hasattr(f, "__self__"): - name = f.__self__.__class__.__name__ # type: ignore - else: - name = f.__qualname__.rsplit(".", maxsplit=1)[0] # type: ignore - else: - name = f.__qualname__ - - return jax.named_scope(name)(f) - - def is_jax_or_hax_array_like(x): return is_jax_array_like(x) or is_named_array(x) commit 57d6d911971579618120df83817c0cd4b35babf1 Date: 2022-10-21T11:12:52-07:00 add a way to disable shape checks for NamedArrays since we perform shenanigans diff --git a/src/haliax/__init__.py b/src/haliax/__init__.py index ba56391..5c843ec 100644 --- a/src/haliax/__init__.py +++ b/src/haliax/__init__.py @@ -8,6 +8,7 @@ from .core import ( Axis, AxisSpec, NamedArray, + are_shape_checks_enabled, broadcast_axis, broadcast_to, concat_axis_specs, @@ -16,6 +17,7 @@ from .core import ( named, rearrange, rename, + shape_checks, split, take, unbind, @@ -345,4 +347,6 @@ __all__ = [ "true_divide", "auto_sharded", "axis_mapping", + "shape_checks", + "are_shape_checks_enabled", ] diff --git a/src/haliax/core.py b/src/haliax/core.py index d25ae05..d25b54d 100644 --- a/src/haliax/core.py +++ b/src/haliax/core.py @@ -1,3 +1,4 @@ +import contextlib import functools as ft from dataclasses import dataclass from math import prod @@ -27,6 +28,30 @@ AxisSpec = Union[Axis, Sequence[Axis]] Scalar = Union[float, int] NamedNumeric = Union[Scalar, "NamedArray"] +_ENABLE_SHAPE_CHECKS = True + + +@contextlib.contextmanager +def shape_checks(enabled): + """ + Sometimes we end up in situations where an array that jax makes is passed into the NamedArray constructor that + doesn't conform to the shape we expect. This shows up in particular when we are using jax.vmap or jax.scan, + and we sometimes have weird situations with deserialization + + Yields the old value because we sometimes want to nest this + """ + global _ENABLE_SHAPE_CHECKS + old = _ENABLE_SHAPE_CHECKS + _ENABLE_SHAPE_CHECKS = enabled + try: + yield old + finally: + _ENABLE_SHAPE_CHECKS = old + + +def are_shape_checks_enabled(): + return _ENABLE_SHAPE_CHECKS + @jax.tree_util.register_pytree_node_class @dataclass(frozen=True) @@ -47,6 +72,12 @@ class NamedArray: if len(set(a.name for a in self.axes)) != len(self.axes): raise ValueError(f"Axes must be unique, but {self.axes} are not") + if are_shape_checks_enabled(): + self.ensure_shape_matches_axes() + + def ensure_shape_matches_axes(self): + """This is typically called automatically, but sometimes we need to call it manually if + are_shape_checks_enabled() is False""" if is_jax_array_like(self.array): s = jnp.shape(self.array) if s != tuple(a.size for a in self.axes): @@ -800,4 +831,6 @@ __all__ = [ "broadcast_to", "broadcast_axis", "broadcast_arrays", + "shape_checks", + "are_shape_checks_enabled", ] commit 9c493805753a2b02f039a9ab6e933544defeb191 Date: 2022-10-22T07:23:27-07:00 rename reduce back to fold because reduce has a different meaning in jax diff --git a/src/haliax/__init__.py b/src/haliax/__init__.py index 5c843ec..e049162 100644 --- a/src/haliax/__init__.py +++ b/src/haliax/__init__.py @@ -23,7 +23,7 @@ from .core import ( unbind, unflatten_axis, ) -from .hof import reduce, scan, vmap +from .hof import fold, scan, vmap from .ops import trace, tril, triu, where from .partitioning import auto_sharded, axis_mapping from .wrap import wrap_axiswise_call, wrap_elemwise_binary, wrap_elemwise_unary, wrap_reduction_call @@ -304,7 +304,7 @@ __all__ = [ "cumproduct", "sort", "scan", - "reduce", + "fold", "vmap", "trace", "where", diff --git a/src/haliax/hof.py b/src/haliax/hof.py index e082e42..26c52ea 100644 --- a/src/haliax/hof.py +++ b/src/haliax/hof.py @@ -87,7 +87,7 @@ def scan( return scanned_f -def reduce( +def fold( fn: Callable[[Carry, X], Carry], axis: Axis, *, @@ -343,4 +343,4 @@ def _ensure_first(axis): return ensure_first -__all__ = ["scan", "reduce", "vmap"] +__all__ = ["scan", "fold", "vmap"] diff --git a/tests/test_hof.py b/tests/test_hof.py index 64ffcd2..d2da8f6 100644 --- a/tests/test_hof.py +++ b/tests/test_hof.py @@ -65,7 +65,7 @@ def test_reduce(): acc = hax.zeros((Height, Width)) - total = hax.reduce(fold_fun, Depth)(acc, named1) + total = hax.fold(fold_fun, Depth)(acc, named1) assert jnp.all(jnp.isclose(total.rearrange(acc.axes).array, jnp.sum(named1.array, axis=2))) @@ -83,7 +83,7 @@ def test_reduce_static_args(): acc = hax.zeros((Height, Width)) - total = hax.reduce(fold_fun, Depth)(acc, named1, True, static2=False) + total = hax.fold(fold_fun, Depth)(acc, named1, True, static2=False) assert jnp.all(jnp.isclose(total.rearrange(acc.axes).array, jnp.sum(named1.array, axis=2))) commit c30d3b600667972990ef5c6430c1eca8f97f79de Date: 2022-10-22T07:23:47-07:00 remove stray doc from layernorm diff --git a/src/haliax/nn/normalization.py b/src/haliax/nn/normalization.py index 7645bed..92808d8 100644 --- a/src/haliax/nn/normalization.py +++ b/src/haliax/nn/normalization.py @@ -10,7 +10,7 @@ from ..core import AxisSpec, NamedArray class LayerNorm(eqx.Module): r""" Normalises the input along the specified axis (or axes), using the mean and variance of the - input along that axis. This is equivalent to the following code: + input along that axis. """ axis: AxisSpec = eqx.static_field() eps: float = eqx.static_field() commit 5487ce94303f82a98fc38c7fd4c344cb058b1f9e Date: 2022-10-24T09:02:10-07:00 add clip to haliax diff --git a/src/haliax/__init__.py b/src/haliax/__init__.py index e049162..a4107ab 100644 --- a/src/haliax/__init__.py +++ b/src/haliax/__init__.py @@ -24,7 +24,7 @@ from .core import ( unflatten_axis, ) from .hof import fold, scan, vmap -from .ops import trace, tril, triu, where +from .ops import clip, trace, tril, triu, where from .partitioning import auto_sharded, axis_mapping from .wrap import wrap_axiswise_call, wrap_elemwise_binary, wrap_elemwise_unary, wrap_reduction_call @@ -308,6 +308,7 @@ __all__ = [ "vmap", "trace", "where", + "clip", "tril", "triu", "add", diff --git a/src/haliax/core.py b/src/haliax/core.py index d25b54d..77af392 100644 --- a/src/haliax/core.py +++ b/src/haliax/core.py @@ -3,7 +3,7 @@ import functools as ft from dataclasses import dataclass from math import prod from types import EllipsisType -from typing import Any, Dict, List, Mapping, Optional, Sequence, Tuple, Union, cast +from typing import Any, Dict, List, Mapping, Optional, Sequence, Tuple, Union, cast, overload import jax import jax.numpy as jnp @@ -164,10 +164,10 @@ class NamedArray: def astype(self, dtype) -> "NamedArray": return NamedArray(self.array.astype(dtype), self.axes) - # TODO - # def clip(self, a_min=None, a_max=None) -> Any: - # ... + def clip(self, a_min=None, a_max=None) -> Any: + return haliax.clip(self, a_min=a_min, a_max=a_max) + # TODO # def compress(self, condition, axis: Optional[int] = None) -> Any: # ... @@ -767,11 +767,33 @@ def broadcast_to(a: NamedArray, axes: Tuple[Axis, ...], ensure_order: bool = Tru return a +@overload +def broadcast_arrays( + *arrays: NamedArray, require_subset: bool = True, ensure_order: bool = True +) -> Tuple[NamedArray, ...]: + ... + + +@overload +def broadcast_arrays( + *arrays: NamedNumeric, require_subset: bool = True, ensure_order: bool = True +) -> Tuple[NamedNumeric, ...]: + ... + + def broadcast_arrays( - *arrays: NamedArray, + *arrays: NamedNumeric, require_subset: bool = True, ensure_order: bool = True, -) -> Tuple[NamedArray, ...]: +) -> Tuple[NamedNumeric, ...]: + return broadcast_arrays_and_return_axes(*arrays, require_subset=require_subset, ensure_order=ensure_order)[0] + + +def broadcast_arrays_and_return_axes( + *arrays: NamedNumeric, + require_subset: bool = True, + ensure_order: bool = True, +) -> Tuple[Tuple[NamedNumeric, ...], Tuple[Axis, ...]]: """ Broadcasts a sequence of arrays to a common set of axes. @@ -789,17 +811,22 @@ def broadcast_arrays( axes may not be moved. """ if len(arrays) == 0: - return () + return ((), ()) # sort the arrays by size, so that we use the biggest ones to broadcast the others # need to hold on to the order so we can return the arrays in the same order - size_order = sorted(range(len(arrays)), key=lambda i: arrays[i].size, reverse=True) - all_axes = [arrays[i].axes for i in size_order] + actual_arrays = [x for x in arrays if isinstance(x, NamedArray)] + size_order = sorted(range(len(actual_arrays)), key=lambda i: actual_arrays[i].size, reverse=True) + all_axes = [actual_arrays[i].axes for i in size_order] full_axes = ft.reduce(lambda a, b: _broadcast_axes(a, b, require_subset) if a is not None else None, all_axes) # type: ignore if full_axes is None: raise ValueError(f"Cannot broadcast arrays {arrays}: no subset relationship") - return tuple(broadcast_to(a, full_axes, ensure_order=ensure_order) for a in arrays) + arrays = tuple( + broadcast_to(a, full_axes, ensure_order=ensure_order) if isinstance(a, NamedArray) else a for a in arrays + ) + + return arrays, full_axes def broadcast_axis(a: NamedArray, axis: AxisSpec) -> NamedArray: @@ -834,3 +861,9 @@ __all__ = [ "shape_checks", "are_shape_checks_enabled", ] + + +def raw_array_or_scalar(x: NamedNumeric): + if isinstance(x, NamedArray): + return x.array + return x diff --git a/src/haliax/ops.py b/src/haliax/ops.py index 33d2be9..f2eb7ad 100644 --- a/src/haliax/ops.py +++ b/src/haliax/ops.py @@ -3,7 +3,14 @@ from typing import Union import jax import jax.numpy as jnp -from .core import Axis, NamedArray, NamedNumeric, broadcast_arrays +from .core import ( + Axis, + NamedArray, + NamedNumeric, + broadcast_arrays, + broadcast_arrays_and_return_axes, + raw_array_or_scalar, +) def trace(array: NamedArray, axis1: Axis, axis2: Axis, offset=0, dtype=None) -> NamedArray: @@ -42,13 +49,27 @@ def where(condition: Union[NamedNumeric, bool], x: NamedNumeric, y: NamedNumeric if jnp.isscalar(x): x = NamedArray(jnp.broadcast_to(x, condition.array.shape), condition.axes) + assert isinstance(x, NamedArray) + if jnp.isscalar(y): y = NamedArray(jnp.broadcast_to(y, condition.array.shape), condition.axes) + assert isinstance(y, NamedArray) + condition, x, y = broadcast_arrays(condition, x, y) # type: ignore return NamedArray(jnp.where(condition.array, x.array, y.array), condition.axes) +def clip(array: NamedNumeric, a_min: NamedNumeric, a_max: NamedNumeric) -> NamedArray: + """Like jnp.clip, but with named axes. This version currently only accepts the three argument form.""" + (array, a_min, a_max), axes = broadcast_arrays_and_return_axes(array, a_min, a_max) + array = raw_array_or_scalar(array) + a_min = raw_array_or_scalar(a_min) + a_max = raw_array_or_scalar(a_max) + + return NamedArray(jnp.clip(array, a_min, a_max), axes) + + def tril(array: NamedArray, axis1: Axis, axis2: Axis, k=0) -> NamedArray: """Compute the lower triangular part of an array along two named axes.""" array = array.rearrange((..., axis1, axis2)) diff --git a/tests/test_ops.py b/tests/test_ops.py index 4a3bdba..7aedf04 100644 --- a/tests/test_ops.py +++ b/tests/test_ops.py @@ -111,6 +111,38 @@ def test_where(): _ = hax.where(named5 > named6, named5, named6) +def test_clip(): + Height = Axis("Height", 10) + Width = Axis("Width", 3) + Depth = Axis("Depth", 4) + + named1 = hax.random.uniform(PRNGKey(0), (Height, Width, Depth)) + named2 = hax.clip(named1, 0.3, 0.7) + assert jnp.all(jnp.isclose(named2.array, jnp.clip(named1.array, 0.3, 0.7))) + + named2_reorder = named2.rearrange((Width, Height, Depth)) + named3 = hax.clip(named2_reorder, 0.3, 0.7) + named3 = named3.rearrange((Height, Width, Depth)) + assert jnp.all(jnp.isclose(named3.array, jnp.clip(named2.array, 0.3, 0.7))) + + # now some interesting broadcasting + lower = hax.full((Height, Width), 0.3) + upper = hax.full((Width, Depth), 0.7) + named4 = hax.clip(named1, lower, upper) + named4 = named4.rearrange((Height, Width, Depth)) + + assert jnp.all( + jnp.isclose( + named4.array, + jnp.clip( + named1.array, + lower.array.reshape((Height.size, Width.size, 1)), + upper.array.reshape((1, Width.size, Depth.size)), + ), + ) + ) + + def test_tril_triu(): Height = Axis("Height", 10) Width = Axis("Width", 3) commit 5138364d8fc15457e92604206069912d3dfddcaf Date: 2022-10-24T09:11:33-07:00 delete some TODOs for methods I won't implement probably diff --git a/src/haliax/core.py b/src/haliax/core.py index 77af392..93d46d3 100644 --- a/src/haliax/core.py +++ b/src/haliax/core.py @@ -186,9 +186,6 @@ class NamedArray: def cumsum(self, axis: Optional[AxisSpec] = None, *, dtype=None) -> "NamedArray": return haliax.cumsum(self, axis=axis, dtype=dtype) - # def diagonal(self, offset=0, axis1: int = 0, axis2: int = 1) -> Any: - # ... - def dot(self, axis: AxisSpec, b, *, precision=None) -> "NamedArray": return dot(axis, self, b, precision=precision) @@ -223,10 +220,6 @@ class NamedArray: ) -> "NamedArray": return haliax.min(self, axis=axis, initial=initial, where=where) - # TODO - # def nonzero(self, *, size=None, fill_value=None) -> Any: - # ... - def prod( self, axis: Optional[AxisSpec] = None, @@ -261,9 +254,6 @@ class NamedArray: def round(self, decimals=0) -> "NamedArray": return haliax.round(self, decimals=decimals) - # def searchsorted(self, v, side='left', sorter=None) -> Any: - # ... - def sort(self, axis: Axis, kind="quicksort") -> Any: return haliax.sort(self, axis=axis, kind=kind) commit a27ebbc7af31c32157452dc697ef3114c1e71ea3 Date: 2022-10-24T22:35:54-07:00 close out todo in tests diff --git a/tests/test_hof.py b/tests/test_hof.py index d2da8f6..590eee7 100644 --- a/tests/test_hof.py +++ b/tests/test_hof.py @@ -59,13 +59,9 @@ def test_reduce(): Depth = Axis("Depth", 4) named1 = hax.random.uniform(PRNGKey(0), (Height, Width, Depth)) - def fold_fun(acc, x): - # TODO: implement binary ops! - return NamedArray(acc.array + x.rearrange(acc.axes).array, acc.axes) - acc = hax.zeros((Height, Width)) - total = hax.fold(fold_fun, Depth)(acc, named1) + total = hax.fold(lambda x, y: x + y, Depth)(acc, named1) assert jnp.all(jnp.isclose(total.rearrange(acc.axes).array, jnp.sum(named1.array, axis=2))) commit 1af2786be8d7e3e91466148ef11364d83c00e957 Date: 2022-10-26T15:14:22-07:00 add license diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..310ad36 --- /dev/null +++ b/LICENSE @@ -0,0 +1,201 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright 2022 Stanford University + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. commit a5aa0ec3795058877b938f612e67499d8a706f39 Date: 2022-10-27T22:29:05-07:00 see if we can get away with less autosharding diff --git a/src/haliax/core.py b/src/haliax/core.py index 93d46d3..303568b 100644 --- a/src/haliax/core.py +++ b/src/haliax/core.py @@ -598,7 +598,9 @@ def unbind(array: NamedArray, axis: Axis) -> List[NamedArray]: # arrays = jnp.rollaxis(array.array, axis=axis_index, start=0) # instead we just loop over the axes pulling one out at a time arrays = [jnp.take(array.array, i, axis=axis_index) for i in range(axis.size)] - return [NamedArray(a, new_axes) for a in arrays] + from haliax.partitioning import auto_sharded + + return [auto_sharded(NamedArray(a, new_axes)) for a in arrays] def rename(array: NamedArray, renames: Mapping[Axis, Axis]) -> NamedArray: commit 991d0981b9d72b08d2127228b81b64bee4c41a7c Date: 2022-10-29T23:31:44-07:00 Use NamedArrays for data in gpt2_example (#42) * wip named array for data * add support for where for reduction functions * remove __array__ from NamedArray and add item * fully switch gpt2 over haliax * fix tests for all-named gpt2 * finish porting data stuff to haliax * "scalar" method on NamedArray that asserts scalar-ness before returning the underlying ndarray * fix test * add .item() to get loss value for logging diff --git a/src/haliax/__init__.py b/src/haliax/__init__.py index a4107ab..cf211c6 100644 --- a/src/haliax/__init__.py +++ b/src/haliax/__init__.py @@ -17,6 +17,7 @@ from .core import ( named, rearrange, rename, + roll, shape_checks, split, take, @@ -24,7 +25,7 @@ from .core import ( unflatten_axis, ) from .hof import fold, scan, vmap -from .ops import clip, trace, tril, triu, where +from .ops import isclose, clip, trace, tril, triu, where from .partitioning import auto_sharded, axis_mapping from .wrap import wrap_axiswise_call, wrap_elemwise_binary, wrap_elemwise_unary, wrap_reduction_call @@ -142,8 +143,8 @@ trunc = wrap_elemwise_unary(jnp.trunc) all = wrap_reduction_call(jnp.all) amax = wrap_reduction_call(jnp.amax) any = wrap_reduction_call(jnp.any) -argmax = wrap_reduction_call(jnp.argmax, single_axis_only=True) -argmin = wrap_reduction_call(jnp.argmin, single_axis_only=True) +argmax = wrap_reduction_call(jnp.argmax, single_axis_only=True, supports_where=False) +argmin = wrap_reduction_call(jnp.argmin, single_axis_only=True, supports_where=False) max = wrap_reduction_call(jnp.max) mean = wrap_reduction_call(jnp.mean) min = wrap_reduction_call(jnp.min) @@ -208,6 +209,7 @@ __all__ = [ "broadcast_axis", "named", "dot", + "roll", "split", "flatten_axes", "take", @@ -350,4 +352,5 @@ __all__ = [ "axis_mapping", "shape_checks", "are_shape_checks_enabled", + "isclose", ] diff --git a/src/haliax/core.py b/src/haliax/core.py index 303568b..788ff1c 100644 --- a/src/haliax/core.py +++ b/src/haliax/core.py @@ -1,5 +1,6 @@ import contextlib import functools as ft +import typing from dataclasses import dataclass from math import prod from types import EllipsisType @@ -83,8 +84,23 @@ class NamedArray: if s != tuple(a.size for a in self.axes): raise ValueError(f"Shape of underlying array {s} does not match shape of axes {self.axes}") - def __array__(self): - return self.array.__array__() + def item(self): + return self.array.item() + + def scalar(self) -> jnp.ndarray: + """ + Returns a scalar array corresponding to the value of this NamedArray. + Raises an error if the NamedArray is not scalar. + + We sometimes use this to convert a NamedArray to a scalar for returning a loss or similar. Losses + have to be jnp.ndarrays, not NamedArrays, so we need to convert them. item doesn't work inside jitted + functions because it returns a python scalar. + + You could just call array, but that's not as clear and doesn't assert. + """ + if self.array.ndim != 0: + raise ValueError(f"Expected scalar, got {self.array.ndim}-dimensional array") + return self.array # shape = property(lambda self: self.array.shape) dtype = property(lambda self: self.array.dtype) @@ -100,7 +116,15 @@ class NamedArray: assert len(tree) == 1 return cls(tree[0], axes=aux) - def _lookup_indices(self, axis: AxisSpec): + @typing.overload + def _lookup_indices(self, axis: Axis) -> Optional[int]: + ... + + @typing.overload + def _lookup_indices(self, axis: Sequence[Axis]) -> Tuple[Optional[int], ...]: + ... + + def _lookup_indices(self, axis: AxisSpec) -> Union[Optional[int], Tuple[Optional[int], ...]]: """ For a single axis, returns an int corresponding to the index of the axis. For multiple axes, returns a tuple of ints corresponding to the indices of the axes. @@ -603,6 +627,16 @@ def unbind(array: NamedArray, axis: Axis) -> List[NamedArray]: return [auto_sharded(NamedArray(a, new_axes)) for a in arrays] +def roll(array: NamedArray, shift: Union[int, Tuple[int, ...]], axis: AxisSpec) -> NamedArray: + """ + Roll an array along an axis or axes. Analogous to np.roll + """ + axis_indices = array._lookup_indices(axis) + if axis_indices is None: + raise ValueError(f"axis {axis} not found in {array}") + return NamedArray(jnp.roll(array.array, shift, axis_indices), array.axes) + + def rename(array: NamedArray, renames: Mapping[Axis, Axis]) -> NamedArray: for old, new in renames.items(): if old.size != new.size: @@ -846,6 +880,7 @@ __all__ = [ "flatten_axes", "unflatten_axis", "unbind", + "roll", "_broadcast_order", "broadcast_to", "broadcast_axis", diff --git a/src/haliax/nn/__init__.py b/src/haliax/nn/__init__.py index 21572bf..3fe0b15 100644 --- a/src/haliax/nn/__init__.py +++ b/src/haliax/nn/__init__.py @@ -1,9 +1,12 @@ import functools +from typing import Union import jax.nn as jnn import jax.numpy as jnp -from ..core import Axis, NamedArray +import haliax + +from ..core import Axis, AxisSpec, NamedArray from ..wrap import wrap_axiswise_call, wrap_elemwise_unary, wrap_reduction_call from .dropout import Dropout from .linear import Linear @@ -29,8 +32,9 @@ selu = wrap_elemwise_unary(jnn.selu) gelu = wrap_elemwise_unary(jnn.gelu) # TODO: glu = wrap_elemwise_unary(jnn.gelu) -logsumexp = wrap_reduction_call(jnn.logsumexp, False) +logsumexp = wrap_reduction_call(jnn.logsumexp, False, supports_where=False) +# TODO: support where in softmax, etc softmax = wrap_axiswise_call(jnn.softmax, False) # TODO: standardize has optional "mean" and "variance" arguments we need to support # standardize = wrap_normalization_call(jnn.standardize, False) @@ -38,9 +42,16 @@ log_softmax = wrap_axiswise_call(jnn.log_softmax, False) @functools.wraps(jnn.one_hot) -def one_hot(x: NamedArray, class_axis: Axis, *, dtype=jnp.float_) -> NamedArray: - array = jnn.one_hot(x.array, num_classes=class_axis.size, dtype=dtype) - return NamedArray(array, x.axes + (class_axis,)) +def one_hot(x: Union[NamedArray, int], class_axis: Axis, *, dtype=jnp.float_) -> NamedArray: + if isinstance(x, NamedArray): + array = jnn.one_hot(x.array, num_classes=class_axis.size, dtype=dtype) + return NamedArray(array, x.axes + (class_axis,)) + else: + assert isinstance(x, int) + assert class_axis.size > x and x >= -class_axis.size + + array = jnp.zeros(class_axis.size).at[x].set(1) + return haliax.named(array, class_axis) __all__ = [ diff --git a/src/haliax/ops.py b/src/haliax/ops.py index f2eb7ad..8691cdb 100644 --- a/src/haliax/ops.py +++ b/src/haliax/ops.py @@ -86,4 +86,11 @@ def triu(array: NamedArray, axis1: Axis, axis2: Axis, k=0) -> NamedArray: return NamedArray(inner, array.axes) -__all__ = ["trace", "where", "tril", "triu"] +def isclose(a: NamedArray, b: NamedArray, rtol=1e-05, atol=1e-08, equal_nan=False) -> NamedArray: + """Returns a boolean array where two arrays are element-wise equal within a tolerance.""" + a, b = broadcast_arrays(a, b) + # TODO: numpy supports an array atol and rtol, but we don't yet + return NamedArray(jnp.isclose(a.array, b.array, rtol=rtol, atol=atol, equal_nan=equal_nan), a.axes) + + +__all__ = ["trace", "where", "tril", "triu", "isclose"] diff --git a/src/haliax/wrap.py b/src/haliax/wrap.py index 21df9ef..08c693e 100644 --- a/src/haliax/wrap.py +++ b/src/haliax/wrap.py @@ -21,19 +21,27 @@ def wrap_elemwise_unary(f): return wrapper -def wrap_reduction_call(fn, single_axis_only: bool = False): +def wrap_reduction_call(fn, single_axis_only: bool = False, supports_where: bool = True): @functools.wraps(fn) - def wrapper(a, axis: Optional[AxisSpec] = None, **kwargs): - if kwargs.get("where", None) is not None: - raise ValueError("where is not supported yet for NamedArray") + def wrapper(a, axis: Optional[AxisSpec] = None, where: NamedArray = None, **kwargs): + kwargs = dict(kwargs) + if where is not None and not supports_where: + raise ValueError(f"where is not supported by {fn.__name__}") + if kwargs.get("out", None) is not None: raise ValueError("out is not supported yet for NamedArray") if kwargs.get("keepdims", False): raise ValueError("keepdims is not supported for NamedArray") def reduce_one_leaf(a): - nonlocal axis + nonlocal axis, where if isinstance(a, NamedArray): + if where is not None: + if not isinstance(where, NamedArray): + raise TypeError("where must be a NamedArray if a is a NamedArray") + where = broadcast_to(where, a.axes) + kwargs["where"] = where.array + if axis is None: result = fn(a.array, axis=None, **kwargs) if jnp.isscalar(result): @@ -56,6 +64,8 @@ def wrap_reduction_call(fn, single_axis_only: bool = False): return result return NamedArray(result, tuple(new_axes)) else: + if where is not None: + kwargs["where"] = where return fn(a, axis=axis, **kwargs) return jax.tree_util.tree_map(reduce_one_leaf, a, is_leaf=lambda x: isinstance(x, NamedArray)) diff --git a/tests/core_test.py b/tests/core_test.py index 9874098..cf1de36 100644 --- a/tests/core_test.py +++ b/tests/core_test.py @@ -90,6 +90,51 @@ def test_reduction_functions(): assert jnp.all(jnp.equal(hax.argmax(m1, axis=Height).array, jnp.argmax(m1.array, axis=0))) +def test_reduction_functions_with_where(): + Height = Axis("Height", 2) + Width = Axis("Width", 3) + Depth = Axis("Depth", 4) + + rand_m = jax.random.uniform(PRNGKey(0), (Height.size, Width.size, Depth.size)) + + m1 = NamedArray(rand_m, (Height, Width, Depth)) + + mask = m1 > 0.5 + jmask = m1.array > 0.5 + + # sum out everything + assert jnp.all(jnp.equal(hax.sum(m1, where=mask).array, jnp.sum(rand_m, where=jmask))) + # ensure it's a scalar + + assert jnp.all(jnp.equal(hax.sum(m1, axis=Height, where=mask).array, jnp.sum(rand_m, axis=0, where=jmask))) + assert jnp.all(jnp.equal(hax.sum(m1, axis=Width, where=mask).array, jnp.sum(rand_m, axis=1, where=jmask))) + + # sum out two axes + assert jnp.all( + jnp.equal(hax.sum(m1, axis=(Height, Width), where=mask).array, jnp.sum(rand_m, axis=(0, 1), where=jmask)) + ) + assert jnp.all( + jnp.equal(hax.sum(m1, axis=(Width, Height), where=mask).array, jnp.sum(rand_m, axis=(1, 0), where=jmask)) + ) + assert jnp.all( + jnp.equal(hax.sum(m1, axis=(Height, Depth), where=mask).array, jnp.sum(rand_m, axis=(0, 2), where=jmask)) + ) + + # sum out three axes + assert jnp.all( + jnp.equal( + hax.sum(m1, axis=(Height, Width, Depth), where=mask).array, + jnp.sum(rand_m, axis=(0, 1, 2), where=jmask), + ) + ) + assert jnp.all( + jnp.equal( + hax.sum(m1, axis=(Width, Height, Depth), where=mask).array, + jnp.sum(rand_m, axis=(1, 0, 2), where=jmask), + ) + ) + + def test_split(): Height = Axis("Height", 2) Width = Axis("Width", 3) commit 48ad5cb03db811fd390abf150e0668791c329908 Date: 2022-10-31T14:47:15-07:00 move paramter_axis_mapping silliness to trainer config diff --git a/src/haliax/partitioning.py b/src/haliax/partitioning.py index 878fe88..4ec4da0 100644 --- a/src/haliax/partitioning.py +++ b/src/haliax/partitioning.py @@ -293,16 +293,16 @@ def _cached_filter_eval_shape(fun, *args, **kwargs): return _eval_shape_cache[key] -def physical_axis_name(axis: Axis) -> Optional[PhysicalAxis]: - """Get the physical axis name for a logical axis from the global mapping. Returns none if the axis is not mapped.""" - mapping = _mapping_holder.thread_data.resource_mapping +def physical_axis_name(axis: Axis, mapping: Optional[ResourceMapping] = None) -> Optional[PhysicalAxis]: + """Get the physical axis name for a logical axis from the mapping. Returns none if the axis is not mapped.""" + mapping = mapping or _mapping_holder.thread_data.resource_mapping if mapping is None: return None else: - return mapping.get(axis.name, None) + return mapping.get(axis.name, None) # type: ignore -def physical_axis_size(axis: Axis) -> Optional[int]: +def physical_axis_size(axis: Axis, mapping: Optional[ResourceMapping] = None) -> Optional[int]: """Get the physical axis size for a logical axis. This is the product of the size of all physical axes that this logical axis is mapped to.""" # TODO: shouldn't be accessing this internal api, but... @@ -313,7 +313,7 @@ def physical_axis_size(axis: Axis) -> Optional[int]: except AttributeError: raise ValueError("No resource mapping found") - name: Union[None, str, Sequence[str]] = physical_axis_name(axis) + name: Union[None, str, Sequence[str]] = physical_axis_name(axis, mapping) if name is None: return None elif isinstance(name, str): @@ -328,9 +328,9 @@ def pspec_for_axis(axis: AxisSpec) -> PartitionSpec: return PartitionSpec(*(physical_axis_name(a) for a in axis)) -def round_axis_for_partitioning(axis: Axis) -> Axis: +def round_axis_for_partitioning(axis: Axis, mapping: Optional[ResourceMapping] = None) -> Axis: """Round an axis so that it's divisible by the size of the partition it's on""" - size = physical_axis_size(axis) + size = physical_axis_size(axis, mapping) if size is None: return axis else: commit eb978f789080f4dbaac222fc9f421724663ce908 Date: 2022-11-03T10:55:53-07:00 Checkpointer take 2 (#44) * add support for fancy checkpointing: save based on time, multiple schedules * delete old saving callback * pr comments * extract timedelta parsing for tests * i'm a dumb dumb * test checkpointer diff --git a/requirements.txt b/requirements.txt index 404f427..4f53e4e 100644 --- a/requirements.txt +++ b/requirements.txt @@ -12,3 +12,4 @@ git+https://github.com/deepmind/jmp#260e5ba01f46b10c579a61393e6c7e546aeae93e fsspec==2022.7.1 # pin this to make gcsfs happy furl tensorstore +pytimeparse commit 5f6514262b567dae576b6ace1bc3697506a9df1d Date: 2022-11-03T12:11:49-07:00 update dependencies and pin them some (#46) diff --git a/requirements.txt b/requirements.txt index 4f53e4e..485f49d 100644 --- a/requirements.txt +++ b/requirements.txt @@ -1,15 +1,15 @@ -equinox -transformers +equinox~=0.9.0 +transformers>=4.22.0 optax wandb pyrallis pyarrow zstandard -datasets -gcsfs +datasets~=2.6.0 +gcsfs==2022.10.0 braceexpand git+https://github.com/deepmind/jmp#260e5ba01f46b10c579a61393e6c7e546aeae93e -fsspec==2022.7.1 # pin this to make gcsfs happy +fsspec==2022.10.0 # pin this to make gcsfs happy furl tensorstore pytimeparse diff --git a/src/haliax/jax_utils.py b/src/haliax/jax_utils.py index eeb455a..915e1d5 100644 --- a/src/haliax/jax_utils.py +++ b/src/haliax/jax_utils.py @@ -5,7 +5,7 @@ import equinox as eqx import jax import numpy as np from chex import PRNGKey -from equinox.compile_utils import Static +from equinox.module import Static from jax import numpy as jnp from jax import random as jrandom from jaxtyping import PyTree diff --git a/src/haliax/partitioning.py b/src/haliax/partitioning.py index 4ec4da0..8c11552 100644 --- a/src/haliax/partitioning.py +++ b/src/haliax/partitioning.py @@ -200,11 +200,11 @@ def named_pjit( "mapping vis axis_mapping" ) - dynamic_fun, static_fun_leaves, static_fun_def = hashable_partition(fn, is_jax_array_like) + dynamic_fun, static_fun = hashable_partition(fn, is_jax_array_like) @functools.wraps(fn) def f(*args, **kwargs): - dynamic_argspec, static_argspec, static_arg_def = hashable_partition((args, kwargs), is_jax_array_like) + dynamic_argspec, static_argspec = hashable_partition((args, kwargs), is_jax_array_like) dynamic = (dynamic_fun, dynamic_argspec) if donate_args is not None or donate_kwargs is not None: @@ -215,12 +215,7 @@ def named_pjit( dynamic_donated = jax.tree_util.tree_map(lambda _: None, dynamic) dynamic_reserved = dynamic - static = ( - static_fun_def, - static_fun_leaves, - static_arg_def, - static_argspec, - ) + static = (static_fun, static_argspec) output_shape = _cached_filter_eval_shape(fn, *args, **kwargs) in_resources = infer_resource_partitions((dynamic_donated, dynamic_reserved), in_axis_resources) @@ -256,16 +251,10 @@ def _named_pjit_cache(fun_names, **jitkwargs): def fun_wrapped(dynamic_donated, dynamic_reserved, static): dynamic = eqx.combine(dynamic_donated, dynamic_reserved) dynamic_fun, dynamic_spec = dynamic + static_fun, static_spec = static - ( - static_fun_treedef, - static_fun_leaves, - static_spec_treedef, - static_spec_leaves, - ) = static - - fun = hashable_combine(dynamic_fun, static_fun_leaves, static_fun_treedef) - args, kwargs = hashable_combine(dynamic_spec, static_spec_leaves, static_spec_treedef) + fun = hashable_combine(dynamic_fun, static_fun) + args, kwargs = hashable_combine(dynamic_spec, static_spec) out = fun(*args, **kwargs) return out @@ -284,13 +273,11 @@ def _cached_filter_eval_shape(fun, *args, **kwargs): eval_shape is surprisingly expensive, so we cache it. We use this for named_pjit for evaluating resource partitions of the output. """ - dynamic, static, treedef = hashable_partition((fun, args, kwargs), is_jax_array_like) - key = (static, treedef) - - if key not in _eval_shape_cache: - _eval_shape_cache[key] = filter_eval_shape(fun, *args, **kwargs) + dynamic, static = hashable_partition((fun, args, kwargs), is_jax_array_like) + if static not in _eval_shape_cache: + _eval_shape_cache[static] = filter_eval_shape(fun, *args, **kwargs) - return _eval_shape_cache[key] + return _eval_shape_cache[static] def physical_axis_name(axis: Axis, mapping: Optional[ResourceMapping] = None) -> Optional[PhysicalAxis]: commit 1cc043e7293d609191f78ae44c27e9a94ec42e8c Date: 2022-11-03T13:52:49-07:00 Pip package, update readme, contributing.md (#45) * setup script for levanter * update README.md with some getting started * shamelessly copy CONTRIBUTING.md from mistral * change save interval for nano diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md new file mode 100644 index 0000000..82f9c2f --- /dev/null +++ b/CONTRIBUTING.md @@ -0,0 +1,104 @@ +Contributing +============ + +Levanter is a growing code base, and we are excited for other folks to get involved. The instructions below walk you through our dev setup and how to submit a PR. + +Dev Installation +---------------- + +First follow the same instructions as provided for the [Levanter README](README.md) to install Levanter. + +The main addition for a dev environment is to install [`pre-commit`](https://pre-commit.com/): + + pre-commit install + +This will set up git hook scripts that ensure your code is formatted in a manner consistent with +the repo. If any problems are found, the appropriate files will be updated with fixes. You will +need to review and commit the fixed files. + +Forking The Repo +---------------- + +To submit changes, you will need to work off of a fork of the repo and issue a pull request. + +There are two easy ways to fork the repo. + +If you have installed the [GitHub CLI](https://cli.github.com/) you can issue this command: + + gh repo fork stanford-crfm/levanter --clone=true + +This will create the fork and clone the repo into your current directory. + +Alternatively you can fork the repo in your browser. While logged in to your GitHub account, +go to the [Levanter repo](https://github.com/stanford-crfm/levanter) and click on the Fork +button in the upper left hand corner. + +You can then clone your forked version of the Levanter repo like any other GitHub repo. + +Create A Branch For Your Submission +----------------------------------- + +You will generally need to create a branch of `main` for your code changes. In general every submission +should be focused on a specific set of bug fixes or new features that are coherently +related. Changes that are not related belong in different submissions. So you should +be able to give your branch an informative name such as `checkpointer-time-bugfix` . + +You can create a branch off of `main` with this command: + + git checkout -b checkpointer-time-bugfix main + +Implement Your Changes +---------------------- + +As you implement your changes in your feature branch, the git hook scripts will check your +code for proper formatting as you make commits. Make sure you have run `pre-commit install` +before you start making commits. + +You can also check all files in the current branch with this command: + + pre-commit run --all-files + +When your changes are operational you should verify that the current tests are passing. + +Set up your environment for running the tests: + + export PYTHONPATH=/path/to/levanter/src + wandb offline + +You can run the tests with this command: + + pytest tests + +You should add tests for any functionality you have added consistent with the [pytest](https://docs.pytest.org/en/6.2.x/) format +of the existing tests. + +Submit Pull Request +------------------- + +When your feature branch is ready you should submit a pull request. + +Detailed instructions for submtting a pull request from a fork can be found on [Github Docs](https://docs.github.com/en/github/collaborating-with-pull-requests/proposing-changes-to-your-work-with-pull-requests/creating-a-pull-request-from-a-fork). + +The steps basically are: + +1. While logged in to your GitHub, go to the original [Levanter repo pull request page](https://github.com/stanford-crfm/levanter/pulls) +2. Click on the highlighted text stating "compare across forks". +3. Set the base repository to `stanford-crfm/levanter` and the base branch to `main`. +4. Set the head repository to `your-org/levanter` and the compare branch to `your-feature-branch`. +5. Click on the "Create pull request" button and complete the pull request form. + +When submitting your pull request, you should provide a detailed description of what you've done. + +The following is a useful template: + + ## Description + A brief and concise description of what your pull request is trying to accomplish. + + ## Fixes Issues + A list of issues/bugs with # references. (e.g., #123) + + ## Unit test coverage + Are there unit tests in place to make sure your code is functioning correctly? + + ## Known breaking changes/behaviors + Does this break anything in Levanter's existing user interface? If so, what is it and how is it addressed? diff --git a/README.md b/README.md index c58291e..9875bfe 100644 --- a/README.md +++ b/README.md @@ -14,4 +14,49 @@ on Foundation Models (CRFM)](https://crfm.stanford.edu/). > — Patrick Rothfuss, *The Name of the Wind* Haliax is a module (currently) inside Levanter for named tensors, modeled on Alexander Rush's [Tensor Considered Harmful](https://arxiv.org/abs/1803.09868). -It's designed to work with Equinox to make constructing distributed models easier. +It's designed to work with Jax and Equinox to make constructing distributed models easier. + + +## Getting Started with Levanter + +### Installation + +First install the appropriate version of Jax for your system. See [Jax's installation instructions](https://github.com/google/jax/blob/main/README.md#installation) +as it varies from platform to platform. + +If you're using a TPU, more complete documentation for setting that up is available [here](docs/Getting-Started-TPU-VM.md). + +Now clone this repository and install it with pip: + +```bash +git clone https://github.com/stanford-crfm/levanter.git +cd levanter +pip install -e . +wandb login # optional, we use wandb for logging +``` + +TODO: put things on pypi, etc + + +### Training a GPT2-nano + +As a kind of hello world, here's how you can train a GPT2-nano model on a small dataset. + +```bash +python examples/gpt2_example.py --config_path config/gpt2_nano.yaml +``` + +This will train a GPT2-nano model on the [WikiText-2](https://blog.einstein.ai/the-wikitext-long-term-dependency-language-modeling-dataset/) dataset. +You can change the dataset by changing the `dataset` field in the config file. + +The config file is a [Pyrallis](https://github.com/eladrich/pyrallis) config file. Pyrallis is yet-another yaml-to-dataclass library. +You can use `--help` or poke around other configs to see all the options available to you. + + +## Contributing + +We welcome contributions! Please see [CONTRIBUTING.md](CONTRIBUTING.md) for more information. + +## License + +Levanter is licensed under the Apache License, Version 2.0. See [LICENSE](LICENSE) for the full license text. diff --git a/requirements.txt b/requirements.txt index 485f49d..daf632f 100644 --- a/requirements.txt +++ b/requirements.txt @@ -8,7 +8,7 @@ zstandard datasets~=2.6.0 gcsfs==2022.10.0 braceexpand -git+https://github.com/deepmind/jmp#260e5ba01f46b10c579a61393e6c7e546aeae93e +jmp @ git+https://github.com/deepmind/jmp#7b3ae548154625a56a6dbdb03bc07d4f599c37b2 fsspec==2022.10.0 # pin this to make gcsfs happy furl tensorstore commit 9ac9f9e8c60daa42546d572ac6ca37c252aaab21 Date: 2022-11-03T16:34:42-07:00 move types to their own file (#51) diff --git a/src/haliax/__init__.py b/src/haliax/__init__.py index cf211c6..dea4ac9 100644 --- a/src/haliax/__init__.py +++ b/src/haliax/__init__.py @@ -5,8 +5,6 @@ import haliax.random as random from haliax import nn as nn from .core import ( - Axis, - AxisSpec, NamedArray, are_shape_checks_enabled, broadcast_axis, @@ -25,8 +23,9 @@ from .core import ( unflatten_axis, ) from .hof import fold, scan, vmap -from .ops import isclose, clip, trace, tril, triu, where +from .ops import clip, isclose, trace, tril, triu, where from .partitioning import auto_sharded, axis_mapping +from .types import Axis, AxisSpec from .wrap import wrap_axiswise_call, wrap_elemwise_binary, wrap_elemwise_unary, wrap_reduction_call diff --git a/src/haliax/core.py b/src/haliax/core.py index 788ff1c..842b944 100644 --- a/src/haliax/core.py +++ b/src/haliax/core.py @@ -14,19 +14,9 @@ import haliax from haliax.jax_utils import is_jax_array_like from haliax.util import ensure_tuple +from .types import Axis, AxisSpec, PrecisionLike, Scalar -@dataclass(frozen=True) -class Axis: - name: str - size: int - - def alias(self, new_name: str): - return Axis(new_name, self.size) - - -AxisSpec = Union[Axis, Sequence[Axis]] -Scalar = Union[float, int] NamedNumeric = Union[Scalar, "NamedArray"] _ENABLE_SHAPE_CHECKS = True @@ -210,7 +200,7 @@ class NamedArray: def cumsum(self, axis: Optional[AxisSpec] = None, *, dtype=None) -> "NamedArray": return haliax.cumsum(self, axis=axis, dtype=dtype) - def dot(self, axis: AxisSpec, b, *, precision=None) -> "NamedArray": + def dot(self, axis: AxisSpec, b, *, precision: PrecisionLike = None) -> "NamedArray": return dot(axis, self, b, precision=precision) @property @@ -492,7 +482,7 @@ def take(array: NamedArray, axis: Axis, index: Union[int, NamedArray]) -> NamedA return NamedArray(new_array, new_axes) -def dot(axis: AxisSpec, *arrays: NamedArray, precision=None) -> NamedArray: +def dot(axis: AxisSpec, *arrays: NamedArray, precision: PrecisionLike = None) -> NamedArray: """Returns the tensor product of two NamedArrays. The axes `axis` are contracted over, and any other axes that are shared between the arrays are batched over. Non-contracted Axes in one that are not in the other are preserved. @@ -868,8 +858,6 @@ def broadcast_axis(a: NamedArray, axis: AxisSpec) -> NamedArray: __all__ = [ - "Axis", - "AxisSpec", "NamedArray", "concat_axis_specs", "dot", diff --git a/src/haliax/hof.py b/src/haliax/hof.py index 26c52ea..a61fb42 100644 --- a/src/haliax/hof.py +++ b/src/haliax/hof.py @@ -9,9 +9,10 @@ import jax.lax as lax from equinox.custom_types import BoolAxisSpec from jaxtyping import PyTree -from .core import Axis, NamedArray +from .core import NamedArray from .jax_utils import broadcast_prefix, combine, is_jax_array_like from .partitioning import auto_sharded, physical_axis_name +from .types import Axis from .util import is_jax_or_hax_array_like, is_named_array diff --git a/src/haliax/nn/__init__.py b/src/haliax/nn/__init__.py index 3fe0b15..43c2649 100644 --- a/src/haliax/nn/__init__.py +++ b/src/haliax/nn/__init__.py @@ -6,7 +6,8 @@ import jax.numpy as jnp import haliax -from ..core import Axis, AxisSpec, NamedArray +from ..core import NamedArray +from ..types import Axis, AxisSpec from ..wrap import wrap_axiswise_call, wrap_elemwise_unary, wrap_reduction_call from .dropout import Dropout from .linear import Linear diff --git a/src/haliax/nn/dropout.py b/src/haliax/nn/dropout.py index aa5c790..91d9994 100644 --- a/src/haliax/nn/dropout.py +++ b/src/haliax/nn/dropout.py @@ -4,7 +4,8 @@ import equinox as eqx import jax import haliax -from haliax.core import AxisSpec, NamedArray +from haliax.core import NamedArray +from haliax.types import AxisSpec from haliax.util import ensure_tuple diff --git a/src/haliax/nn/linear.py b/src/haliax/nn/linear.py index ce767cc..d63d1ba 100644 --- a/src/haliax/nn/linear.py +++ b/src/haliax/nn/linear.py @@ -5,7 +5,8 @@ import jax import haliax as hax -from ..core import AxisSpec, NamedArray +from ..core import NamedArray +from ..types import AxisSpec class Linear(eqx.Module): diff --git a/src/haliax/nn/normalization.py b/src/haliax/nn/normalization.py index 92808d8..9d76f15 100644 --- a/src/haliax/nn/normalization.py +++ b/src/haliax/nn/normalization.py @@ -4,7 +4,8 @@ import equinox as eqx import haliax as hax -from ..core import AxisSpec, NamedArray +from ..core import NamedArray +from ..types import AxisSpec class LayerNorm(eqx.Module): diff --git a/src/haliax/ops.py b/src/haliax/ops.py index 8691cdb..1b7719a 100644 --- a/src/haliax/ops.py +++ b/src/haliax/ops.py @@ -3,14 +3,8 @@ from typing import Union import jax import jax.numpy as jnp -from .core import ( - Axis, - NamedArray, - NamedNumeric, - broadcast_arrays, - broadcast_arrays_and_return_axes, - raw_array_or_scalar, -) +from .core import NamedArray, NamedNumeric, broadcast_arrays, broadcast_arrays_and_return_axes, raw_array_or_scalar +from .types import Axis def trace(array: NamedArray, axis1: Axis, axis2: Axis, offset=0, dtype=None) -> NamedArray: diff --git a/src/haliax/partitioning.py b/src/haliax/partitioning.py index 8c11552..eb78984 100644 --- a/src/haliax/partitioning.py +++ b/src/haliax/partitioning.py @@ -14,8 +14,9 @@ from jax.experimental.pjit import FROM_GDA, pjit, with_sharding_constraint from jax.interpreters.pxla import PartitionSpec from jaxtyping import PyTree -from .core import Axis, AxisSpec, NamedArray +from .core import NamedArray from .jax_utils import filter_eval_shape, is_jax_array_like +from .types import Axis, AxisSpec from .util import StringHolderEnum, ensure_tuple, is_named_array diff --git a/src/haliax/random.py b/src/haliax/random.py index a8fdb5f..27d9438 100644 --- a/src/haliax/random.py +++ b/src/haliax/random.py @@ -8,11 +8,12 @@ import jax import jax.random as jrandom # TODO: handle broadcasting of array args to random functions (e.g. minval and maxval for uniform) -from haliax.core import Axis, NamedArray +from haliax.core import NamedArray from haliax.util import ensure_tuple from .jax_utils import named_call from .partitioning import auto_sharded, physical_axis_size, pspec_for_axis +from .types import Axis def _wrap_random_function(func): diff --git a/src/haliax/types.py b/src/haliax/types.py new file mode 100644 index 0000000..4eb6e1b --- /dev/null +++ b/src/haliax/types.py @@ -0,0 +1,19 @@ +from dataclasses import dataclass +from typing import Sequence, Tuple, Union + +from jax.lax import Precision + + +@dataclass(frozen=True) +class Axis: + name: str + size: int + + def alias(self, new_name: str): + return Axis(new_name, self.size) + + +AxisSpec = Union[Axis, Sequence[Axis]] +Scalar = Union[float, int] + +PrecisionLike = Union[None, str, Precision, Tuple[str, str], Tuple[Precision, Precision]] diff --git a/src/haliax/wrap.py b/src/haliax/wrap.py index 08c693e..df72187 100644 --- a/src/haliax/wrap.py +++ b/src/haliax/wrap.py @@ -4,9 +4,11 @@ from typing import Optional import jax import jax.numpy as jnp -from haliax.core import AxisSpec, NamedArray, _broadcast_order, broadcast_to +from haliax.core import NamedArray, _broadcast_order, broadcast_to from haliax.util import ensure_tuple +from .types import AxisSpec + def wrap_elemwise_unary(f): """Wraps a unary elementwise function to take and return NamedArrays""" diff --git a/tests/test_nn.py b/tests/test_nn.py index b460e60..ea18ae5 100644 --- a/tests/test_nn.py +++ b/tests/test_nn.py @@ -19,7 +19,7 @@ def _compare_eqx_and_haliax(hax_mod: eqx.Module, eqx_mod: eqx.Module): def test_layer_norm(): - H = hax.Axis("H", 10) + H = Axis("H", 10) hax_ln = hax.nn.LayerNorm(H) eqx_ln = eqx.nn.LayerNorm(shape=(H.size,)) @@ -30,7 +30,7 @@ def test_layer_norm(): def test_dropout(): - H = hax.Axis("H", 10) + H = Axis("H", 10) key = jrandom.PRNGKey(0) hax_dropout = hax.nn.Dropout(0.5) eqx_dropout = eqx.nn.Dropout(0.5) commit 3147312f05885eaaa40feeefbc0996d75f7d7019 Date: 2022-11-07T23:49:50-08:00 Forgetful Causal Masking and Alibi bias (#53) * messing around with a factored out implementation of attention/alibi * clean up and generalize attention, add fcm masking * add simple test for fcm * sample the mask ratio like the paper recommends * rough cut at fcm in gpt2 * fix weird deletion * more comments, better names for fcm diff --git a/src/haliax/core.py b/src/haliax/core.py index 842b944..3c562a8 100644 --- a/src/haliax/core.py +++ b/src/haliax/core.py @@ -763,22 +763,37 @@ def _broadcast_axes( return tuple(x for x in b_axes if x not in a_axes) + a_axes -def broadcast_to(a: NamedArray, axes: Tuple[Axis, ...], ensure_order: bool = True) -> NamedArray: +def broadcast_to( + a: NamedArray, axes: AxisSpec, ensure_order: bool = True, enforce_no_extra_axes: bool = True +) -> NamedArray: """ - Broadcasts a to the given axes. If ensure_order is True (default), then the returned array will have the same axes - in the same order as the given axes. Otherwise, the axes may not be moved + Broadcasts a so that it has the given axes. + If ensure_order is True (default), then the returned array will have the same axes in the same order as the given + axes. Otherwise, the axes may not be moved + + If enforce_no_extra_axes is True and the array has axes that are not in axes, then a ValueError is raised. """ + + axes = ensure_tuple(axes) + if a.axes == axes: return a to_add = tuple(ax for ax in axes if ax not in a.axes) + all_axes = to_add + a.axes + + if enforce_no_extra_axes and len(all_axes) != len(axes): + raise ValueError(f"Cannot broadcast {a} to {axes}: extra axes present") + + extra_axes = tuple(ax for ax in a.axes if ax not in axes) + # broadcast whatever we need to the front and reorder - a_array = jnp.broadcast_to(a.array, [ax.size for ax in to_add] + [ax.size for ax in a.axes]) - a = NamedArray(a_array, to_add + a.axes) + a_array = jnp.broadcast_to(a.array, [ax.size for ax in all_axes]) + a = NamedArray(a_array, all_axes) if ensure_order: - a = rearrange(a, axes) + a = rearrange(a, axes + extra_axes) return a @@ -847,14 +862,13 @@ def broadcast_arrays_and_return_axes( def broadcast_axis(a: NamedArray, axis: AxisSpec) -> NamedArray: """ - Broadcasts a, ensuring that it has all the axes in axis + Broadcasts a, ensuring that it has all the axes in axis. + broadcast_axis is an alias for broadcast_to(a, axis, enforce_no_extra_axes=False, ensure_order=False) """ if isinstance(axis, Axis) and axis in a.axes: return a - axis = ensure_tuple(axis) - new_axes = tuple(ax for ax in axis if ax not in a.axes) - return broadcast_to(a, new_axes + a.axes) + return broadcast_to(a, axis, enforce_no_extra_axes=False, ensure_order=False) __all__ = [ diff --git a/src/haliax/nn/__init__.py b/src/haliax/nn/__init__.py index 43c2649..56e808f 100644 --- a/src/haliax/nn/__init__.py +++ b/src/haliax/nn/__init__.py @@ -5,9 +5,10 @@ import jax.nn as jnn import jax.numpy as jnp import haliax +import haliax.nn.attention as attention from ..core import NamedArray -from ..types import Axis, AxisSpec +from ..types import Axis from ..wrap import wrap_axiswise_call, wrap_elemwise_unary, wrap_reduction_call from .dropout import Dropout from .linear import Linear @@ -49,13 +50,14 @@ def one_hot(x: Union[NamedArray, int], class_axis: Axis, *, dtype=jnp.float_) -> return NamedArray(array, x.axes + (class_axis,)) else: assert isinstance(x, int) - assert class_axis.size > x and x >= -class_axis.size + assert class_axis.size > x >= -class_axis.size - array = jnp.zeros(class_axis.size).at[x].set(1) + array = jnp.zeros(class_axis.size, dtype=dtype).at[x].set(1) return haliax.named(array, class_axis) __all__ = [ + "attention", "relu", "relu6", "sigmoid", diff --git a/src/haliax/nn/attention.py b/src/haliax/nn/attention.py new file mode 100644 index 0000000..f8c7b7c --- /dev/null +++ b/src/haliax/nn/attention.py @@ -0,0 +1,199 @@ +import math +from typing import List, Optional + +import jax +import jax.numpy as jnp +from jax.random import PRNGKey + +import haliax +import haliax.random as hrandom +from haliax.core import NamedArray +from haliax.types import Axis, AxisSpec, PrecisionLike + + +# With attention we usually distinguish between the mask and the bias, though the former is just a special case of the +# latter. In practice, the mask is a boolean array that is applied after the softmax, while the bias is a float array +# that is applied before the softmax. + +# because we use named axis we can be fairly loose about the shape of masks and biases: want to have a different +# mask for each head? fine. want to broadcast across the key sequence length? fine. etc etc + + +def dot_product_attention_weights( + Head: Axis, + KSeqLen: AxisSpec, + query: NamedArray, + key: NamedArray, + mask: Optional[NamedArray] = None, + bias: Optional[NamedArray] = None, + attention_dtype: Optional[jnp.dtype] = None, + precision: PrecisionLike = None, +) -> NamedArray: + """ + NamedArray version of dot product attention. Computes the logits for the attention weights. Note that the + "SeqLen" axis in query must be distinct from the "SeqLen" axis in key. + + :param Head: Axis of head dimension + :param KSeqLen: Axis of key sequence length. Can be an AxisSpec to attend along more than one axis. + :param query: NamedArray of shape (QSeqLen, HeadDim) + :param key: NamedArray of shape (KSeqLen, HeadDim) + :param mask: Optional[NamedArray] broadcast compatible with (HeadDim, QSeqLen, KSeqLen). Should be boolean, applied after softmax. + :param bias: Optional[NamedArray] broadcast compatible with (HeadDim, QSeqLen, KSeqLen). Should be float, applied before softmax. + :param attention_dtype: Optional dtype to use for attention + :param precision: PrecisionLike for dot product. See precision argument to jax.lax.dot_general + :return: NamedArray of shape (QSeqLen, KSeqLen) + """ + # cf https://github.com/google/flax/blob/509bf97ea272e130d932920f45307ac98947d994/flax/linen/attention.py#L40 + import haliax.nn as hnn + + orig_dtype = query.dtype + query = query / jnp.sqrt(Head.size) + + if attention_dtype is not None: + query = query.astype(attention_dtype) + key = key.astype(attention_dtype) + + weights = haliax.dot(Head, query, key, precision=precision) + + if bias is not None: + weights = weights + bias + + weights = hnn.softmax(weights, axis=KSeqLen) + + if mask is not None: + weights = weights * mask + + return weights.astype(orig_dtype) + + +def dot_product_attention( + QSeqLen: Axis, + KSeqLen: Axis, + HeadDim: Axis, + query: NamedArray, + key: NamedArray, + value: NamedArray, + mask: Optional[NamedArray] = None, + bias: Optional[NamedArray] = None, + attention_dtype: Optional[jnp.dtype] = None, + precision: PrecisionLike = None, +) -> NamedArray: + """ + NamedArray version of dot product attention. This can be multi-headed or not. + + :param QSeqLen: Axis of sequence length + :param KSeqLen: Axis of key sequence length + :param HeadDim: Axis of head dimension + :param query: NamedArray of shape (QSeqLen, HeadDim) + :param key: NamedArray of shape (KSeqLen, HeadDim) + :param value: NamedArray of shape (KSeqLen, HeadDim) + :param mask: Optional[NamedArray] broadcast compatible with (HeadDim, QSeqLen, KSeqLen). Should be boolean, applied after softmax. + :param bias: Optional[NamedArray] broadcast compatible with (HeadDim, QSeqLen, KSeqLen). Should be float, applied before softmax. + :param attention_dtype: Optional dtype to use for attention + :param precision: PrecisionLike for dot product. See precision argument to jax.lax.dot_general + :return: NamedArray of shape (QSeqLen, HeadDim) + """ + # cf https://github.com/google/flax/blob/509bf97ea272e130d932920f45307ac98947d994/flax/linen/attention.py#L125 + + # rename key/value length axis if it's the same as the query length axis + if KSeqLen == QSeqLen: + KSeqLen = QSeqLen.alias(KSeqLen.name + "_key") + key = key.rename({KSeqLen: QSeqLen}) + value = value.rename({KSeqLen: QSeqLen}) + + weights = dot_product_attention_weights(HeadDim, KSeqLen, query, key, mask, bias, attention_dtype, precision) + + return haliax.dot(KSeqLen, weights, value) + + +def mask_to_bias(mask: NamedArray, mask_value: float = -1e9) -> NamedArray: + return mask * mask_value + + +def combine_masks_and(mask1: Optional[NamedArray], mask2: Optional[NamedArray]) -> Optional[NamedArray]: + if mask1 is None: + return mask2 + if mask2 is None: + return mask1 + return mask1 & mask2 + + +def combine_masks_or(mask1: Optional[NamedArray], mask2: Optional[NamedArray]) -> Optional[NamedArray]: + if mask1 is None: + return mask2 + if mask2 is None: + return mask1 + return mask1 | mask2 + + +def causal_mask(QSeqLen: Axis, KSeqLen: Axis) -> NamedArray: + """ + Creates a causal mask for attention. + + :param QSeqLen: Axis of query sequence length + :param KSeqLen: Axis of key sequence length + :return: NamedArray of shape (QSeqLen, KSeqLen) + """ + # copilot wrote this and i'm just blown away + return haliax.arange(QSeqLen).broadcast_axis(KSeqLen) >= haliax.arange(KSeqLen).broadcast_axis(QSeqLen) + + +def dropout_mask(axes: AxisSpec, dropout_rate: float, *, key: PRNGKey) -> NamedArray: + """ + Really just an alias for haliax.random.bernoulli. You can pass in e.g. Head, QSeqLen and KSeqLen + """ + return hrandom.bernoulli(key, shape=axes, p=1 - dropout_rate) + + +def forgetful_causal_mask(KSeqLen: Axis, mask_prob: float, sample_prob: bool = True, *, key: PRNGKey) -> NamedArray: + """ + Forgetful Context Masking a la https://arxiv.org/abs/2210.13432. Randomly drops out positions from the key sequence. + Reportedly better than normal attention dropout. Almost certainly faster. + + You're always allowed to attend to the 0th position. (They say BOS token, but we don't always start with bos) + + :param KSeqLen: Axis of key sequence length + :param mask_prob: Probability a position to mask + :param sample_prob: If True, sample the prob between 0 and the provided prob (this is what the paper does) + """ + zeroth_on = haliax.nn.one_hot(0, KSeqLen, dtype=jnp.bool_) # always allow 0th position + if mask_prob == 0: + return jnp.ones((KSeqLen.size,), dtype=jnp.bool_) + elif mask_prob == 1: + return zeroth_on + else: + if sample_prob: + key, subkey = jax.random.split(key) + mask_prob = jax.random.uniform(subkey, shape=(), minval=0, maxval=mask_prob) + base: NamedArray = hrandom.bernoulli(key, shape=(KSeqLen,), p=1 - mask_prob) + return base | zeroth_on + + +def _get_alibi_slopes(heads: int) -> List[float]: + # from https://github.com/ofirpress/attention_with_linear_biases/blob/a35aaca144e0eb6b789dfcb46784c4b8e31b7983/fairseq/models/transformer.py#L742 + def get_slopes_power_of_2(n: int): + start = 2 ** (-(2 ** -(math.log2(n) - 3))) + ratio = start + return [start * ratio**i for i in range(n)] + + if math.log2(heads).is_integer(): + return get_slopes_power_of_2(heads) + closest_power_of_2 = 2 ** math.floor(math.log2(heads)) + return ( + get_slopes_power_of_2(closest_power_of_2) + + get_slopes_power_of_2(2 * closest_power_of_2)[0::2][: heads - closest_power_of_2] + ) + + +def alibi_attention_bias(Heads: Axis, SeqLen: Axis) -> NamedArray: + """ + Creates an attention bias for alibi attention. + + :param SeqLen: Axis of sequence length + :param Heads: Axis of heads + :return: NamedArray of shape (Heads, QSeqLen) + """ + slopes = haliax.named(jnp.array(_get_alibi_slopes(Heads.size)), Heads) + positions = haliax.arange(SeqLen).broadcast_axis(Heads) + + return slopes * positions diff --git a/tests/test_attention.py b/tests/test_attention.py new file mode 100644 index 0000000..adc393d --- /dev/null +++ b/tests/test_attention.py @@ -0,0 +1,50 @@ +from jax.random import PRNGKey + +import haliax as hax +from haliax.nn.attention import alibi_attention_bias, dot_product_attention_weights, forgetful_causal_mask + + +def test_alibi_attention_bias(): + KeySeqLen = hax.Axis("KeySeqLen", 20) + NumHeads = hax.Axis("NumHeads", 1) + Hid = hax.Axis("Hid", 8) + + bias = alibi_attention_bias(NumHeads, KeySeqLen) + + query = hax.ones((NumHeads, Hid)) + key = hax.ones((KeySeqLen, NumHeads, Hid)) + + weights_bias = dot_product_attention_weights(Hid, KeySeqLen, query, key, bias=bias) + weights_no_bias = dot_product_attention_weights(Hid, KeySeqLen, query, key) + + assert weights_bias.take(KeySeqLen, -1).item() > weights_bias.take(KeySeqLen, -2).item() + assert weights_bias.take(KeySeqLen, -1).item() > weights_no_bias.take(KeySeqLen, -1).item() + + assert weights_no_bias.take(KeySeqLen, -1).item() == weights_no_bias.take(KeySeqLen, -2).item() + + +def test_fcm_attention_mask(): + KeySeqLen = hax.Axis("KeySeqLen", 20) + + mask = forgetful_causal_mask(KeySeqLen, mask_prob=0.6, sample_prob=False, key=PRNGKey(0)) + + assert mask.axes == (KeySeqLen,) + assert mask.array[0].item() == 1 + + assert mask.astype(float).sum().item() <= KeySeqLen.size + + QuerySeqLen = hax.Axis("QuerySeqLen", 10) + Head = hax.Axis("Head", 8) + + query = hax.arange(QuerySeqLen).broadcast_axis(Head) + key = hax.arange(KeySeqLen).broadcast_axis(Head) + + weights = dot_product_attention_weights(Head, KeySeqLen, query, key, mask=mask) + + # check that all masked out values are zero + # TODO: think about how to make this work with named arrays + weights = weights.rearrange((KeySeqLen, QuerySeqLen)).array + mask = mask.array + + assert weights[mask == 0].sum() == 0 + assert weights[mask == 1].sum() > 0 diff --git a/tests/test_ops.py b/tests/test_ops.py index 7aedf04..2f65a7f 100644 --- a/tests/test_ops.py +++ b/tests/test_ops.py @@ -3,7 +3,7 @@ import pytest from jax.random import PRNGKey import haliax as hax -from haliax import Axis +from haliax import Axis, NamedArray def test_trace(): @@ -76,7 +76,25 @@ def test_add_scalar(): assert jnp.all(jnp.isclose(named3.array, named1.array + 1.0)) -# TODO: tests for other ops +def test_add_no_overlap(): + Height = Axis("Height", 10) + Width = Axis("Width", 3) + Depth = Axis("Depth", 4) + + named1: NamedArray = hax.random.uniform(PRNGKey(0), (Height)) + named2 = hax.random.uniform(PRNGKey(1), (Width, Depth)) + + with pytest.raises(ValueError): + _ = named1 + named2 + + named3 = named1.broadcast_to((Height, Width, Depth)) + named2 + + assert jnp.all( + jnp.isclose(named3.array, named1.array.reshape((-1, 1, 1)) + named2.array.reshape((1,) + named2.array.shape)) + ) + + +# TODO: tests for other ops: def test_where(): commit 8bb11db6543c35d48d9fbb815767d4a32abd43ef Date: 2022-11-08T23:06:02-08:00 NamedNumeric->NamedOrNumeric diff --git a/src/haliax/core.py b/src/haliax/core.py index 3c562a8..fa14b47 100644 --- a/src/haliax/core.py +++ b/src/haliax/core.py @@ -17,7 +17,7 @@ from haliax.util import ensure_tuple from .types import Axis, AxisSpec, PrecisionLike, Scalar -NamedNumeric = Union[Scalar, "NamedArray"] +NamedOrNumeric = Union[Scalar, "NamedArray"] _ENABLE_SHAPE_CHECKS = True @@ -807,24 +807,24 @@ def broadcast_arrays( @overload def broadcast_arrays( - *arrays: NamedNumeric, require_subset: bool = True, ensure_order: bool = True -) -> Tuple[NamedNumeric, ...]: + *arrays: NamedOrNumeric, require_subset: bool = True, ensure_order: bool = True +) -> Tuple[NamedOrNumeric, ...]: ... def broadcast_arrays( - *arrays: NamedNumeric, + *arrays: NamedOrNumeric, require_subset: bool = True, ensure_order: bool = True, -) -> Tuple[NamedNumeric, ...]: +) -> Tuple[NamedOrNumeric, ...]: return broadcast_arrays_and_return_axes(*arrays, require_subset=require_subset, ensure_order=ensure_order)[0] def broadcast_arrays_and_return_axes( - *arrays: NamedNumeric, + *arrays: NamedOrNumeric, require_subset: bool = True, ensure_order: bool = True, -) -> Tuple[Tuple[NamedNumeric, ...], Tuple[Axis, ...]]: +) -> Tuple[Tuple[NamedOrNumeric, ...], Tuple[Axis, ...]]: """ Broadcasts a sequence of arrays to a common set of axes. @@ -892,7 +892,7 @@ __all__ = [ ] -def raw_array_or_scalar(x: NamedNumeric): +def raw_array_or_scalar(x: NamedOrNumeric): if isinstance(x, NamedArray): return x.array return x diff --git a/src/haliax/ops.py b/src/haliax/ops.py index 1b7719a..fbfadab 100644 --- a/src/haliax/ops.py +++ b/src/haliax/ops.py @@ -3,7 +3,7 @@ from typing import Union import jax import jax.numpy as jnp -from .core import NamedArray, NamedNumeric, broadcast_arrays, broadcast_arrays_and_return_axes, raw_array_or_scalar +from .core import NamedArray, NamedOrNumeric, broadcast_arrays, broadcast_arrays_and_return_axes, raw_array_or_scalar from .types import Axis @@ -26,7 +26,7 @@ def trace(array: NamedArray, axis1: Axis, axis2: Axis, offset=0, dtype=None) -> return NamedArray(inner, axes) -def where(condition: Union[NamedNumeric, bool], x: NamedNumeric, y: NamedNumeric) -> NamedArray: +def where(condition: Union[NamedOrNumeric, bool], x: NamedOrNumeric, y: NamedOrNumeric) -> NamedArray: """Like jnp.where, but with named axes. This version currently only accepts the three argument form.""" # TODO: support the one argument form @@ -54,7 +54,7 @@ def where(condition: Union[NamedNumeric, bool], x: NamedNumeric, y: NamedNumeric return NamedArray(jnp.where(condition.array, x.array, y.array), condition.axes) -def clip(array: NamedNumeric, a_min: NamedNumeric, a_max: NamedNumeric) -> NamedArray: +def clip(array: NamedOrNumeric, a_min: NamedOrNumeric, a_max: NamedOrNumeric) -> NamedArray: """Like jnp.clip, but with named axes. This version currently only accepts the three argument form.""" (array, a_min, a_max), axes = broadcast_arrays_and_return_axes(array, a_min, a_max) array = raw_array_or_scalar(array) commit 6b9f0cf789e504c077d21141517eb2da93ffdfe4 Date: 2022-11-14T10:19:54-08:00 Remove furl, merge checkpoint_test and test_checkpoint (#55) * fix issues with new fsspec * change save frequency to 10000 steps * yield last batch even if it's small * switch back to furl for checkpoints to minimize issues * make discovery stay closer to furl land * grr. * move tests to test_checkpoint * fix furl changes in tests * remove furl b/c it makes things more fragile, not less * missed a spot * only rm on worker 0 * need to unstrip protocol to make things work with tensorstore * don't append scheme for local paths diff --git a/requirements.txt b/requirements.txt index daf632f..e52df16 100644 --- a/requirements.txt +++ b/requirements.txt @@ -10,6 +10,5 @@ gcsfs==2022.10.0 braceexpand jmp @ git+https://github.com/deepmind/jmp#7b3ae548154625a56a6dbdb03bc07d4f599c37b2 fsspec==2022.10.0 # pin this to make gcsfs happy -furl tensorstore pytimeparse commit 4b6b974b3cba1cd9f55fcf2d962c98dea697ed9a Date: 2022-11-11T19:33:31+00:00 change named_pjit to make axis_resources become the axis_mapping for the pjitted call. diff --git a/src/haliax/partitioning.py b/src/haliax/partitioning.py index eb78984..6413ba0 100644 --- a/src/haliax/partitioning.py +++ b/src/haliax/partitioning.py @@ -157,8 +157,8 @@ def named_pjit( resource partitions. If no resource mapping is provided, this function attempts to use the global resource mapping. - If either of in_axis_resources or out_axis_resources is provided, then both must be provided. - If axis_resources is provided, then in_axis_resources and out_axis_resources must not be provided. + axis_resources will be used for a context-specific resource mapping as well as in_axis_resources and out_axis_resources + if they are not provided. :param fn: The function to be pjit'd :param axis_resources: A mapping from logical axis names to physical axis names @@ -171,11 +171,6 @@ def named_pjit( """ # TODO: support jax.Array - if in_axis_resources is not None or out_axis_resources is not None: - if axis_resources is not None: - raise ValueError("Cannot provide both axis_resources and in_axis_resources/out_axis_resources") - if in_axis_resources is None or out_axis_resources is None: - raise ValueError("Must provide both in_axis_resources and out_axis_resources") if fn is None: return functools.partial( @@ -188,17 +183,15 @@ def named_pjit( **pjit_args, ) - if axis_resources is None and in_axis_resources is None: - axis_resources = _mapping_holder.thread_data.resource_mapping + axis_resources = axis_resources or _mapping_holder.thread_data.resource_mapping + in_axis_resources = in_axis_resources or axis_resources + out_axis_resources = out_axis_resources or axis_resources - if axis_resources is not None: - in_axis_resources = axis_resources - out_axis_resources = axis_resources - if in_axis_resources is None or out_axis_resources is None: + if axis_resources is None and (in_axis_resources is None or out_axis_resources is None): raise ValueError( - "Must provide in_axis_resources and out_axis_resources, or axis_resources, or have a global " - "mapping vis axis_mapping" + "Must provide axis_resources, or in_axis_resources and out_axis_resources," + " or have a global mapping via axis_mapping" ) dynamic_fun, static_fun = hashable_partition(fn, is_jax_array_like) @@ -225,9 +218,9 @@ def named_pjit( my_pjit_args = dict(**pjit_args) my_pjit_args["in_axis_resources"] = in_resources my_pjit_args["out_axis_resources"] = out_resources - cached_pjitted_fun = _named_pjit_cache(get_fun_names(fn), **my_pjit_args) - - return cached_pjitted_fun(dynamic_donated, dynamic_reserved, static) + with axis_mapping(axis_resources or {}): + cached_pjitted_fun = _named_pjit_cache(get_fun_names(fn), **my_pjit_args) + return cached_pjitted_fun(dynamic_donated, dynamic_reserved, static) return f commit 558459e2e5a441e051c635e87a74985f3f6df595 Date: 2022-11-22T00:21:50-08:00 Explicitly define random number generators, make rng sharding opt-in (#58) * split out the sharding stuff to its own wrapper, write the wrapper functions explicitly * add tests to test_random for new random * more random, some cleanup * add categorical to random * use explicit generate_sharded in gpt2/linear * fix bugs in sharded_generate, add more logging * cleanup diff --git a/src/haliax/core.py b/src/haliax/core.py index fa14b47..424da4c 100644 --- a/src/haliax/core.py +++ b/src/haliax/core.py @@ -106,6 +106,9 @@ class NamedArray: assert len(tree) == 1 return cls(tree[0], axes=aux) + def has_axis(self, axis: AxisSpec) -> bool: + return self._lookup_indices(axis) is not None + @typing.overload def _lookup_indices(self, axis: Axis) -> Optional[int]: ... @@ -544,7 +547,7 @@ def split(a: NamedArray, axis: Axis, new_axes: Sequence[Axis]) -> Sequence[Named # e.g. we'd like something like rearrange(array, (..., new_axis), merge_axes={new_axis: (old_axis1, old_axis2)}) # or rearrange(array, (new_axis1, ..., new_axis2), split_axes={old_axis: (new_axis1, new_axis2)}) # or even rearrange(array, (x, ..., b, a), map_axes={old_axis: (a, b), x: (old1, old2)}) -def rearrange(array: NamedArray, axes: Sequence[Union[Axis, EllipsisType]]): +def rearrange(array: NamedArray, axes: Sequence[Union[Axis, EllipsisType]]) -> NamedArray: """ Rearrange an array so that its underlying storage conforms to axes. axes may include up to 1 ellipsis, indicating that the remaining axes should be @@ -764,18 +767,22 @@ def _broadcast_axes( def broadcast_to( - a: NamedArray, axes: AxisSpec, ensure_order: bool = True, enforce_no_extra_axes: bool = True + a: NamedOrNumeric, axes: AxisSpec, ensure_order: bool = True, enforce_no_extra_axes: bool = True ) -> NamedArray: """ Broadcasts a so that it has the given axes. If ensure_order is True (default), then the returned array will have the same axes in the same order as the given - axes. Otherwise, the axes may not be moved + axes. Otherwise, the axes may not be moved if they are already in the array. The axes may not be contiguous however If enforce_no_extra_axes is True and the array has axes that are not in axes, then a ValueError is raised. """ - axes = ensure_tuple(axes) + if not isinstance(a, NamedArray): + a = named(jnp.asarray(a), ()) + + assert isinstance(a, NamedArray) # mypy gets confused + if a.axes == axes: return a @@ -792,10 +799,24 @@ def broadcast_to( a_array = jnp.broadcast_to(a.array, [ax.size for ax in all_axes]) a = NamedArray(a_array, all_axes) - if ensure_order: - a = rearrange(a, axes + extra_axes) + # if the new axes are already in the right order, then we're done + if ensure_order and not _is_subsequence(axes, all_axes): + a = a.rearrange(axes + extra_axes) + + return typing.cast(NamedArray, a) - return a + +def _is_subsequence(needle, haystack): + needle_i = 0 + haystack_j = 0 + while needle_i < len(needle) and haystack_j < len(haystack): + if needle[needle_i] == haystack[haystack_j]: + needle_i += 1 + haystack_j += 1 + + if needle_i < len(needle): + return False + return True @overload @@ -863,12 +884,12 @@ def broadcast_arrays_and_return_axes( def broadcast_axis(a: NamedArray, axis: AxisSpec) -> NamedArray: """ Broadcasts a, ensuring that it has all the axes in axis. - broadcast_axis is an alias for broadcast_to(a, axis, enforce_no_extra_axes=False, ensure_order=False) + broadcast_axis is an alias for broadcast_to(a, axis, enforce_no_extra_axes=False, ensure_order=True) """ if isinstance(axis, Axis) and axis in a.axes: return a - return broadcast_to(a, axis, enforce_no_extra_axes=False, ensure_order=False) + return broadcast_to(a, axis, enforce_no_extra_axes=False, ensure_order=True) __all__ = [ @@ -890,9 +911,3 @@ __all__ = [ "shape_checks", "are_shape_checks_enabled", ] - - -def raw_array_or_scalar(x: NamedOrNumeric): - if isinstance(x, NamedArray): - return x.array - return x diff --git a/src/haliax/nn/dropout.py b/src/haliax/nn/dropout.py index 91d9994..1dc4960 100644 --- a/src/haliax/nn/dropout.py +++ b/src/haliax/nn/dropout.py @@ -67,7 +67,7 @@ class Dropout(eqx.Module): shape_to_generate = tuple(ax for ax in x.axes if ax not in axes) q = 1 - self.pdrop - mask = haliax.random.bernoulli(key, q, shape_to_generate) + mask = haliax.random.bernoulli(key, shape_to_generate, q) q = x.dtype.type(q) out = haliax.where(mask, x / q, 0) diff --git a/src/haliax/nn/linear.py b/src/haliax/nn/linear.py index d63d1ba..c7d9759 100644 --- a/src/haliax/nn/linear.py +++ b/src/haliax/nn/linear.py @@ -21,7 +21,7 @@ class Linear(eqx.Module): def __init__(self, In: AxisSpec, Out: AxisSpec, *, key, include_bias=True): joint_spec = hax.concat_axis_specs(In, Out) - self.weight = hax.random.normal(key, joint_spec) * 0.02 + self.weight = hax.random.generate_sharded(hax.random.normal)(key, joint_spec) * 0.02 self.bias = hax.zeros(Out) if include_bias else None self.In = In diff --git a/src/haliax/ops.py b/src/haliax/ops.py index fbfadab..93e3533 100644 --- a/src/haliax/ops.py +++ b/src/haliax/ops.py @@ -3,7 +3,7 @@ from typing import Union import jax import jax.numpy as jnp -from .core import NamedArray, NamedOrNumeric, broadcast_arrays, broadcast_arrays_and_return_axes, raw_array_or_scalar +from .core import NamedArray, NamedOrNumeric, broadcast_arrays, broadcast_arrays_and_return_axes from .types import Axis @@ -87,4 +87,10 @@ def isclose(a: NamedArray, b: NamedArray, rtol=1e-05, atol=1e-08, equal_nan=Fals return NamedArray(jnp.isclose(a.array, b.array, rtol=rtol, atol=atol, equal_nan=equal_nan), a.axes) +def raw_array_or_scalar(x: NamedOrNumeric): + if isinstance(x, NamedArray): + return x.array + return x + + __all__ = ["trace", "where", "tril", "triu", "isclose"] diff --git a/src/haliax/random.py b/src/haliax/random.py index 27d9438..5d7eeb6 100644 --- a/src/haliax/random.py +++ b/src/haliax/random.py @@ -1,107 +1,353 @@ """Wrappers around jax.random functions.""" - import functools import inspect -from typing import Sequence +from typing import Optional import jax +import jax.numpy as jnp import jax.random as jrandom -# TODO: handle broadcasting of array args to random functions (e.g. minval and maxval for uniform) -from haliax.core import NamedArray +import haliax +from haliax.core import NamedArray, NamedOrNumeric, broadcast_to from haliax.util import ensure_tuple from .jax_utils import named_call -from .partitioning import auto_sharded, physical_axis_size, pspec_for_axis -from .types import Axis +from .partitioning import auto_sharded, physical_axis_name, physical_axis_size, pspec_for_axis +from .types import Axis, AxisSpec -def _wrap_random_function(func): - """Wrap a jax random function to return a NamedArray and takes axes as inputs""" +@named_call +def uniform( + key, shape: AxisSpec, dtype=jnp.float_, minval: NamedOrNumeric = 0.0, maxval: NamedOrNumeric = 1.0 +) -> NamedArray: + shape = ensure_tuple(shape) + minval = broadcast_to(minval, shape).array + maxval = broadcast_to(maxval, shape).array + jax_shape = _to_jax_shape(shape) + jax_array = jrandom.uniform(key=key, shape=jax_shape, dtype=dtype, minval=minval, maxval=maxval) + return auto_sharded(NamedArray(jax_array, shape)) - @named_call(name=func.__name__) - @functools.wraps(func) - def wrapper(key: jrandom.KeyArray, *args, **kwargs): - sig: inspect.BoundArguments = inspect.signature(func).bind(key, *args, **kwargs) - sig.apply_defaults() - # get shape - orig_shape = sig.arguments["shape"] - orig_shape = ensure_tuple(orig_shape) - if isinstance(orig_shape, Sequence): - is_haliax = len(orig_shape) == 0 or any(isinstance(s, Axis) for s in orig_shape) - shape = tuple(axis.size if isinstance(axis, Axis) else axis for axis in orig_shape) - else: - is_haliax = False - - if is_haliax: - - # this is a bit tricky but, for sharded models, we sometimes want to split the random key so that we only - # need to generate the random numbers for the local shard. We do this because the RNG can't actually - # auto-shard, meaning that if you want to generate a [1024] vector across 4 devices, each one actually - # generates all 1024 numbers, and then only uses 256 of them. This is a waste of time, especially when it's - # not a [1024] vector but a [1600, 6400] matrix (for say, gpt-2). So we split the key here, and then let - # vmap hopefully only generate the random numbers for the local shard. - # - # However, we don't want to oversplit or it kind of ruins the whole point since we have to split the key on - # every node... So instead we just split along the *largest* physical axis - # TODO: we won't need to do this when they add better splitting for random numbers - # (froystig is maybe going to do this?) - - # what we do is we take the biggest axis that is sharded and split on it, ties going to the first axis - pspec = pspec_for_axis(orig_shape) +@named_call +def normal(key, shape: AxisSpec, dtype=jnp.float_): + shape = ensure_tuple(shape) + jax_shape = _to_jax_shape(shape) + jax_array = jrandom.normal(key=key, shape=jax_shape, dtype=dtype) + return auto_sharded(NamedArray(jax_array, shape)) + + +@named_call +def bernoulli(key, shape: AxisSpec, p: NamedOrNumeric): + shape = ensure_tuple(shape) + p = broadcast_to(p, shape).array + jax_shape = _to_jax_shape(shape) + jax_array = jrandom.bernoulli(key=key, p=p, shape=jax_shape) + return auto_sharded(NamedArray(jax_array, shape)) + + +@named_call +def randint(key, shape: AxisSpec, minval: NamedOrNumeric, maxval: NamedOrNumeric, dtype=jnp.int_): + shape = ensure_tuple(shape) + minval = broadcast_to(minval, shape).array + maxval = broadcast_to(maxval, shape).array + jax_shape = _to_jax_shape(shape) + jax_array = jrandom.randint(key=key, shape=jax_shape, minval=minval, maxval=maxval, dtype=dtype) + return auto_sharded(NamedArray(jax_array, shape)) + + +@named_call +def poisson(key, shape: AxisSpec, lam: NamedOrNumeric, dtype=jnp.int_): + shape = ensure_tuple(shape) + lam = broadcast_to(lam, shape).array + jax_shape = _to_jax_shape(shape) + jax_array = jrandom.poisson(key=key, lam=lam, shape=jax_shape, dtype=dtype) + return auto_sharded(NamedArray(jax_array, shape)) + + +@named_call +def exponential(key, shape: AxisSpec, dtype=jnp.float_): + shape = ensure_tuple(shape) + jax_shape = _to_jax_shape(shape) + jax_array = jrandom.exponential(key=key, shape=jax_shape, dtype=dtype) + return auto_sharded(NamedArray(jax_array, shape)) + + +@named_call +def gamma(key, shape: AxisSpec, a: NamedOrNumeric, dtype=jnp.float_): + shape = ensure_tuple(shape) + a = broadcast_to(a, shape).array + jax_shape = _to_jax_shape(shape) + jax_array = jrandom.gamma(key=key, a=a, shape=jax_shape, dtype=dtype) + return auto_sharded(NamedArray(jax_array, shape)) + + +@named_call +def beta(key, shape: AxisSpec, a: NamedOrNumeric, b: NamedOrNumeric, dtype=jnp.float_): + shape = ensure_tuple(shape) + a = broadcast_to(a, shape).array + b = broadcast_to(b, shape).array + jax_shape = _to_jax_shape(shape) + jax_array = jrandom.beta(key=key, a=a, b=b, shape=jax_shape, dtype=dtype) + return auto_sharded(NamedArray(jax_array, shape)) + + +@named_call +def laplace(key, shape: AxisSpec, dtype=jnp.float_): + shape = ensure_tuple(shape) + jax_shape = _to_jax_shape(shape) + jax_array = jrandom.laplace(key=key, shape=jax_shape, dtype=dtype) + return auto_sharded(NamedArray(jax_array, shape)) + + +@named_call +def cauchy(key, shape: AxisSpec, dtype=jnp.float_): + shape = ensure_tuple(shape) + jax_shape = _to_jax_shape(shape) + jax_array = jrandom.cauchy(key=key, shape=jax_shape, dtype=dtype) + return auto_sharded(NamedArray(jax_array, shape)) + + +@named_call +def logistic(key, shape: AxisSpec, dtype=jnp.float_): + shape = ensure_tuple(shape) + jax_shape = _to_jax_shape(shape) + jax_array = jrandom.logistic(key=key, shape=jax_shape, dtype=dtype) + return auto_sharded(NamedArray(jax_array, shape)) + + +@named_call +def truncated_normal(key, shape: AxisSpec, lower: NamedOrNumeric, upper: NamedOrNumeric, dtype=jnp.float_): + shape = ensure_tuple(shape) + lower = broadcast_to(lower, shape).array + upper = broadcast_to(upper, shape).array + jax_shape = _to_jax_shape(shape) + jax_array = jrandom.truncated_normal(key=key, lower=lower, upper=upper, shape=jax_shape, dtype=dtype) + return auto_sharded(NamedArray(jax_array, shape)) + + +_enforce_sharded_generate = False +""" mostly for testing: enforces shard generation for all random functions even if not running distributed""" + + +def generate_sharded(fn, axis: Optional[Axis] = None): + """ + Create a wrapped version of fn (which should be a random generator) that generates the random array in a sharded + manner, using vmap over the provided axis, or inferring the "best" one if not provided. + + This is a bit tricky but, for sharded models, we sometimes want to split the random key so that we only + need to generate the random numbers for the local shard. We do this because the RNG can't actually + auto-shard, meaning that if you want to generate a [1024] vector across 4 devices, each one actually + generates all 1024 numbers, and then only uses 256 of them. This is a waste of time, especially when it's + not a [1024] vector but a [1600, 6400] matrix (for say, gpt-2). So we split the key here, and then let + vmap hopefully only generate the random numbers for the local shard. + + + + However, we don't want to oversplit or it kind of ruins the whole point since we have to split the key on + every node... So instead we just split along the *largest* physical axis, or the provided axis if it's + provided. + """ + # TODO: we won't need to do this when they add better splitting for random numbers + # (froystig is maybe going to do this?) + + @functools.wraps(fn) + def wrapped_fn(*args, **kwargs): + _axis = axis + bound = inspect.signature(fn).bind(*args, **kwargs) + bound.apply_defaults() + key = bound.arguments["key"] + shape = bound.arguments["shape"] + + shape = ensure_tuple(shape) + + if len(shape) == 0: + # scalar + return fn(*args, **kwargs) + + if _axis is None: + pspec = pspec_for_axis(shape) if pspec: - biggest_axis, biggest_physical = max( - zip(orig_shape, pspec), key=lambda x: (physical_axis_size(x[0]) or 0) if x[1] else 0 + _axis, biggest_physical = max( + zip(shape, pspec), key=lambda x: (physical_axis_size(x[0]) or 0) if x[1] else 0 ) else: - biggest_axis = biggest_physical = None + _axis = biggest_physical = None - if biggest_physical and biggest_axis.size > 1: - index_of_biggest_axis = orig_shape.index(biggest_axis) - shape = shape[:index_of_biggest_axis] + shape[index_of_biggest_axis + 1 :] - sig.arguments["shape"] = shape - keys = jrandom.split(key, biggest_axis.size) + _axis = _axis or shape[0] + else: + biggest_physical = physical_axis_name(axis) - def fn(key): - return func(key, *sig.args[1:], **sig.kwargs) + if _enforce_sharded_generate or biggest_physical: + with jax.named_scope(f"generate_sharded({_axis})"): + index_of_axis_to_shard = shape.index(_axis) + # remove axis from shape + shape_without_axis = shape[:index_of_axis_to_shard] + shape[index_of_axis_to_shard + 1 :] - out = jax.vmap(fn, in_axes=(0,), out_axes=index_of_biggest_axis)(keys) - return auto_sharded(NamedArray(out, orig_shape)) - else: - sig.arguments["shape"] = shape - out = func(**sig.arguments) - return auto_sharded(NamedArray(out, orig_shape)) + keys = jrandom.split(key, _axis.size) + + bound.arguments["shape"] = shape_without_axis + bound.arguments["key"] = keys + + return haliax.vmap(fn, axis=_axis)(*bound.args, **bound.kwargs) else: - return func(**sig.arguments) + with jax.named_scope(f"generate_sharded({_axis}, no_shard)"): + return fn(*args, **kwargs) + + return wrapped_fn - return wrapper +@named_call +def ball(key, shape: AxisSpec, D: Axis, p: float = 2.0, dtype=jnp.float_): + shape = ensure_tuple(shape) + jax_shape = _to_jax_shape(shape) + jax_array = jrandom.ball(key=key, shape=jax_shape, d=D.size, p=p, dtype=dtype) + return auto_sharded(NamedArray(jax_array, shape + (D,))) + + +@named_call +def choice(key, shape: AxisSpec, a: NamedArray, axis: Axis, replace: bool = True, p: Optional[NamedArray] = None): + """ + Selects random elements from an array along the given axis. If p is provided, the elements are selected + with probability proportional to their weights and it must be a 1-d array with its only axis being the axis. + shape and a.axes must not overlap except that axis may be repeated in both. + + :return: Array with shape `shape` + (`a.axes` - `axis`) + """ + + index = a._lookup_indices(axis) + assert index is not None, f"axis {axis} not in a" + + shape = ensure_tuple(shape) + if p is not None: + assert p.axes == (axis,), f"p must have axis {axis} or be None" + + jax_shape = _to_jax_shape(shape) + jax_p = p.array if p is not None else None + + jax_array = jrandom.choice(key, a.array, jax_shape, replace=replace, p=jax_p, axis=index) + + expected_shape = shape + tuple(a.axes[:index] + a.axes[index + 1 :]) + + return auto_sharded(NamedArray(jax_array, expected_shape)) + + +@named_call +def categorical(key, shape: AxisSpec, logits: NamedArray, axis: Axis): + """Sample random values from categorical distributions. + + Args: + key: a PRNG key used as the random key. + shape: A tuple of nonnegative integers representing the result shape. + Must be broadcast-compatible with logits without the axis + logits: Unnormalized log probabilities of the categorical distribution(s) to sample from, + so that `softmax(logits, axis)` gives the corresponding probabilities. + axis: Axis along which logits belong to the same categorical distribution. + Returns: + A random array with int dtype and shape given by ``shape`` + """ + shape = ensure_tuple(shape) + + # TODO: could alias the axis and rename at end + if axis in shape: + raise ValueError(f"axis {axis} cannot be in shape {shape}") + + logits = logits.broadcast_axis(shape) + + index = logits._lookup_indices(axis) + assert index is not None, f"axis {axis} not in logits" + + jax_shape = _to_jax_shape(shape) + + jax_array = jrandom.categorical(key, logits.array, axis=index, shape=jax_shape) + return auto_sharded(NamedArray(jax_array, shape)) + + +@named_call +def gumbel(key, shape: AxisSpec, dtype=jnp.float_): + shape = ensure_tuple(shape) + jax_shape = _to_jax_shape(shape) + jax_array = jrandom.gumbel(key, jax_shape, dtype=dtype) + return auto_sharded(NamedArray(jax_array, shape)) + + +@named_call +def permutation(key, x: NamedArray, axis: Axis, independent: bool = False): + axis_index = x._lookup_indices(axis) + jax_array = jrandom.permutation(key, x.array, axis_index, independent=independent) + return auto_sharded(NamedArray(jax_array, x.axes)) + + +@named_call +def rademacher(key, shape: AxisSpec, dtype=jnp.float_): + shape = ensure_tuple(shape) + jax_shape = _to_jax_shape(shape) + jax_array = jrandom.rademacher(key, jax_shape, dtype=dtype) + return auto_sharded(NamedArray(jax_array, shape)) + + +@named_call +def t(key, shape: AxisSpec, df: NamedOrNumeric, dtype=jnp.float_): + shape = ensure_tuple(shape) + df = broadcast_to(df, shape) + jax_shape = _to_jax_shape(shape) + jax_array = jrandom.t(key, df.array, jax_shape, dtype=dtype) + return auto_sharded(NamedArray(jax_array, shape)) + + +@named_call +def weibull_min(key, shape: AxisSpec, scale: NamedOrNumeric, concentration: NamedOrNumeric, dtype=jnp.float_): + shape = ensure_tuple(shape) + scale = broadcast_to(scale, shape) + concentration = broadcast_to(concentration, shape) + jax_shape = _to_jax_shape(shape) + jax_array = jrandom.weibull_min(key, scale.array, concentration.array, jax_shape, dtype=dtype) + return auto_sharded(NamedArray(jax_array, shape)) + + +@named_call +def pareto(key, shape: AxisSpec, b: NamedOrNumeric, dtype=jnp.float_): + shape = ensure_tuple(shape) + b = broadcast_to(b, shape) + jax_shape = _to_jax_shape(shape) + jax_array = jrandom.pareto(key, b.array, jax_shape, dtype=dtype) + return auto_sharded(NamedArray(jax_array, shape)) + + +@named_call +def loggamma(key, shape: AxisSpec, a: NamedOrNumeric, dtype=jnp.float_): + shape = ensure_tuple(shape) + a = broadcast_to(a, shape) + jax_shape = _to_jax_shape(shape) + jax_array = jrandom.loggamma(key, a.array, jax_shape, dtype=dtype) + return auto_sharded(NamedArray(jax_array, shape)) + + +def _to_jax_shape(shape): + return tuple(axis.size if isinstance(axis, Axis) else axis for axis in shape) -uniform = _wrap_random_function(jrandom.uniform) -normal = _wrap_random_function(jrandom.normal) -randint = _wrap_random_function(jrandom.randint) -bernoulli = _wrap_random_function(jrandom.bernoulli) -poisson = _wrap_random_function(jrandom.poisson) -exponential = _wrap_random_function(jrandom.exponential) -gamma = _wrap_random_function(jrandom.gamma) -beta = _wrap_random_function(jrandom.beta) -laplace = _wrap_random_function(jrandom.laplace) -cauchy = _wrap_random_function(jrandom.cauchy) -logistic = _wrap_random_function(jrandom.logistic) -truncated_normal = _wrap_random_function(jrandom.truncated_normal) __all__ = [ + "generate_sharded", "uniform", "normal", - "randint", + "ball", "bernoulli", - "poisson", + "beta", + "cauchy", + "choice", "exponential", "gamma", - "beta", + "gumbel", "laplace", - "cauchy", "logistic", + "permutation", + "poisson", + "rademacher", "truncated_normal", + # "categorical", + # "dirichlet", + "loggamma", + "pareto", + "t", + "weibull_min", ] diff --git a/tests/test_random.py b/tests/test_random.py index c43ea67..9a2f49d 100644 --- a/tests/test_random.py +++ b/tests/test_random.py @@ -1,8 +1,323 @@ +from typing import Callable + import jax +import jax.numpy as jnp +from chex import PRNGKey import haliax as hax +from haliax.random import generate_sharded + + +Height = hax.Axis("Height", 4) +Width = hax.Axis("Width", 8) +Digit = hax.Axis("Digit", 10) def test_empty_shape(): key = jax.random.PRNGKey(0) hax.random.uniform(key, shape=()) + + +def test_uniform_with_bounds_scalar(): + check_gen_is_equal(jax.random.uniform, hax.random.uniform) + + key = jax.random.PRNGKey(0) + u = hax.random.uniform(key, shape=(Height, Width), minval=-3.0, maxval=0.5) + + assert u.axes == (Height, Width) + + assert hax.all(u >= -3.0) + assert hax.all(u <= 0.5) + + +def test_uniform_with_bounds_broadcast(): + key = jax.random.PRNGKey(0) + lb = hax.arange(Height, start=-5.0) + ub = hax.full(Width, 0.5) + u = hax.random.uniform(key, shape=(Height, Width), minval=lb, maxval=ub) + + assert u.axes == (Height, Width) + + assert hax.all(u >= lb) + assert hax.all(u <= 0.5) + + check_gen_is_equal( + lambda k, s: jax.random.uniform(k, shape=s, minval=lb.array.reshape(-1, 1), maxval=ub.array.reshape(1, -1)), + lambda k, s: hax.random.uniform(k, s, minval=lb, maxval=ub), + ) + + +def test_uniform_with_bounds_broadcast_and_scalar(): + key = jax.random.PRNGKey(0) + lb = hax.full(Height, -3.0) + ub = 0.5 + u = hax.random.uniform(key, shape=(Height, Width), minval=lb, maxval=ub) + + assert u.axes == (Height, Width) + + assert hax.all(u >= -3.0) + assert hax.all(u <= 0.5) + + +def test_sharded_uniform_with_bounds_broadcast_and_scalar(): + hax.random._enforce_sharded_generate = True + try: + key = jax.random.PRNGKey(0) + lb = hax.full(Height, -3.0) + ub = 0.5 + u = generate_sharded(hax.random.uniform, axis=Height)(key, shape=(Height, Width), minval=lb, maxval=ub) + + assert u.axes == (Height, Width) + + assert hax.all(u >= -3.0) + assert hax.all(u <= 0.5) + finally: + hax.random._enforce_sharded_generate = False + + # now just assert that this does in fact change the randomness + u2 = hax.random.uniform(key, shape=(Height, Width), minval=lb, maxval=ub) + assert not hax.all(u == u2) + + +def test_randint(): + check_gen_is_equal(lambda k, s: jax.random.randint(k, s, 0, 10), lambda k, s: hax.random.randint(k, s, 0, 10)) + # check broadcasting + minval = hax.arange(Width, step=1) + check_gen_is_equal( + lambda k, s: jax.random.randint(k, s, minval.array.reshape(1, -1), 10), + lambda k, s: hax.random.randint(k, s, minval, 10), + ) + + minval = hax.arange(Height, step=1) + check_gen_is_equal( + lambda k, s: jax.random.randint(k, s, minval.array.reshape(-1, 1), 10), + lambda k, s: hax.random.randint(k, s, minval, 10), + ) + + +def check_gen_is_equal( + jax_fn: Callable[[PRNGKey, tuple], jnp.ndarray], hax_fn: Callable[[PRNGKey, hax.AxisSpec], hax.NamedArray] +): + key = jax.random.PRNGKey(0) + + hax_out = hax_fn(key, (Height, Width)) + jax_out = jax_fn(key, (Height.size, Width.size)) + + assert hax_out.array.shape == jax_out.shape + assert hax.all(hax_out.array == jax_out) + + +def test_normal(): + check_gen_is_equal(jax.random.normal, hax.random.normal) + + +def test_bernoulli(): + check_gen_is_equal(lambda k, s: jax.random.bernoulli(k, 0.5, s), lambda k, s: hax.random.bernoulli(k, s, 0.5)) + # check broadcasting + prob = hax.arange(Width, step=0.1) + check_gen_is_equal( + lambda k, s: jax.random.bernoulli(k, prob.array.reshape(1, -1), s), + lambda k, s: hax.random.bernoulli(k, s, prob), + ) + prob = hax.arange(Height, step=0.1) + check_gen_is_equal( + lambda k, s: jax.random.bernoulli(k, prob.array.reshape(-1, 1), s), + lambda k, s: hax.random.bernoulli(k, s, prob), + ) + + +def test_poisson(): + check_gen_is_equal(lambda k, s: jax.random.poisson(k, 0.5, s), lambda k, s: hax.random.poisson(k, s, 0.5)) + # check broadcasting + lam = hax.arange(Width, step=0.1) + check_gen_is_equal( + lambda k, s: jax.random.poisson(k, lam.array.reshape(1, -1), s), + lambda k, s: hax.random.poisson(k, s, lam), + ) + lam = hax.arange(Height, step=0.1) + check_gen_is_equal( + lambda k, s: jax.random.poisson(k, lam.array.reshape(-1, 1), s), + lambda k, s: hax.random.poisson(k, s, lam), + ) + + +def test_laplace(): + check_gen_is_equal(lambda k, s: jax.random.laplace(k, s), lambda k, s: hax.random.laplace(k, s)) + + +def test_exponential(): + check_gen_is_equal(lambda k, s: jax.random.exponential(k, s), lambda k, s: hax.random.exponential(k, s)) + + +def test_gamma(): + check_gen_is_equal(lambda k, s: jax.random.gamma(k, 0.5, s), lambda k, s: hax.random.gamma(k, s, 0.5)) + # check broadcasting + alpha = hax.arange(Width, step=0.1) + check_gen_is_equal( + lambda k, s: jax.random.gamma(k, alpha.array.reshape(1, -1), s), + lambda k, s: hax.random.gamma(k, s, alpha), + ) + alpha = hax.arange(Height, step=0.1) + check_gen_is_equal( + lambda k, s: jax.random.gamma(k, alpha.array.reshape(-1, 1), s), + lambda k, s: hax.random.gamma(k, s, alpha), + ) + + +def test_gumbel(): + check_gen_is_equal(lambda k, s: jax.random.gumbel(k, s), lambda k, s: hax.random.gumbel(k, s)) + + +def test_beta(): + check_gen_is_equal(lambda k, s: jax.random.beta(k, 0.6, 0.5, s), lambda k, s: hax.random.beta(k, s, 0.6, 0.5)) + # check broadcasting + alpha = hax.arange(Width, step=0.1, start=0.01) + beta = hax.arange(Width, step=0.1, start=0.01) + check_gen_is_equal( + lambda k, s: jax.random.beta(k, alpha.array.reshape(1, -1), beta.array.reshape(1, -1), s), + lambda k, s: hax.random.beta(k, s, alpha, beta), + ) + alpha = hax.arange(Height, step=0.1, start=0.01) + beta = hax.arange(Height, step=0.1, start=0.01) + check_gen_is_equal( + lambda k, s: jax.random.beta(k, alpha.array.reshape(-1, 1), beta.array.reshape(-1, 1), s), + lambda k, s: hax.random.beta(k, s, alpha, beta), + ) + + +def test_rademacher(): + check_gen_is_equal(lambda k, s: jax.random.rademacher(k, s), lambda k, s: hax.random.rademacher(k, s)) + + +def test_ball(): + check_gen_is_equal(lambda k, s: jax.random.ball(k, Digit.size, shape=s), lambda k, s: hax.random.ball(k, s, Digit)) + + +def test_cauchy(): + check_gen_is_equal(lambda k, s: jax.random.cauchy(k, s), lambda k, s: hax.random.cauchy(k, s)) + + +def test_logistic(): + check_gen_is_equal(lambda k, s: jax.random.logistic(k, s), lambda k, s: hax.random.logistic(k, s)) + + +def test_truncated_normal(): + lower = hax.arange(Width, step=0.1, start=0.01) + upper = hax.arange(Width, step=0.1, start=0.01) + check_gen_is_equal( + lambda k, s: jax.random.truncated_normal(k, lower.array.reshape(1, -1), upper.array.reshape(1, -1), s), + lambda k, s: hax.random.truncated_normal(k, s, lower, upper), + ) + + lower = hax.arange(Height, step=0.1, start=0.01) + upper = hax.arange(Height, step=0.1, start=0.01) + check_gen_is_equal( + lambda k, s: jax.random.truncated_normal(k, lower.array.reshape(-1, 1), upper.array.reshape(-1, 1), s), + lambda k, s: hax.random.truncated_normal(k, s, lower, upper), + ) + + lower = hax.arange(Width, step=0.1, start=0.01) + upper = hax.arange(Height, step=0.1, start=0.01) + + check_gen_is_equal( + lambda k, s: jax.random.truncated_normal(k, lower.array.reshape(1, -1), upper.array.reshape(-1, 1), s), + lambda k, s: hax.random.truncated_normal(k, s, lower, upper), + ) + + +def test_choice(): + digits = hax.arange(Digit) + check_gen_is_equal( + lambda k, s: jax.random.choice(k, digits.array, shape=s), lambda k, s: hax.random.choice(k, s, digits, Digit) + ) + + weights = hax.arange(Digit, step=0.1, start=0.01) + check_gen_is_equal( + lambda k, s: jax.random.choice(k, digits.array, shape=s, p=weights.array), + lambda k, s: hax.random.choice(k, s, digits, Digit, p=weights), + ) + + +def test_categorical(): + logits = hax.random.uniform( + jax.random.PRNGKey(0), + ( + Height, + Width, + Digit, + ), + ) + check_gen_is_equal( + lambda k, s: jax.random.categorical(k, logits.array, shape=s, axis=-1), + lambda k, s: hax.random.categorical(k, s, logits, Digit), + ) + + logits = logits.rearrange((Digit, Height, Width)) + check_gen_is_equal( + lambda k, s: jax.random.categorical(k, logits.array, shape=s, axis=0), + lambda k, s: hax.random.categorical(k, s, logits, Digit), + ) + + # check broadcasting + logits = hax.random.uniform( + jax.random.PRNGKey(0), + ( + Height, + Digit, + ), + ) + # https://github.com/google/jax/issues/13124 broadcasting is wrong with jax categorical + raw_logits = jnp.broadcast_to(logits.array.reshape(-1, 1, Digit.size), (Height.size, Width.size, Digit.size)) + check_gen_is_equal( + lambda k, s: jax.random.categorical(k, raw_logits, shape=s, axis=-1), + lambda k, s: hax.random.categorical(k, s, logits, Digit), + ) + + +def test_permutation(): + data = hax.random.uniform(jax.random.PRNGKey(0), (Width, Height)) + + hax_perm = hax.random.permutation(jax.random.PRNGKey(0), data, Height) + jax_perm = jax.random.permutation(jax.random.PRNGKey(0), data.array, 1) + + assert jnp.all(hax_perm.array == jax_perm) + + hax_perm = hax.random.permutation(jax.random.PRNGKey(0), data, Width) + jax_perm = jax.random.permutation(jax.random.PRNGKey(0), data.array, 0) + + assert jnp.all(hax_perm.array == jax_perm) + + +def test_t(): + param = hax.arange(Width, start=0.1) + check_gen_is_equal(lambda k, s: jax.random.t(k, param.array, shape=s), lambda k, s: hax.random.t(k, s, param)) + + check_gen_is_equal(lambda k, s: jax.random.t(k, 0.5, shape=s), lambda k, s: hax.random.t(k, s, 0.5)) + + +def test_weibull_min(): + scale = hax.arange(Width, start=0.1) + concentration = hax.arange(Height, start=0.1) + + check_gen_is_equal( + lambda k, s: jax.random.weibull_min( + k, scale.array.reshape(1, -1), concentration.array.reshape(-1, 1), shape=s + ), + lambda k, s: hax.random.weibull_min(k, s, scale, concentration), + ) + + +def test_pareto(): + b = hax.arange(Width, start=0.1) + + check_gen_is_equal( + lambda k, s: jax.random.pareto(k, b.array.reshape(1, -1), shape=s), lambda k, s: hax.random.pareto(k, s, b) + ) + + +def test_loggamma(): + a = hax.arange(Width, start=0.1) + + check_gen_is_equal( + lambda k, s: jax.random.loggamma(k, a.array.reshape(1, -1), shape=s), lambda k, s: hax.random.loggamma(k, s, a) + ) commit 3ef8d98a220404d928f359a397ad66ff1723e4e5 Date: 2022-11-23T12:17:24-08:00 messed up a merge diff --git a/src/haliax/random.py b/src/haliax/random.py index 5d7eeb6..d74dfe8 100644 --- a/src/haliax/random.py +++ b/src/haliax/random.py @@ -188,7 +188,7 @@ def generate_sharded(fn, axis: Optional[Axis] = None): bound.arguments["shape"] = shape_without_axis bound.arguments["key"] = keys - return haliax.vmap(fn, axis=_axis)(*bound.args, **bound.kwargs) + return haliax.vmap(fn, axis=_axis)(*bound.args, **bound.kwargs).reshape(shape) else: with jax.named_scope(f"generate_sharded({_axis}, no_shard)"): return fn(*args, **kwargs) commit 5b96e78edd293360e6a98166a457a84b025a991b Date: 2022-11-23T12:17:24-08:00 messed up a merge diff --git a/src/haliax/random.py b/src/haliax/random.py index d74dfe8..acf148f 100644 --- a/src/haliax/random.py +++ b/src/haliax/random.py @@ -188,7 +188,7 @@ def generate_sharded(fn, axis: Optional[Axis] = None): bound.arguments["shape"] = shape_without_axis bound.arguments["key"] = keys - return haliax.vmap(fn, axis=_axis)(*bound.args, **bound.kwargs).reshape(shape) + return haliax.vmap(fn, axis=_axis)(*bound.args, **bound.kwargs).rearrange(shape) else: with jax.named_scope(f"generate_sharded({_axis}, no_shard)"): return fn(*args, **kwargs) commit f5d26ce1204593927ff86a2291d6af755411f114 Date: 2022-12-15T08:58:43-08:00 fix tests for jax 0.4.{0, 1} (#71) * fix test for jax 0.4.0 * fix test in multi-device setting diff --git a/tests/test_partitioning.py b/tests/test_partitioning.py index f603b26..62f7ac1 100644 --- a/tests/test_partitioning.py +++ b/tests/test_partitioning.py @@ -3,7 +3,7 @@ import jax import jax.numpy as jnp import numpy as np from jax.interpreters import pxla -from jax.interpreters.pxla import PartitionSpec, Replicated, ShardedAxis +from jax.interpreters.pxla import PartitionSpec from jaxtyping import Array from utils import skip_if_not_enough_devices @@ -59,21 +59,9 @@ def test_pjit_class_init(): mod = named_pjit(MyModuleInit)() assert mod.named.array.shape == (Dim2.size, Dim3.size) - assert mod.named.array.sharding_spec.mesh_mapping == ( - ShardedAxis(0), - ShardedAxis(1), - ) assert mod.unnamed1.shape == () - assert mod.unnamed1.sharding_spec.mesh_mapping == ( - Replicated(len(devices) // 2), - Replicated(2), - ) assert mod.named2.array.shape == (Dim3.size,) - assert mod.named2.array.sharding_spec.mesh_mapping == ( - Replicated(len(devices) // 2), - ShardedAxis(0), - ) @skip_if_not_enough_devices(4) commit 36999d5a9ea22a9977ae740a6609fd5a6332f315 Date: 2023-01-10T09:59:30-08:00 JAX SMI for memory utilization, initial cut at CUDA docs (#68) * jaxsmi * fix device memory logging on gpu, cleanup * quick notes about getting started on CUDA * write to a per-device pid * wip * wip * wip * tweak docs * cleanup diff --git a/requirements.txt b/requirements.txt index e52df16..a4e7fa6 100644 --- a/requirements.txt +++ b/requirements.txt @@ -12,3 +12,4 @@ jmp @ git+https://github.com/deepmind/jmp#7b3ae548154625a56a6dbdb03bc07d4f599c37 fsspec==2022.10.0 # pin this to make gcsfs happy tensorstore pytimeparse +humanfriendly commit 7776688b24972eb90d1d47c1d2dda3262d8d3fb2 Date: 2023-01-10T10:24:16-08:00 Structured global data loader (#70) * move the lm dataset configs to data.text, add shardabledataset to exports * clean up docs for ShardedIndexedDataset and rename to GlobalBatchDataset * refactor so that GlobalBatchDataset doesn't know about BatchEncodings * add __len__ method to TokenSeqDataset * require __len__ on Dataset * use the len method on Dataset to make GlobalBatchDataset non-infinite * cleanup up todo in text.py * move the lm dataset configs to data.text, add shardabledataset to exports * clean up docs for ShardedIndexedDataset and rename to GlobalBatchDataset * refactor so that GlobalBatchDataset doesn't know about BatchEncodings * add ShapeSpec/NamedShapeSpec and item_shapes for dataloading * add stack to haliax * make pspec_for_axis take an axis mapping arg * concat BatchEncoding should return np arrays to conform to new item_spec stuff * generalized GlobalBatchDataset to support structured datasets * remove redundant assert (that gets in the way when we disable checks) * fix exception handling in context manager * tests and fixes for structured datasets with GlobalBatchDataset * fix tests * forgot to update gpt2_eval.py in all this refactoring. * tweak enforce_eos * cleanup sharded.py TODOs diff --git a/src/haliax/__init__.py b/src/haliax/__init__.py index dea4ac9..d08ea95 100644 --- a/src/haliax/__init__.py +++ b/src/haliax/__init__.py @@ -1,3 +1,5 @@ +from typing import Sequence + import jax import jax.numpy as jnp @@ -74,6 +76,14 @@ def arange(axis: Axis, *, start=0, step=1, dtype=None) -> NamedArray: return NamedArray(jnp.arange(start, stop, step, dtype=dtype), (axis,)) +def stack(axis: Axis, arrays: Sequence[NamedArray]) -> NamedArray: + """Version of jnp.stack that returns a NamedArray""" + if len(arrays) == 0: + return zeros(axis) + arrays = [a.rearrange(arrays[0].axes) for a in arrays] + return NamedArray(jnp.stack([a.array for a in arrays], axis=0), (axis,) + arrays[0].axes) + + # elementwise unary operations abs = wrap_elemwise_unary(jnp.abs) absolute = wrap_elemwise_unary(jnp.absolute) diff --git a/src/haliax/partitioning.py b/src/haliax/partitioning.py index 6413ba0..8248102 100644 --- a/src/haliax/partitioning.py +++ b/src/haliax/partitioning.py @@ -58,8 +58,10 @@ def axis_mapping(mapping: ResourceMapping, *, merge: bool = True, **kwargs): mapping.update(kwargs) _mapping_holder.thread_data.resource_mapping = mapping - yield - _mapping_holder.thread_data.resource_mapping = old_mapping + try: + yield + finally: + _mapping_holder.thread_data.resource_mapping = old_mapping T = TypeVar("T", bound=PyTree) @@ -171,7 +173,6 @@ def named_pjit( """ # TODO: support jax.Array - if fn is None: return functools.partial( named_pjit, @@ -187,7 +188,6 @@ def named_pjit( in_axis_resources = in_axis_resources or axis_resources out_axis_resources = out_axis_resources or axis_resources - if axis_resources is None and (in_axis_resources is None or out_axis_resources is None): raise ValueError( "Must provide axis_resources, or in_axis_resources and out_axis_resources," @@ -303,10 +303,10 @@ def physical_axis_size(axis: Axis, mapping: Optional[ResourceMapping] = None) -> return prod([mesh_shape[n] for n in name]) -def pspec_for_axis(axis: AxisSpec) -> PartitionSpec: +def pspec_for_axis(axis: AxisSpec, mapping: Optional[ResourceMapping] = None) -> PartitionSpec: """Get the PartitionSpec for a single axis""" axis = ensure_tuple(axis) - return PartitionSpec(*(physical_axis_name(a) for a in axis)) + return PartitionSpec(*(physical_axis_name(a, mapping) for a in axis)) def round_axis_for_partitioning(axis: Axis, mapping: Optional[ResourceMapping] = None) -> Axis: diff --git a/tests/core_test.py b/tests/core_test.py index cf1de36..280c2f7 100644 --- a/tests/core_test.py +++ b/tests/core_test.py @@ -283,3 +283,22 @@ def test_arange(): # test start and stride assert jnp.all(jnp.equal(hax.arange(H, start=2, step=2).array, jnp.arange(2, 22, 2))) + + +def test_stack(): + B = Axis("Batch", 2) + H = Axis("Height", 4) + W = Axis("Width", 3) + + named1 = hax.random.uniform(PRNGKey(0), (H, W)) + named2 = hax.random.uniform(PRNGKey(1), (H, W)) + + assert jnp.all(jnp.equal(hax.stack(B, (named1, named2)).array, jnp.stack((named1.array, named2.array), axis=0))) + + named3 = hax.random.uniform(PRNGKey(2), (W, H)) + # test that this rearranges fine + assert jnp.all( + jnp.equal( + hax.stack(B, (named1, named3)).array, jnp.stack((named1.array, named3.array.transpose(1, 0)), axis=0) + ) + ) commit a4f9bde3ca6b03c4f70a16c2885c13072d57fbc3 Date: 2023-01-10T10:29:47-08:00 update readme diff --git a/README.md b/README.md index 9875bfe..7119619 100644 --- a/README.md +++ b/README.md @@ -52,6 +52,14 @@ You can change the dataset by changing the `dataset` field in the config file. The config file is a [Pyrallis](https://github.com/eladrich/pyrallis) config file. Pyrallis is yet-another yaml-to-dataclass library. You can use `--help` or poke around other configs to see all the options available to you. +### Training on a TPU Cloud VM + +Please see the [TPU Getting Started](docs/Getting-Started-TPU-VM.md) guide for more information on how to set up a TPU Cloud VM and run Levanter there. + +### Training with CUDA + +Please see the [CUDA Getting Started](docs/Getting-Started-CUDA.md) guide for more information on how to set up a CUDA environment and run Levanter there. + ## Contributing commit 4074955ab55338fdc7df85b459356b19715292be Date: 2023-01-10T10:37:11-08:00 link to overview doc in readme diff --git a/README.md b/README.md index 7119619..80e7205 100644 --- a/README.md +++ b/README.md @@ -40,7 +40,7 @@ TODO: put things on pypi, etc ### Training a GPT2-nano -As a kind of hello world, here's how you can train a GPT2-nano model on a small dataset. +As a kind of hello world, here's how you can train a GPT-2 "nano"-sized model on a small dataset. ```bash python examples/gpt2_example.py --config_path config/gpt2_nano.yaml @@ -52,14 +52,17 @@ You can change the dataset by changing the `dataset` field in the config file. The config file is a [Pyrallis](https://github.com/eladrich/pyrallis) config file. Pyrallis is yet-another yaml-to-dataclass library. You can use `--help` or poke around other configs to see all the options available to you. -### Training on a TPU Cloud VM +#### Training on a TPU Cloud VM Please see the [TPU Getting Started](docs/Getting-Started-TPU-VM.md) guide for more information on how to set up a TPU Cloud VM and run Levanter there. -### Training with CUDA +#### Training with CUDA Please see the [CUDA Getting Started](docs/Getting-Started-CUDA.md) guide for more information on how to set up a CUDA environment and run Levanter there. +### Understanding Levanter and Haliax + +Please see the [Overview](docs/Overview.md) guide for more information on how Levanter and Haliax work, their inspirations, etc. ## Contributing commit bbf4df10505d71d4b6dbefb5a3fd6db145883080 Date: 2023-01-10T15:16:49-08:00 Remove most references to GlobalDeviceArrays (#72) * something * seems like jax.Array might "just" work, for now * remove simplify_gdas and use jax.Array instead * more migration to jax.Array * remove most references to GlobalDeviceArray * update test diff --git a/src/haliax/partitioning.py b/src/haliax/partitioning.py index 8248102..e24d948 100644 --- a/src/haliax/partitioning.py +++ b/src/haliax/partitioning.py @@ -127,17 +127,14 @@ def infer_resource_partitions(tree: PyTree, resource_mapping: Optional[ResourceM def partition_spec(node: typing.Any): if isinstance(node, NamedArray): - # if isinstance(node.array, GlobalDeviceArray): - # TODO: should probably check for compatibility - # return FROM_GDA - # else: return NamedArray( PartitionSpec(*tuple(_resource_mapping.get(axis.name, None) for axis in node.axes)), # type: ignore node.axes, ) elif isinstance(node, GlobalDeviceArray): return FROM_GDA - # TODO: jax.Array + elif hasattr(node, "sharding"): + return node.sharding else: return None @@ -155,7 +152,7 @@ def named_pjit( **pjit_args, ): """ - A version of pjit that uses NamedArrays, GlobalDeviceArrays, and the provided resource mapping to infer the + A version of pjit that uses NamedArrays and the provided resource mapping to infer the resource partitions. If no resource mapping is provided, this function attempts to use the global resource mapping. @@ -212,6 +209,7 @@ def named_pjit( static = (static_fun, static_argspec) output_shape = _cached_filter_eval_shape(fn, *args, **kwargs) + # TODO: with new jax.Array I shouldn't have to specify shardings, but I do... in_resources = infer_resource_partitions((dynamic_donated, dynamic_reserved), in_axis_resources) out_resources = infer_resource_partitions(output_shape, out_axis_resources) diff --git a/tests/test_partitioning.py b/tests/test_partitioning.py index 62f7ac1..6bb6ce2 100644 --- a/tests/test_partitioning.py +++ b/tests/test_partitioning.py @@ -4,6 +4,7 @@ import jax.numpy as jnp import numpy as np from jax.interpreters import pxla from jax.interpreters.pxla import PartitionSpec +from jax.sharding import SingleDeviceSharding from jaxtyping import Array from utils import skip_if_not_enough_devices @@ -35,7 +36,7 @@ def test_infer_named_axes(): axes: MyModule = infer_resource_partitions(mod) assert axes.named.array == PartitionSpec(None, ResourceAxis.DATA, ResourceAxis.MODEL) - assert axes.unnamed1 is None + assert axes.unnamed1 is None or isinstance(axes.unnamed1, SingleDeviceSharding) class MyModuleInit(eqx.Module): commit 4d90dc6b0eda9bfccb4bad6b7555acd04084b68e Date: 2023-01-24T09:59:09-08:00 Better ZeRO implementation (#73) FIxes the sharding so that Jax / SPMD more consistently shards the scanned gradient for the blocks over the mesh Also does some refactoring to get there diff --git a/src/haliax/__init__.py b/src/haliax/__init__.py index d08ea95..31aae8b 100644 --- a/src/haliax/__init__.py +++ b/src/haliax/__init__.py @@ -13,12 +13,12 @@ from .core import ( broadcast_to, concat_axis_specs, dot, + enable_shape_checks, flatten_axes, named, rearrange, rename, roll, - shape_checks, split, take, unbind, @@ -26,7 +26,7 @@ from .core import ( ) from .hof import fold, scan, vmap from .ops import clip, isclose, trace, tril, triu, where -from .partitioning import auto_sharded, axis_mapping +from .partitioning import auto_sharded, axis_mapping, shard_with_axis_mapping from .types import Axis, AxisSpec from .wrap import wrap_axiswise_call, wrap_elemwise_binary, wrap_elemwise_unary, wrap_reduction_call @@ -359,7 +359,8 @@ __all__ = [ "true_divide", "auto_sharded", "axis_mapping", - "shape_checks", + "shard_with_axis_mapping", + "enable_shape_checks", "are_shape_checks_enabled", "isclose", ] diff --git a/src/haliax/core.py b/src/haliax/core.py index 424da4c..a14942b 100644 --- a/src/haliax/core.py +++ b/src/haliax/core.py @@ -23,7 +23,7 @@ _ENABLE_SHAPE_CHECKS = True @contextlib.contextmanager -def shape_checks(enabled): +def enable_shape_checks(enabled): """ Sometimes we end up in situations where an array that jax makes is passed into the NamedArray constructor that doesn't conform to the shape we expect. This shows up in particular when we are using jax.vmap or jax.scan, @@ -908,6 +908,6 @@ __all__ = [ "broadcast_to", "broadcast_axis", "broadcast_arrays", - "shape_checks", + "enable_shape_checks", "are_shape_checks_enabled", ] diff --git a/src/haliax/hof.py b/src/haliax/hof.py index a61fb42..d00a3e2 100644 --- a/src/haliax/hof.py +++ b/src/haliax/hof.py @@ -46,6 +46,12 @@ def scan( False otherwise. Behaves similarly to the `default` argument in filter_jit """ + def is_scanned_with_axis(leaf): + if is_named_array(leaf): + return axis in leaf.axes and is_scanned(leaf) + else: + return is_scanned(leaf) + def scanned_f(init, *args, **kwargs): # This implementation is a bit tricky. @@ -53,7 +59,7 @@ def scan( # unscanned arguments are just passed through, essentially captured as part of a lambda # scanned arguments are passed through the scan, which means we need to hoist the axis to the front xs = (args, kwargs) - scanned_xs, unscanned_xs = eqx.partition(xs, is_scanned, is_leaf=is_named_array) + scanned_xs, unscanned_xs = eqx.partition(xs, is_scanned_with_axis, is_leaf=is_named_array) # Next we have to hoist the axis we're scanning over to the front of the array, because that's what scan # expects. Then we have to scan over the 0th dim of the arrays (as flattened non-pytrees) @@ -72,11 +78,9 @@ def scan( scanned_x = jax.tree_util.tree_unflatten(x_elem_structure, scanned_x_leaves) # this part is the most delicate: combining the scanned x with the unscanned x scanned_x = combine(scanned_x, unscanned_xs, is_leaf=is_named_array) - scanned_x = auto_sharded(scanned_x) args, kwargs = scanned_x carry, y = f(carry, *args, **kwargs) y = jax.tree_util.tree_map(_pacify_named_arrays, y, is_leaf=is_named_array) - y = auto_sharded(y) return carry, y leaves = jax.tree_util.tree_leaves(axis_first_xs) diff --git a/src/haliax/partitioning.py b/src/haliax/partitioning.py index e24d948..534795f 100644 --- a/src/haliax/partitioning.py +++ b/src/haliax/partitioning.py @@ -46,7 +46,7 @@ _mapping_holder = _ResourceMappingHolder() @contextlib.contextmanager -def axis_mapping(mapping: ResourceMapping, *, merge: bool = True, **kwargs): +def axis_mapping(mapping: ResourceMapping, *, merge: bool = False, **kwargs): """Context manager for setting the global resource mapping""" mapping = dict(mapping) @@ -161,8 +161,8 @@ def named_pjit( :param fn: The function to be pjit'd :param axis_resources: A mapping from logical axis names to physical axis names - :param in_axis_resources: A mapping from logical axis names to physical axis names for the input - :param out_axis_resources: A mapping from logical axis names to physical axis names for the output + :param in_axis_resources: A mapping from logical axis names to physical axis names for arguments, defaults to axis_resources + :param out_axis_resources: A mapping from logical axis names to physical axis names for the result, defaults to axis_resources :param donate_args: A PyTree of booleans or function leaf->bool, indicating whether to donate arguments to the computation :param donate_kwargs: A PyTree of booleans or function leaf->bool, indicating whether to donate keyword arguments to commit 141f91dae28e6b63e4ced29452bc39610143121e Date: 2023-01-24T12:03:57-08:00 Extract attention masks to top level (#74) diff --git a/src/haliax/hof.py b/src/haliax/hof.py index d00a3e2..7b29581 100644 --- a/src/haliax/hof.py +++ b/src/haliax/hof.py @@ -11,7 +11,7 @@ from jaxtyping import PyTree from .core import NamedArray from .jax_utils import broadcast_prefix, combine, is_jax_array_like -from .partitioning import auto_sharded, physical_axis_name +from .partitioning import physical_axis_name from .types import Axis from .util import is_jax_or_hax_array_like, is_named_array commit 21519b1fa7f1f663220a10eb79083086239f190b Date: 2023-01-24T13:28:13-08:00 let's try disabling bias again diff --git a/src/haliax/nn/linear.py b/src/haliax/nn/linear.py index c7d9759..41e7217 100644 --- a/src/haliax/nn/linear.py +++ b/src/haliax/nn/linear.py @@ -19,10 +19,10 @@ class Linear(eqx.Module): In: AxisSpec = eqx.static_field() Out: AxisSpec = eqx.static_field() - def __init__(self, In: AxisSpec, Out: AxisSpec, *, key, include_bias=True): + def __init__(self, In: AxisSpec, Out: AxisSpec, *, key, use_bias=True): joint_spec = hax.concat_axis_specs(In, Out) self.weight = hax.random.generate_sharded(hax.random.normal)(key, joint_spec) * 0.02 - self.bias = hax.zeros(Out) if include_bias else None + self.bias = hax.zeros(Out) if use_bias else None self.In = In self.Out = Out commit 33c2911c5c255f62137fbee028fb71c264081a8e Date: 2023-02-09T10:54:09-08:00 Longformer Attention (#75) * add moving_window (from Github) * add padded_moving_window * add padded_moving_window * more direct comparison to numpy * haliax.sliding_window * rm old nn code * longformer attention * simple test of longformer attention * try a different sliding window implementation * wip * wip * wip: one implementation * it works! * cleanup * wip tuning * refactor longformer attention so that we don't have to pad * fix sliding_window test * integrate support for biases into longformer attention * cleanup * integrate support for biases into longformer attention * remove the numpy wrapper sliding_window because we don't use it diff --git a/src/haliax/__init__.py b/src/haliax/__init__.py index 31aae8b..2bfd946 100644 --- a/src/haliax/__init__.py +++ b/src/haliax/__init__.py @@ -19,13 +19,14 @@ from .core import ( rearrange, rename, roll, + slice, split, take, unbind, unflatten_axis, ) from .hof import fold, scan, vmap -from .ops import clip, isclose, trace, tril, triu, where +from .ops import clip, isclose, pad_left, trace, tril, triu, where from .partitioning import auto_sharded, axis_mapping, shard_with_axis_mapping from .types import Axis, AxisSpec from .wrap import wrap_axiswise_call, wrap_elemwise_binary, wrap_elemwise_unary, wrap_reduction_call @@ -221,6 +222,7 @@ __all__ = [ "roll", "split", "flatten_axes", + "slice", "take", "unbind", "rename", @@ -363,4 +365,5 @@ __all__ = [ "enable_shape_checks", "are_shape_checks_enabled", "isclose", + "pad_left", ] diff --git a/src/haliax/core.py b/src/haliax/core.py index a14942b..da52ca2 100644 --- a/src/haliax/core.py +++ b/src/haliax/core.py @@ -158,6 +158,9 @@ class NamedArray: def rename(self, renames: Mapping[Axis, Axis]) -> "NamedArray": return haliax.rename(self, renames=renames) + def slice(self, axis: Axis, new_axis: Axis, start: int = 0) -> "NamedArray": + return haliax.slice(self, axis=axis, new_axis=new_axis, start=start) + def take(self, axis: Axis, index: Union[int, "NamedArray"]) -> "NamedArray": return haliax.take(self, axis=axis, index=index) @@ -485,6 +488,21 @@ def take(array: NamedArray, axis: Axis, index: Union[int, NamedArray]) -> NamedA return NamedArray(new_array, new_axes) +def slice(array: NamedArray, axis: Axis, new_axis: Axis, start: int = 0) -> NamedArray: + """ + Selects elements from an array along an axis, by an index or by another named array + This is somewhat better than take if you want a contiguous slice of an array + """ + axis_index = array._lookup_indices(axis) + if axis_index is None: + raise ValueError(f"axis {axis} not found in {array}") + + sliced = jax.lax.dynamic_slice_in_dim(array.array, start, new_axis.size, axis=axis_index) + new_axes = array.axes[:axis_index] + (new_axis,) + array.axes[axis_index + 1 :] + # new axes come from splicing the old axis with + return NamedArray(sliced, new_axes) + + def dot(axis: AxisSpec, *arrays: NamedArray, precision: PrecisionLike = None) -> NamedArray: """Returns the tensor product of two NamedArrays. The axes `axis` are contracted over, and any other axes that are shared between the arrays are batched over. Non-contracted Axes in one @@ -898,6 +916,7 @@ __all__ = [ "dot", "named", "rearrange", + "slice", "take", "split", "flatten_axes", diff --git a/src/haliax/nn/attention.py b/src/haliax/nn/attention.py index f8c7b7c..868c52d 100644 --- a/src/haliax/nn/attention.py +++ b/src/haliax/nn/attention.py @@ -3,6 +3,7 @@ from typing import List, Optional import jax import jax.numpy as jnp +import numpy as np from jax.random import PRNGKey import haliax @@ -12,8 +13,10 @@ from haliax.types import Axis, AxisSpec, PrecisionLike # With attention we usually distinguish between the mask and the bias, though the former is just a special case of the -# latter. In practice, the mask is a boolean array that is applied after the softmax, while the bias is a float array -# that is applied before the softmax. +# latter. In practice, the mask is a boolean array that is applied using `where` to the logits, while the bias is a +# float array that is added to the logits. The mask is usually used to prevent attention to certain positions, while +# the bias is usually used to encourage or discourage attention to certain positions. +# The mask usually is head-independent, while the bias is frequently head-dependent # because we use named axis we can be fairly loose about the shape of masks and biases: want to have a different # mask for each head? fine. want to broadcast across the key sequence length? fine. etc etc @@ -37,8 +40,8 @@ def dot_product_attention_weights( :param KSeqLen: Axis of key sequence length. Can be an AxisSpec to attend along more than one axis. :param query: NamedArray of shape (QSeqLen, HeadDim) :param key: NamedArray of shape (KSeqLen, HeadDim) - :param mask: Optional[NamedArray] broadcast compatible with (HeadDim, QSeqLen, KSeqLen). Should be boolean, applied after softmax. - :param bias: Optional[NamedArray] broadcast compatible with (HeadDim, QSeqLen, KSeqLen). Should be float, applied before softmax. + :param mask: Optional[NamedArray] broadcast compatible with (HeadDim, QSeqLen, KSeqLen). Should be boolean + :param bias: Optional[NamedArray] broadcast compatible with (HeadDim, QSeqLen, KSeqLen). Should be float :param attention_dtype: Optional dtype to use for attention :param precision: PrecisionLike for dot product. See precision argument to jax.lax.dot_general :return: NamedArray of shape (QSeqLen, KSeqLen) @@ -57,12 +60,11 @@ def dot_product_attention_weights( if bias is not None: weights = weights + bias + if mask is not None: + weights = haliax.where(mask, weights, -1e9) weights = hnn.softmax(weights, axis=KSeqLen) - if mask is not None: - weights = weights * mask - return weights.astype(orig_dtype) @@ -87,11 +89,15 @@ def dot_product_attention( :param query: NamedArray of shape (QSeqLen, HeadDim) :param key: NamedArray of shape (KSeqLen, HeadDim) :param value: NamedArray of shape (KSeqLen, HeadDim) - :param mask: Optional[NamedArray] broadcast compatible with (HeadDim, QSeqLen, KSeqLen). Should be boolean, applied after softmax. - :param bias: Optional[NamedArray] broadcast compatible with (HeadDim, QSeqLen, KSeqLen). Should be float, applied before softmax. + :param mask: Optional[NamedArray] broadcast compatible with (HeadDim, QSeqLen, KSeqLen). Should be boolean + :param bias: Optional[NamedArray] broadcast compatible with (HeadDim, QSeqLen, KSeqLen). Should be float :param attention_dtype: Optional dtype to use for attention :param precision: PrecisionLike for dot product. See precision argument to jax.lax.dot_general :return: NamedArray of shape (QSeqLen, HeadDim) + + Mask and bias are given as separate arguments because they are often computed separately and have different shapes. + For example, mask is frequently just a boolean array of shape (QSeqLen, KSeqLen), while bias is frequently a float + array of shape (HeadDim, QSeqLen, KSeqLen) or (HeadDim, KSeqLen) """ # cf https://github.com/google/flax/blob/509bf97ea272e130d932920f45307ac98947d994/flax/linen/attention.py#L125 @@ -185,7 +191,7 @@ def _get_alibi_slopes(heads: int) -> List[float]: ) -def alibi_attention_bias(Heads: Axis, SeqLen: Axis) -> NamedArray: +def alibi_attention_bias(Heads: Axis, SeqLen: Axis, dtype=jnp.float32) -> NamedArray: """ Creates an attention bias for alibi attention. @@ -193,7 +199,8 @@ def alibi_attention_bias(Heads: Axis, SeqLen: Axis) -> NamedArray: :param Heads: Axis of heads :return: NamedArray of shape (Heads, QSeqLen) """ - slopes = haliax.named(jnp.array(_get_alibi_slopes(Heads.size)), Heads) + slopes = haliax.named(np.array(_get_alibi_slopes(Heads.size)), Heads) positions = haliax.arange(SeqLen).broadcast_axis(Heads) - return slopes * positions + biases = slopes * positions + return biases.astype(dtype) diff --git a/src/haliax/ops.py b/src/haliax/ops.py index 93e3533..4f21a94 100644 --- a/src/haliax/ops.py +++ b/src/haliax/ops.py @@ -87,10 +87,27 @@ def isclose(a: NamedArray, b: NamedArray, rtol=1e-05, atol=1e-08, equal_nan=Fals return NamedArray(jnp.isclose(a.array, b.array, rtol=rtol, atol=atol, equal_nan=equal_nan), a.axes) +def pad_left(array: NamedArray, axis: Axis, new_axis: Axis, value=0) -> NamedArray: + """Pad an array along named axes.""" + amount_to_pad_to = new_axis.size - axis.size + if amount_to_pad_to < 0: + raise ValueError(f"Cannot pad {axis} to {new_axis}") + + idx = array._lookup_indices(axis) + + padding = [(0, 0)] * array.ndim + if idx is None: + raise ValueError(f"Axis {axis} not found in array. Available axes: {array.axes}") + padding[idx] = (amount_to_pad_to, 0) + + padded = jnp.pad(array.array, padding, constant_values=value) + return NamedArray(padded, array.axes[:idx] + (new_axis,) + array.axes[idx + 1 :]) + + def raw_array_or_scalar(x: NamedOrNumeric): if isinstance(x, NamedArray): return x.array return x -__all__ = ["trace", "where", "tril", "triu", "isclose"] +__all__ = ["trace", "where", "tril", "triu", "isclose", "pad_left", "clip"] diff --git a/tests/test_attention.py b/tests/test_attention.py index adc393d..62de3cc 100644 --- a/tests/test_attention.py +++ b/tests/test_attention.py @@ -1,4 +1,6 @@ +import numpy as np from jax.random import PRNGKey +from utils import skip_if_no_torch import haliax as hax from haliax.nn.attention import alibi_attention_bias, dot_product_attention_weights, forgetful_causal_mask @@ -23,6 +25,24 @@ def test_alibi_attention_bias(): assert weights_no_bias.take(KeySeqLen, -1).item() == weights_no_bias.take(KeySeqLen, -2).item() +@skip_if_no_torch +def test_alibi_attention_compared_to_hf(): + import torch + from transformers.models.bloom.modeling_bloom import build_alibi_tensor + + L = hax.Axis("L", 128) + H = hax.Axis("NumHeads", 16) + + # Returns tensor shaped (batch_size * num_heads, 1, max_seq_len) + torch_tensor = ( + build_alibi_tensor(torch.ones(1, L.size), H.size, dtype=torch.float32).numpy().reshape(H.size, L.size) + ) + + hax_tensor = np.array(alibi_attention_bias(H, L).array) + + assert np.allclose(torch_tensor, hax_tensor) + + def test_fcm_attention_mask(): KeySeqLen = hax.Axis("KeySeqLen", 20) commit 6b0b806dbeb6970abb3bb0012213606e7e1f7c62 Date: 2023-03-01T17:14:11-08:00 Autoshutdown hook for TPU vms (#80) * reorganize utils a bit * initial attempt at shutdown hook for tpu vms * use the shutdown hook diff --git a/requirements.txt b/requirements.txt index a4e7fa6..c3b7346 100644 --- a/requirements.txt +++ b/requirements.txt @@ -13,3 +13,4 @@ fsspec==2022.10.0 # pin this to make gcsfs happy tensorstore pytimeparse humanfriendly +requests commit 6f4169440bbef1affade8c144726e7c98f1a2f63 Date: 2023-03-01T22:35:24-08:00 Util cleanup (#81) * some dumb cleanup * merge levanter nn functions with haliax nn functions diff --git a/src/haliax/nn/__init__.py b/src/haliax/nn/__init__.py index 56e808f..bdbba39 100644 --- a/src/haliax/nn/__init__.py +++ b/src/haliax/nn/__init__.py @@ -1,10 +1,11 @@ import functools -from typing import Union +from typing import Tuple, Union import jax.nn as jnn import jax.numpy as jnp import haliax +import haliax as hax import haliax.nn.attention as attention from ..core import NamedArray @@ -56,6 +57,41 @@ def one_hot(x: Union[NamedArray, int], class_axis: Axis, *, dtype=jnp.float_) -> return haliax.named(array, class_axis) +def cross_entropy_loss( + pred_y: NamedArray, + Label: Axis, + target_y: NamedArray, +) -> NamedArray: + loss, _ = cross_entropy_loss_and_log_normalizers(pred_y, Label, target_y) + return loss + + +def cross_entropy_loss_and_log_normalizers( + pred_y: NamedArray, + Label: Axis, + target_y: NamedArray, +) -> Tuple[NamedArray, NamedArray]: + """ + Compute the cross entropy loss and log normalizers for a batch of predictions and targets. + + :param pred_y: a NamedArray with the Label axis (and possibly others for e.g. batch and seq) containing the logits + :param Label: the Label axis + :param target_y: a NamedArray with the Label axis (and possibly others) containing the targets + + :return: tuple of two named arrays, with "per position" losses and log normalizers + """ + log_normalizers = hax.nn.logsumexp(pred_y, Label) + neg_log_normalized = log_normalizers - pred_y + + loss = hax.dot(Label, target_y, neg_log_normalized) + + return loss, log_normalizers + + +def quick_gelu(x): + return x * sigmoid(1.702 * x) + + __all__ = [ "attention", "relu", @@ -79,6 +115,9 @@ __all__ = [ "softmax", "log_softmax", "one_hot", + "cross_entropy_loss", + "cross_entropy_loss_and_log_normalizers", + "quick_gelu", "Dropout", "LayerNorm", "Linear", commit 637e8f8492eb6c16083bc0b01d7887412311e19e Date: 2023-03-02T00:29:58-08:00 Migrate to safe tensors, remove dependency on pytorch for creating HF checkpoints (#82) * wip * use safetensors when we can for loading * use safetensors for saving (i.e. pytorchless saving of hf checkpoints!) diff --git a/requirements.txt b/requirements.txt index c3b7346..cac0413 100644 --- a/requirements.txt +++ b/requirements.txt @@ -14,3 +14,4 @@ tensorstore pytimeparse humanfriendly requests +safetensors[numpy] commit 78b448ddbee0496d92071cd477f945b306011ddf Date: 2023-03-04T13:35:33-08:00 Visualize log probs in html (#83) * simple function to dump an html file with heatmaps for log probs * trying to use the heatmap? * more or less working * improve detokenization * improve detokenization * fix up the heatmap stuff * require matplotlib diff --git a/requirements.txt b/requirements.txt index cac0413..66b629f 100644 --- a/requirements.txt +++ b/requirements.txt @@ -15,3 +15,4 @@ pytimeparse humanfriendly requests safetensors[numpy] +matplotlib commit f5f66a9e292fedc577416ac1399b9ac87665e197 Date: 2023-03-06T18:58:32-08:00 fix up the gpt2 eval script, compare to pure torch, just in case diff --git a/src/haliax/partitioning.py b/src/haliax/partitioning.py index 534795f..f9012a3 100644 --- a/src/haliax/partitioning.py +++ b/src/haliax/partitioning.py @@ -182,8 +182,12 @@ def named_pjit( ) axis_resources = axis_resources or _mapping_holder.thread_data.resource_mapping - in_axis_resources = in_axis_resources or axis_resources - out_axis_resources = out_axis_resources or axis_resources + + if in_axis_resources is None: + in_axis_resources = axis_resources + + if out_axis_resources is None: + out_axis_resources = axis_resources if axis_resources is None and (in_axis_resources is None or out_axis_resources is None): raise ValueError( commit f0fe9c17ab6e3ff1f662affa4b8bda5ae17c0c7f Date: 2023-03-14T14:14:15-07:00 Fixes to eval, hf checkpoint conversion (#87) * grr * tqdm * better tqdm * support eval on train * add tqdm to torch * loss mask * oops * wip fixing model conversion for large models * wip fixing model conversion for large models * wip fixing model conversion for large models * oops * logging? * this seems ok * cleanup * tweaks wip * more logging and synchronization for checkpoint extraction * tweak to fix tokenizer loading * remove files we shouldn't put in this patch * something's going on with the test server * tweak requirements.txt for new gcsfs diff --git a/requirements.txt b/requirements.txt index 66b629f..c1c9b61 100644 --- a/requirements.txt +++ b/requirements.txt @@ -6,10 +6,10 @@ pyrallis pyarrow zstandard datasets~=2.6.0 -gcsfs==2022.10.0 +gcsfs==2023.3.0 braceexpand jmp @ git+https://github.com/deepmind/jmp#7b3ae548154625a56a6dbdb03bc07d4f599c37b2 -fsspec==2022.10.0 # pin this to make gcsfs happy +fsspec==2023.3.0 # pin this to make gcsfs happy tensorstore pytimeparse humanfriendly commit 682377148218c49acb7374ab48e09fd2fb504d72 Date: 2023-03-29T20:23:02-07:00 Sharded token indexing offline (#100) diff --git a/requirements.txt b/requirements.txt index c1c9b61..c46bcbd 100644 --- a/requirements.txt +++ b/requirements.txt @@ -16,3 +16,4 @@ humanfriendly requests safetensors[numpy] matplotlib +filelock commit 72f8d9ec1d94e93e0a164cad2e9b8f970e018b82 Date: 2023-04-10T22:57:30-07:00 remove most references to gda (#110) diff --git a/src/haliax/jax_utils.py b/src/haliax/jax_utils.py index 915e1d5..051a8a0 100644 --- a/src/haliax/jax_utils.py +++ b/src/haliax/jax_utils.py @@ -38,9 +38,7 @@ def maybe_rng_split(key: Optional[PRNGKey], num: int = 2): def filter_eval_shape(fun: Callable, *args, **kwargs): - """As `jax.eval_shape`, but allows any Python object as inputs and outputs, including - GlobalDeviceArrays (which equinox.filter_eval_shape does not support). - """ + """As `jax.eval_shape`, but allows any Python object as inputs and outputs""" # TODO: file a bug diff --git a/src/haliax/partitioning.py b/src/haliax/partitioning.py index f9012a3..1baaece 100644 --- a/src/haliax/partitioning.py +++ b/src/haliax/partitioning.py @@ -9,8 +9,7 @@ import equinox as eqx import jax from equinox import is_array from equinox.compile_utils import compile_cache, get_fun_names, hashable_combine, hashable_partition -from jax.experimental.global_device_array import GlobalDeviceArray -from jax.experimental.pjit import FROM_GDA, pjit, with_sharding_constraint +from jax.experimental.pjit import pjit, with_sharding_constraint from jax.interpreters.pxla import PartitionSpec from jaxtyping import PyTree @@ -131,8 +130,8 @@ def infer_resource_partitions(tree: PyTree, resource_mapping: Optional[ResourceM PartitionSpec(*tuple(_resource_mapping.get(axis.name, None) for axis in node.axes)), # type: ignore node.axes, ) - elif isinstance(node, GlobalDeviceArray): - return FROM_GDA + # elif isinstance(node, GlobalDeviceArray): + # return FROM_GDA elif hasattr(node, "sharding"): return node.sharding else: commit 6eb1098efc8d0bbe1207cb47913fdc283e255b44 Date: 2023-04-17T11:40:45-07:00 fix missing returns in text.pyu i don't understand how this code made it in/wasn't caught diff --git a/src/haliax/partitioning.py b/src/haliax/partitioning.py index 1baaece..b42d965 100644 --- a/src/haliax/partitioning.py +++ b/src/haliax/partitioning.py @@ -202,8 +202,16 @@ def named_pjit( dynamic = (dynamic_fun, dynamic_argspec) if donate_args is not None or donate_kwargs is not None: - dargs = donate_args or (False,) * len(args) + if donate_args is None: + dargs = (False,) * len(args) + elif isinstance(donate_args, bool): + dargs = (donate_args,) * len(args) + elif not isinstance(donate_args, tuple): + dargs = tuple(donate_args) + else: + dargs = donate_args dkwargs = donate_kwargs or {k: False for k in kwargs} + dkwargs = {k: dkwargs.get(k, False) for k in kwargs} dynamic_donated, dynamic_reserved = eqx.partition(dynamic, (False, (dargs, dkwargs))) else: dynamic_donated = jax.tree_util.tree_map(lambda _: None, dynamic) commit 270a8ecdd6465b77bc158313cf06901956a6d139 Date: 2023-04-17T12:12:10-07:00 fix "replicated" arrays in named_pjit diff --git a/src/haliax/partitioning.py b/src/haliax/partitioning.py index b42d965..b8b3c42 100644 --- a/src/haliax/partitioning.py +++ b/src/haliax/partitioning.py @@ -11,6 +11,7 @@ from equinox import is_array from equinox.compile_utils import compile_cache, get_fun_names, hashable_combine, hashable_partition from jax.experimental.pjit import pjit, with_sharding_constraint from jax.interpreters.pxla import PartitionSpec +from jaxlib.xla_client import SingleDeviceSharding from jaxtyping import PyTree from .core import NamedArray @@ -133,7 +134,12 @@ def infer_resource_partitions(tree: PyTree, resource_mapping: Optional[ResourceM # elif isinstance(node, GlobalDeviceArray): # return FROM_GDA elif hasattr(node, "sharding"): - return node.sharding + sharding = node.sharding + # these are usually replicated. Is there a better way to tell? + if isinstance(sharding, SingleDeviceSharding): + return None + else: + return sharding else: return None commit 2bf9bc9deb4c0a08265976ee8fcc7c89649f307e Date: 2023-04-26T00:14:24-07:00 Scan Module to hide "scan over layers" unpleasantness in gpt2 (#111) * push auto_shard into Linear * initial attempt at a "Stacked" module for scanned layers * wip * ok it works (modulo serialization) * wip * wip * add filter_checkpoint * add methods for extracting vectorized blocks * cleanup old comments/remove old code * more docs * dumb import * make call to fold explicit in gpt * make call to fold explicit in gpt * add an example diff --git a/src/haliax/jax_utils.py b/src/haliax/jax_utils.py index 051a8a0..0ed0ab8 100644 --- a/src/haliax/jax_utils.py +++ b/src/haliax/jax_utils.py @@ -53,6 +53,28 @@ def filter_eval_shape(fun: Callable, *args, **kwargs): return eqx.combine(dynamic_out, static_out.value) +def filter_checkpoint(fun: Callable, *, prevent_cse: bool = True, policy: Optional[Callable[..., bool]] = None): + """As `jax.checkpoint`, but allows any Python object as inputs and outputs""" + + @ft.wraps(fun) + def _fn(_static, _dynamic): + _args, _kwargs = eqx.combine(_static, _dynamic) + _out = fun(*_args, **_kwargs) + _dynamic_out, _static_out = eqx.partition(_out, is_jax_array_like) + return _dynamic_out, Static(_static_out) + + checkpointed_fun = jax.checkpoint(_fn, prevent_cse=prevent_cse, policy=policy, static_argnums=(0,)) + + @ft.wraps(fun) + def wrapper(*args, **kwargs): + dynamic, static = eqx.partition((args, kwargs), is_jax_array_like) + dynamic_out, static_out = checkpointed_fun(static, dynamic) + + return eqx.combine(dynamic_out, static_out.value) + + return wrapper + + def is_jax_array_like(x): return hasattr(x, "shape") and hasattr(x, "dtype") diff --git a/src/haliax/nn/linear.py b/src/haliax/nn/linear.py index 41e7217..75b521f 100644 --- a/src/haliax/nn/linear.py +++ b/src/haliax/nn/linear.py @@ -30,8 +30,11 @@ class Linear(eqx.Module): @jax.named_scope(name="linear") def __call__(self, inputs): q = inputs.dot(self.In, self.weight) + q = hax.auto_sharded(q) if self.bias is not None: q = q + self.bias + q = hax.auto_sharded(q) + return q diff --git a/src/haliax/nn/scan.py b/src/haliax/nn/scan.py new file mode 100644 index 0000000..5640d1d --- /dev/null +++ b/src/haliax/nn/scan.py @@ -0,0 +1,79 @@ +from typing import Dict, Generic, Optional, Type, TypeVar + +import equinox as eqx + +import haliax +from haliax import Axis +from haliax.jax_utils import filter_checkpoint + + +M = TypeVar("M", bound=eqx.Module) + + +class Stacked(eqx.Module, Generic[M]): + """ + A "Stacked" wraps another module and produces a "stacked" version of it, where an input is applied + to each instance of the stacked module in sequence. This is useful for e.g. transformers + where you have multiple instances of the same transformer block and the input is applied in a fold/for loop + in sequence. + + It's similar in spirit to an equinox.nn.Sequential, but it must be homogeneous. In Jax, this is much cheaper to + compile than a sequential (or moral equivalent), because Jax compiles the module's method once, instead of unrolling + the sequential and compiling everything as a giant graph. In Jax, this pattern is often called "scan layers" or + "scan over layers". + + Stacked supports both "fold" and "scan" semantics. "fold" is the same as a for loop that accumulates a single + output, while "scan" is the same as a for loop that accumulates a list of intermediates as well as the final output. + + Stacked also supports gradient checkpointing, which is useful for very large models that don't fit in memory. + + Example: + >>> import equinox as eqx + >>> import haliax as hax + >>> import haliax.nn as hnn + >>> class MyModule(eqx.Module): + ... def __init__(self, num_layers: int, hidden: hax.Axis, *, key): + ... self.axis = Axis("layer", num_layers) + ... self.layers = Stacked(self.axis, hnn.Linear, In=hidden, Out=hidden, key=key) + ... + ... def __call__(self, x): + ... return self.layers.fold(x) # applies each layer in sequence + ... + >>> Hidden = Axis("hidden", 10) + >>> mod = MyModule(5, Hidden) + >>> mod(hax.ones(Hidden)) + """ + + stacked: M + Block: Axis = eqx.static_field() + # TODO: support fancier gradient checkpointing + gradient_checkpointing: bool = eqx.static_field() + + def __init__(self, Block: Axis, module: Type[M], *args, gradient_checkpointing: bool = False, **kwargs): + super().__init__() + self.Block = Block + self.stacked = haliax.vmap(module, Block)(*args, **kwargs) + self.gradient_checkpointing = gradient_checkpointing + + def scan(self, init, *extra_args, **extra_kwargs): + if self.gradient_checkpointing: + do_block = filter_checkpoint(self._do_block) + else: + do_block = self._do_block + return haliax.scan(do_block, self.Block)(init, self.stacked, *extra_args, **extra_kwargs) + + def fold(self, init, *args, **kwargs): + if self.gradient_checkpointing: + do_block = filter_checkpoint(self._do_block) + else: + do_block = self._do_block + + return haliax.fold(do_block, self.Block)(init, self.stacked, *args, **kwargs) + + @staticmethod + def _do_block(carry, block, *extra_args, **extra_kwargs): + return block(carry, *extra_args, **extra_kwargs) + + # TODO: this is for logic that's in levanter. We should move that logic to haliax I guess? + def _state_dict_key_map(self) -> Optional[Dict[str, Optional[str]]]: + return {"stacked": None} commit 288eca9410e7bdc988e737b135d1367b55a997a9 Date: 2022-11-26T18:00:54-08:00 add glu diff --git a/src/haliax/nn/__init__.py b/src/haliax/nn/__init__.py index bdbba39..71569e1 100644 --- a/src/haliax/nn/__init__.py +++ b/src/haliax/nn/__init__.py @@ -33,7 +33,12 @@ elu = wrap_elemwise_unary(jnn.elu) celu = wrap_elemwise_unary(jnn.celu) selu = wrap_elemwise_unary(jnn.selu) gelu = wrap_elemwise_unary(jnn.gelu) -# TODO: glu = wrap_elemwise_unary(jnn.gelu) + + +def glu(x: NamedArray, axis: Axis) -> NamedArray: + axis_index = x.axes.index(axis) + return jnn.glu(x.array, axis_index) + logsumexp = wrap_reduction_call(jnn.logsumexp, False, supports_where=False) commit 60889aa7e20ec162e79b25f1cadd31cee164f9f5 Date: 2022-11-26T19:22:12-08:00 add standardize diff --git a/src/haliax/__init__.py b/src/haliax/__init__.py index 2bfd946..585457e 100644 --- a/src/haliax/__init__.py +++ b/src/haliax/__init__.py @@ -9,6 +9,7 @@ from haliax import nn as nn from .core import ( NamedArray, are_shape_checks_enabled, + broadcast_arrays, broadcast_axis, broadcast_to, concat_axis_specs, diff --git a/src/haliax/core.py b/src/haliax/core.py index da52ca2..437accb 100644 --- a/src/haliax/core.py +++ b/src/haliax/core.py @@ -846,24 +846,45 @@ def broadcast_arrays( @overload def broadcast_arrays( - *arrays: NamedOrNumeric, require_subset: bool = True, ensure_order: bool = True -) -> Tuple[NamedOrNumeric, ...]: + *arrays: Optional[NamedOrNumeric], require_subset: bool = True, ensure_order: bool = True +) -> Tuple[Optional[NamedOrNumeric], ...]: ... def broadcast_arrays( - *arrays: NamedOrNumeric, + *arrays: Optional[NamedOrNumeric], require_subset: bool = True, ensure_order: bool = True, -) -> Tuple[NamedOrNumeric, ...]: +) -> Tuple[Optional[NamedOrNumeric], ...]: return broadcast_arrays_and_return_axes(*arrays, require_subset=require_subset, ensure_order=ensure_order)[0] +@overload +def broadcast_arrays_and_return_axes( + *arrays: NamedArray, require_subset: bool = True, ensure_order: bool = True +) -> Tuple[Tuple[NamedArray, ...], Tuple[Axis, ...]]: + ... + + +@overload +def broadcast_arrays_and_return_axes( + *arrays: NamedOrNumeric, require_subset: bool = True, ensure_order: bool = True +) -> Tuple[Tuple[NamedOrNumeric, ...], Tuple[Axis, ...]]: + ... + + +@overload +def broadcast_arrays_and_return_axes( + *arrays: Optional[NamedOrNumeric], require_subset: bool = True, ensure_order: bool = True +) -> Tuple[Tuple[Optional[NamedOrNumeric], ...], Tuple[Axis, ...]]: + ... + + def broadcast_arrays_and_return_axes( - *arrays: NamedOrNumeric, + *arrays: Optional[NamedOrNumeric], require_subset: bool = True, ensure_order: bool = True, -) -> Tuple[Tuple[NamedOrNumeric, ...], Tuple[Axis, ...]]: +) -> Tuple[Tuple[Optional[NamedOrNumeric], ...], Tuple[Axis, ...]]: """ Broadcasts a sequence of arrays to a common set of axes. diff --git a/src/haliax/nn/__init__.py b/src/haliax/nn/__init__.py index 71569e1..467df6e 100644 --- a/src/haliax/nn/__init__.py +++ b/src/haliax/nn/__init__.py @@ -1,5 +1,5 @@ import functools -from typing import Tuple, Union +from typing import Optional, Tuple, Union import jax.nn as jnn import jax.numpy as jnp @@ -9,8 +9,8 @@ import haliax as hax import haliax.nn.attention as attention from ..core import NamedArray -from ..types import Axis -from ..wrap import wrap_axiswise_call, wrap_elemwise_unary, wrap_reduction_call +from ..types import Axis, AxisSpec +from ..wrap import unwrap_namedarrays, wrap_axiswise_call, wrap_elemwise_unary, wrap_reduction_call from .dropout import Dropout from .linear import Linear from .normalization import LayerNorm @@ -44,11 +44,27 @@ logsumexp = wrap_reduction_call(jnn.logsumexp, False, supports_where=False) # TODO: support where in softmax, etc softmax = wrap_axiswise_call(jnn.softmax, False) -# TODO: standardize has optional "mean" and "variance" arguments we need to support -# standardize = wrap_normalization_call(jnn.standardize, False) log_softmax = wrap_axiswise_call(jnn.log_softmax, False) +def standardize( + x: NamedArray, + axis: AxisSpec, + *, + mean: Optional[NamedArray] = None, + variance: Optional[NamedArray] = None, + epsilon: float = 1e-5, + where: Optional[NamedArray] = None, +) -> NamedArray: + """Analogous to `jax.nn.standardize`, but with support for NamedArrays.""" + x, mean, variance, where = haliax.broadcast_arrays(x, mean, variance, where) # type: ignore + raw_x, mean, variance, where = unwrap_namedarrays(x, mean, variance, where) + axis_indices = x._lookup_indices(axis) + + plain = jnn.standardize(raw_x, axis_indices, mean=mean, variance=variance, epsilon=epsilon, where=where) + return NamedArray(plain, x.axes) + + @functools.wraps(jnn.one_hot) def one_hot(x: Union[NamedArray, int], class_axis: Axis, *, dtype=jnp.float_) -> NamedArray: if isinstance(x, NamedArray): diff --git a/src/haliax/wrap.py b/src/haliax/wrap.py index df72187..39fa2ab 100644 --- a/src/haliax/wrap.py +++ b/src/haliax/wrap.py @@ -134,4 +134,14 @@ def wrap_elemwise_binary(op): return binop -__all__ = ["wrap_elemwise_unary", "wrap_reduction_call", "wrap_axiswise_call", "wrap_elemwise_binary"] +def unwrap_namedarrays(*a): + return tuple(x.array if isinstance(x, NamedArray) else x for x in a) + + +__all__ = [ + "wrap_elemwise_unary", + "wrap_reduction_call", + "wrap_axiswise_call", + "wrap_elemwise_binary", + "unwrap_namedarrays", +] diff --git a/tests/test_nn.py b/tests/test_nn.py index ea18ae5..52f4b26 100644 --- a/tests/test_nn.py +++ b/tests/test_nn.py @@ -1,4 +1,5 @@ import equinox as eqx +import jax.nn import jax.random as jrandom from jax import numpy as jnp @@ -62,3 +63,45 @@ def test_one_hot_out_of_bound(): actual = hax.nn.one_hot(hax.NamedArray(jnp.array([-1, 3]), (i,)), c) expected = jnp.array([[0.0, 0.0, 0.0], [0.0, 0.0, 0.0]]) assert jnp.all(jnp.isclose(actual.array, expected)) + + +def test_standardize(): + b = Axis("b", 2) + c = Axis("c", 3) + actual = hax.nn.standardize(hax.NamedArray(jnp.array([0, 1, 2]), (c,)), c) + expected = jax.nn.standardize(jnp.array([0, 1, 2]), axis=0) + + assert actual.axes == (c,) + assert jnp.all(jnp.isclose(actual.array, expected)) + + actual = hax.nn.standardize(hax.NamedArray(jnp.array([[0, 1, 2], [3, 4, 5]]), (b, c)), c) + expected = jax.nn.standardize(jnp.array([[0, 1, 2], [3, 4, 5]]), axis=1) + + assert actual.axes == (b, c) + assert jnp.all(jnp.isclose(actual.array, expected)) + + actual = hax.nn.standardize(hax.NamedArray(jnp.array([[0, 1, 2], [3, 4, 5]]), (b, c)), b) + expected = jax.nn.standardize(jnp.array([[0, 1, 2], [3, 4, 5]]), axis=0) + + assert actual.axes == (b, c) + assert jnp.all(jnp.isclose(actual.array, expected)) + + # test passing in where + mask = hax.NamedArray(jnp.array([True, False, True]), (c,)) + actual = hax.nn.standardize(hax.NamedArray(jnp.array([[0, 1, 2], [3, 4, 5]]), (b, c)), b, where=mask) + expected = jax.nn.standardize(jnp.array([[0, 1, 2], [3, 4, 5]]), axis=0, where=mask.array) + + assert actual.axes == (b, c) + assert jnp.all(jnp.isclose(actual.array, expected) | jnp.isnan(expected)) + + # now mean/variance + input = hax.NamedArray(jnp.array([[0, 1, 2], [3, 4, 5]]), (b, c)) + mean = hax.mean(input, c) + variance = hax.var(input, c) + actual = hax.nn.standardize(input, c, mean=mean, variance=variance) + expected = jax.nn.standardize( + input.array, axis=1, mean=mean.array.reshape(-1, 1), variance=variance.array.reshape(-1, 1) + ) + + assert actual.axes == (b, c) + assert jnp.all(jnp.isclose(actual.array, expected)) commit 7f9e6750f68493b950274abcb37b0863ac633522 Date: 2023-04-29T13:23:15-07:00 Allow "string selectors" where possible in Haliax (#128) Also fixes a hidden bug with gradient accumulation due to manipulation of the batch dim... diff --git a/src/haliax/__init__.py b/src/haliax/__init__.py index 585457e..aedcfba 100644 --- a/src/haliax/__init__.py +++ b/src/haliax/__init__.py @@ -29,7 +29,7 @@ from .core import ( from .hof import fold, scan, vmap from .ops import clip, isclose, pad_left, trace, tril, triu, where from .partitioning import auto_sharded, axis_mapping, shard_with_axis_mapping -from .types import Axis, AxisSpec +from .types import Axis, AxisSelection, AxisSelector, AxisSpec from .wrap import wrap_axiswise_call, wrap_elemwise_binary, wrap_elemwise_unary, wrap_reduction_call @@ -78,8 +78,10 @@ def arange(axis: Axis, *, start=0, step=1, dtype=None) -> NamedArray: return NamedArray(jnp.arange(start, stop, step, dtype=dtype), (axis,)) -def stack(axis: Axis, arrays: Sequence[NamedArray]) -> NamedArray: +def stack(axis: AxisSelector, arrays: Sequence[NamedArray]) -> NamedArray: """Version of jnp.stack that returns a NamedArray""" + if isinstance(axis, str): + axis = Axis(axis, len(arrays)) if len(arrays) == 0: return zeros(axis) arrays = [a.rearrange(arrays[0].axes) for a in arrays] @@ -216,6 +218,8 @@ __all__ = [ "Axis", "NamedArray", "AxisSpec", + "AxisSelection", + "AxisSelector", "broadcast_to", "broadcast_axis", "named", diff --git a/src/haliax/core.py b/src/haliax/core.py index 437accb..3be1b90 100644 --- a/src/haliax/core.py +++ b/src/haliax/core.py @@ -1,6 +1,7 @@ import contextlib import functools as ft import typing +import warnings from dataclasses import dataclass from math import prod from types import EllipsisType @@ -12,9 +13,9 @@ import numpy as np import haliax from haliax.jax_utils import is_jax_array_like -from haliax.util import ensure_tuple +from haliax.util import ensure_tuple, index_where -from .types import Axis, AxisSpec, PrecisionLike, Scalar +from .types import Axis, AxisSelection, AxisSelector, AxisSpec, PrecisionLike, Scalar NamedOrNumeric = Union[Scalar, "NamedArray"] @@ -64,9 +65,9 @@ class NamedArray: raise ValueError(f"Axes must be unique, but {self.axes} are not") if are_shape_checks_enabled(): - self.ensure_shape_matches_axes() + self._ensure_shape_matches_axes() - def ensure_shape_matches_axes(self): + def _ensure_shape_matches_axes(self): """This is typically called automatically, but sometimes we need to call it manually if are_shape_checks_enabled() is False""" if is_jax_array_like(self.array): @@ -74,6 +75,21 @@ class NamedArray: if s != tuple(a.size for a in self.axes): raise ValueError(f"Shape of underlying array {s} does not match shape of axes {self.axes}") + def resolve_axes(self, axes: AxisSelection) -> Tuple[Axis, ...]: + """Returns the axes corresponding to the given axis selection.""" + indices = self._lookup_indices(axes) + if isinstance(indices, int): + return (self.axes[indices],) + elif indices is None: + raise ValueError(f"Axis {axes} not found") + else: + result = [] + for i in indices: + if i is None: + raise ValueError(f"Axis {axes} not found") + result.append(self.axes[i]) + return tuple(result) + def item(self): return self.array.item() @@ -106,18 +122,43 @@ class NamedArray: assert len(tree) == 1 return cls(tree[0], axes=aux) - def has_axis(self, axis: AxisSpec) -> bool: + def has_axis(self, axis: AxisSelection) -> bool: return self._lookup_indices(axis) is not None - @typing.overload - def _lookup_indices(self, axis: Axis) -> Optional[int]: + @overload + def axis_size(self, axis: AxisSelector) -> int: # type: ignore ... - @typing.overload - def _lookup_indices(self, axis: Sequence[Axis]) -> Tuple[Optional[int], ...]: + @overload + def axis_size(self, axis: Sequence[AxisSelector]) -> Tuple[int, ...]: # type: ignore ... - def _lookup_indices(self, axis: AxisSpec) -> Union[Optional[int], Tuple[Optional[int], ...]]: + def axis_size(self, axis: AxisSelection) -> Union[int, Tuple[int, ...]]: + """ + Returns the size of the given axis, or a tuple of sizes if given multiple axes. + """ + indices = self._lookup_indices(axis) + if isinstance(indices, int): + return self.axes[indices].size + elif indices is None: + raise ValueError(f"Axis {axis} not found") + else: + result = [] + for i in indices: + if i is None: + raise ValueError(f"Axis {axis} not found") + result.append(self.axes[i].size) + return tuple(result) + + @overload + def _lookup_indices(self, axis: AxisSelector) -> Optional[int]: # type: ignore + ... + + @overload + def _lookup_indices(self, axis: Sequence[AxisSelector]) -> Tuple[Optional[int], ...]: + ... + + def _lookup_indices(self, axis: AxisSelection) -> Union[Optional[int], Tuple[Optional[int], ...]]: """ For a single axis, returns an int corresponding to the index of the axis. For multiple axes, returns a tuple of ints corresponding to the indices of the axes. @@ -125,15 +166,27 @@ class NamedArray: If the axis is not present, returns None for that position """ if isinstance(axis, Axis): + ax_name = axis.name try: return self.axes.index(axis) + except ValueError: + try: + axis_index = index_where(lambda a: a.name == ax_name, self.axes) + if axis_index >= 0: + warnings.warn("Found axis with same name but different size.", UserWarning) + return axis_index + except ValueError: + return None + elif isinstance(axis, str): + try: + return index_where(lambda a: a.name == axis, self.axes) except ValueError: return None else: return tuple(self._lookup_indices(a) for a in axis) # Axis rearrangement - def rearrange(self, axis: Sequence[Union[Axis, EllipsisType]]) -> "NamedArray": + def rearrange(self, axis: Sequence[Union[AxisSelector, EllipsisType]]) -> "NamedArray": return rearrange(self, axis) def broadcast_to(self, axes: AxisSpec) -> "NamedArray": @@ -143,42 +196,43 @@ class NamedArray: def broadcast_axis(self, axis: AxisSpec) -> "NamedArray": return haliax.broadcast_axis(self, axis=axis) - def split(self, axis: Axis, new_axes: Sequence[Axis]) -> Sequence["NamedArray"]: + def split(self, axis: AxisSelector, new_axes: Sequence[Axis]) -> Sequence["NamedArray"]: return haliax.split(self, axis=axis, new_axes=new_axes) - def flatten_axes(self, old_axes: Sequence[Axis], new_axis: Axis) -> "NamedArray": + def flatten_axes(self, old_axes: Sequence[AxisSelector], new_axis: AxisSelector) -> "NamedArray": return haliax.flatten_axes(self, old_axes=old_axes, new_axis=new_axis) - def unflatten_axis(self, axis: Axis, new_axes: Sequence[Axis]) -> "NamedArray": + def unflatten_axis(self, axis: AxisSelector, new_axes: Sequence[Axis]) -> "NamedArray": return haliax.unflatten_axis(self, axis=axis, new_axes=new_axes) - def unbind(self, axis: Axis) -> Sequence["NamedArray"]: + def unbind(self, axis: AxisSelector) -> Sequence["NamedArray"]: return haliax.unbind(self, axis=axis) - def rename(self, renames: Mapping[Axis, Axis]) -> "NamedArray": + def rename(self, renames: Mapping[AxisSelector, AxisSelector]) -> "NamedArray": return haliax.rename(self, renames=renames) - def slice(self, axis: Axis, new_axis: Axis, start: int = 0) -> "NamedArray": + # TOOD: AxisSelector-ify new_axis + def slice(self, axis: AxisSelector, new_axis: Axis, start: int = 0) -> "NamedArray": return haliax.slice(self, axis=axis, new_axis=new_axis, start=start) - def take(self, axis: Axis, index: Union[int, "NamedArray"]) -> "NamedArray": + def take(self, axis: AxisSelector, index: Union[int, "NamedArray"]) -> "NamedArray": return haliax.take(self, axis=axis, index=index) # np.ndarray methods: - def all(self, axis: Optional[AxisSpec] = None) -> "NamedArray": + def all(self, axis: Optional[AxisSelection] = None) -> "NamedArray": return haliax.all(self, axis=axis) - def any(self, axis: Optional[AxisSpec] = None) -> "NamedArray": + def any(self, axis: Optional[AxisSelection] = None) -> "NamedArray": return haliax.any(self, axis=axis) # TODO: test - def argmax(self, axis: Axis) -> "NamedArray": + def argmax(self, axis: AxisSelector) -> "NamedArray": return haliax.argmax(self, axis=axis) - def argmin(self, axis: Axis) -> "NamedArray": + def argmin(self, axis: AxisSelector) -> "NamedArray": return haliax.argmin(self, axis=axis) - def argsort(self, axis: Axis) -> "NamedArray": + def argsort(self, axis: AxisSelector) -> "NamedArray": return haliax.argsort(self, axis=axis) def astype(self, dtype) -> "NamedArray": @@ -200,13 +254,13 @@ class NamedArray: def copy(self) -> "NamedArray": return NamedArray(self.array.copy(), self.axes) - def cumprod(self, axis: Optional[AxisSpec] = None, *, dtype=None) -> "NamedArray": + def cumprod(self, axis: Optional[AxisSelection] = None, *, dtype=None) -> "NamedArray": return haliax.cumprod(self, axis=axis, dtype=dtype) - def cumsum(self, axis: Optional[AxisSpec] = None, *, dtype=None) -> "NamedArray": + def cumsum(self, axis: Optional[AxisSelection] = None, *, dtype=None) -> "NamedArray": return haliax.cumsum(self, axis=axis, dtype=dtype) - def dot(self, axis: AxisSpec, b, *, precision: PrecisionLike = None) -> "NamedArray": + def dot(self, axis: AxisSelection, b, *, precision: PrecisionLike = None) -> "NamedArray": return dot(axis, self, b, precision=precision) @property @@ -215,7 +269,7 @@ class NamedArray: def max( self, - axis: Optional[AxisSpec] = None, + axis: Optional[AxisSelection] = None, *, initial=None, where=None, @@ -224,7 +278,7 @@ class NamedArray: def mean( self, - axis: Optional[AxisSpec] = None, + axis: Optional[AxisSelection] = None, *, dtype=None, where=None, @@ -233,7 +287,7 @@ class NamedArray: def min( self, - axis: Optional[AxisSpec] = None, + axis: Optional[AxisSelection] = None, *, initial=None, where=None, @@ -242,7 +296,7 @@ class NamedArray: def prod( self, - axis: Optional[AxisSpec] = None, + axis: Optional[AxisSelection] = None, *, dtype=None, initial=None, @@ -256,7 +310,7 @@ class NamedArray: where=where, ) - def ptp(self, axis: AxisSpec = None) -> "NamedArray": + def ptp(self, axis: AxisSelection = None) -> "NamedArray": return haliax.ptp(self, axis=axis) # TODO: implement ravel. Can only do if we either ask for an axis or add ProductAxis or something @@ -274,12 +328,12 @@ class NamedArray: def round(self, decimals=0) -> "NamedArray": return haliax.round(self, decimals=decimals) - def sort(self, axis: Axis, kind="quicksort") -> Any: + def sort(self, axis: AxisSelector, kind="quicksort") -> Any: return haliax.sort(self, axis=axis, kind=kind) def std( self, - axis: Optional[AxisSpec] = None, + axis: Optional[AxisSelection] = None, *, dtype=None, ddof=0, @@ -295,7 +349,7 @@ class NamedArray: def sum( self, - axis: Optional[AxisSpec] = None, + axis: Optional[AxisSelection] = None, *, dtype=None, initial=None, @@ -315,12 +369,12 @@ class NamedArray: def tolist(self) -> Any: return self.array.tolist() - def trace(self, axis1: Axis, axis2: Axis, offset=0, dtype=None) -> "NamedArray": + def trace(self, axis1: AxisSelector, axis2: AxisSelector, offset=0, dtype=None) -> "NamedArray": return haliax.trace(self, offset=offset, axis1=axis1, axis2=axis2, dtype=dtype) def var( self, - axis: Optional[AxisSpec] = None, + axis: Optional[AxisSelection] = None, dtype=None, ddof=0, *, @@ -468,7 +522,7 @@ class NamedArray: return float(self.array) -def take(array: NamedArray, axis: Axis, index: Union[int, NamedArray]) -> NamedArray: +def take(array: NamedArray, axis: AxisSelector, index: Union[int, NamedArray]) -> NamedArray: """ Selects elements from an array along an axis, by an index or by another named array @@ -488,7 +542,7 @@ def take(array: NamedArray, axis: Axis, index: Union[int, NamedArray]) -> NamedA return NamedArray(new_array, new_axes) -def slice(array: NamedArray, axis: Axis, new_axis: Axis, start: int = 0) -> NamedArray: +def slice(array: NamedArray, axis: AxisSelector, new_axis: Axis, start: int = 0) -> NamedArray: """ Selects elements from an array along an axis, by an index or by another named array This is somewhat better than take if you want a contiguous slice of an array @@ -503,13 +557,12 @@ def slice(array: NamedArray, axis: Axis, new_axis: Axis, start: int = 0) -> Name return NamedArray(sliced, new_axes) -def dot(axis: AxisSpec, *arrays: NamedArray, precision: PrecisionLike = None) -> NamedArray: +def dot(axis: AxisSelection, *arrays: NamedArray, precision: PrecisionLike = None) -> NamedArray: """Returns the tensor product of two NamedArrays. The axes `axis` are contracted over, and any other axes that are shared between the arrays are batched over. Non-contracted Axes in one that are not in the other are preserved. """ - if isinstance(axis, Axis): - axis = [axis] + axis = ensure_tuple(axis) array_specs = [] @@ -529,7 +582,7 @@ def dot(axis: AxisSpec, *arrays: NamedArray, precision: PrecisionLike = None) -> array_specs.append(spec) # now compute the output axes: - output_axes = tuple(ax for ax in axis_mappings.keys() if ax not in axis) + output_axes = tuple(ax for ax in axis_mappings.keys() if not selects_axis(ax, axis)) output_spec = " ".join(str(axis_mappings[ax]) for ax in output_axes) output = jnp.einsum( @@ -541,22 +594,24 @@ def dot(axis: AxisSpec, *arrays: NamedArray, precision: PrecisionLike = None) -> return NamedArray(output, output_axes) -def split(a: NamedArray, axis: Axis, new_axes: Sequence[Axis]) -> Sequence[NamedArray]: +def split(a: NamedArray, axis: AxisSelector, new_axes: Sequence[Axis]) -> Sequence[NamedArray]: # check the lengths of the new axes - if axis not in a.axes: + index = a._lookup_indices(axis) + if index is None: raise ValueError(f"Axis {axis} not found in {a.axes}") total_len = sum(x.size for x in new_axes) - if total_len != axis.size: - raise ValueError(f"The total length of the new axes {total_len} does not match the length of the axis {axis}") - - index = a._lookup_indices(axis) + if isinstance(axis, Axis): + if total_len != axis.size: + raise ValueError( + f"The total length of the new axes {total_len} does not match the length of the axis {axis}" + ) # now we can split the array offsets = np.cumsum([0] + [x.size for x in new_axes])[1:-1] new_arrays = np.split(a.array, indices_or_sections=offsets, axis=index) - ret_axes = [tuple(ax2 if ax2 is not axis else new_axis for ax2 in a.axes) for new_axis in new_axes] + ret_axes = [tuple(ax2 if not selects_axis(axis, ax2) else new_axis for ax2 in a.axes) for new_axis in new_axes] return [NamedArray(x, ax) for x, ax in zip(new_arrays, ret_axes)] @@ -565,7 +620,7 @@ def split(a: NamedArray, axis: Axis, new_axes: Sequence[Axis]) -> Sequence[Named # e.g. we'd like something like rearrange(array, (..., new_axis), merge_axes={new_axis: (old_axis1, old_axis2)}) # or rearrange(array, (new_axis1, ..., new_axis2), split_axes={old_axis: (new_axis1, new_axis2)}) # or even rearrange(array, (x, ..., b, a), map_axes={old_axis: (a, b), x: (old1, old2)}) -def rearrange(array: NamedArray, axes: Sequence[Union[Axis, EllipsisType]]) -> NamedArray: +def rearrange(array: NamedArray, axes: Sequence[Union[AxisSelector, EllipsisType]]) -> NamedArray: """ Rearrange an array so that its underlying storage conforms to axes. axes may include up to 1 ellipsis, indicating that the remaining axes should be @@ -598,7 +653,7 @@ def rearrange(array: NamedArray, axes: Sequence[Union[Axis, EllipsisType]]) -> N permute_spec.append(Ellipsis) # will revisit ellipsis_pos = len(permute_spec) - 1 else: - assert isinstance(ax, Axis) # please mypy + assert isinstance(ax, Axis) or isinstance(ax, str) # please mypy index = array._lookup_indices(ax) if index is None: raise ValueError(f"Axis {ax} not found in {array}") @@ -621,7 +676,7 @@ def rearrange(array: NamedArray, axes: Sequence[Union[Axis, EllipsisType]]) -> N return NamedArray(jnp.transpose(array.array, permute_spec), out_axes) -def unbind(array: NamedArray, axis: Axis) -> List[NamedArray]: +def unbind(array: NamedArray, axis: AxisSelector) -> List[NamedArray]: """ Unbind an array along an axis, returning a list of NamedArrays. Analogous to torch.unbind or np.rollaxis """ @@ -632,13 +687,14 @@ def unbind(array: NamedArray, axis: Axis) -> List[NamedArray]: # this implementation maybe triggers an all-gather in pjit so no good # arrays = jnp.rollaxis(array.array, axis=axis_index, start=0) # instead we just loop over the axes pulling one out at a time - arrays = [jnp.take(array.array, i, axis=axis_index) for i in range(axis.size)] + axis_size = array.axes[axis_index].size + arrays = [jnp.take(array.array, i, axis=axis_index) for i in range(axis_size)] from haliax.partitioning import auto_sharded return [auto_sharded(NamedArray(a, new_axes)) for a in arrays] -def roll(array: NamedArray, shift: Union[int, Tuple[int, ...]], axis: AxisSpec) -> NamedArray: +def roll(array: NamedArray, shift: Union[int, Tuple[int, ...]], axis: AxisSelection) -> NamedArray: """ Roll an array along an axis or axes. Analogous to np.roll """ @@ -648,15 +704,24 @@ def roll(array: NamedArray, shift: Union[int, Tuple[int, ...]], axis: AxisSpec) return NamedArray(jnp.roll(array.array, shift, axis_indices), array.axes) -def rename(array: NamedArray, renames: Mapping[Axis, Axis]) -> NamedArray: +def rename(array: NamedArray, renames: Mapping[AxisSelector, AxisSelector]) -> NamedArray: for old, new in renames.items(): - if old.size != new.size: + if isinstance(old, Axis) and isinstance(new, Axis) and old.size != new.size: raise ValueError(f"Cannot rename axis {old} to {new}: size mismatch") - new_axes = tuple(renames.get(ax, ax) for ax in array.axes) + + def _rename(ax: Axis) -> Axis: + new_axis = renames.get(ax, ax) + if isinstance(new_axis, Axis): + return new_axis + else: + assert isinstance(new_axis, str) + return Axis(new_axis, ax.size) + + new_axes = tuple(_rename(ax) for ax in array.axes) return NamedArray(array.array, new_axes) -def flatten_axes(array: NamedArray, old_axes: Sequence[Axis], new_axis: Axis) -> NamedArray: +def flatten_axes(array: NamedArray, old_axes: Sequence[AxisSelector], new_axis: AxisSelector) -> NamedArray: """ Merge a sequence of axes into a single axis. The new axis must have the same size as the product of the old axes. For now the new axis will always be the last axis @@ -664,17 +729,38 @@ def flatten_axes(array: NamedArray, old_axes: Sequence[Axis], new_axis: Axis) -> if len(old_axes) == 0: raise ValueError("Must specify at least one axis to merge") - if new_axis.size != prod(ax.size for ax in old_axes): - raise ValueError(f"Cannot merge {old_axes} into {new_axis}: size mismatch") + old_axes = array.resolve_axes(old_axes) - # TODO: might want to do something more clever here when the old_axes aren't at the end - array = rearrange(array, (...,) + tuple(old_axes)) - new_axes = array.axes[: -len(old_axes)] + (new_axis,) - raw_array = array.array.reshape(array.array.shape[: -len(old_axes)] + (new_axis.size,)) - return NamedArray(raw_array, new_axes) + if isinstance(new_axis, Axis): + if new_axis.size != prod(array.axis_size(ax) for ax in old_axes): + raise ValueError(f"Cannot merge {old_axes} into {new_axis}: size mismatch") + else: + assert isinstance(new_axis, str) + new_axis = Axis(new_axis, prod(ax.size for ax in old_axes)) + + # ensure that the old_axes are contiguous + # we basically ensure that the old_axes occur after the index of the first old_axis + intermediate_axes: List[Axis] = [] + new_axes: List[Axis] = [] + index_of_first_old_axis = None + for i, ax in enumerate(array.axes): + if ax in old_axes: + if index_of_first_old_axis is None: + index_of_first_old_axis = i + intermediate_axes.extend(old_axes) + new_axes.append(new_axis) + else: + continue + else: + intermediate_axes.append(ax) + new_axes.append(ax) + + array = array.rearrange(intermediate_axes) + raw_array = array.array.reshape([ax.size for ax in new_axes]) + return NamedArray(raw_array, tuple(new_axes)) -def unflatten_axis(array: NamedArray, axis: Axis, new_axes: Sequence[Axis]) -> NamedArray: +def unflatten_axis(array: NamedArray, axis: AxisSelector, new_axes: Sequence[Axis]) -> NamedArray: """ Split an axis into a sequence of axes. The old axis must have the same size as the product of the new axes. """ @@ -682,36 +768,29 @@ def unflatten_axis(array: NamedArray, axis: Axis, new_axes: Sequence[Axis]) -> N if old_index is None: raise ValueError(f"Axis {axis} not found in {array}") + axis_size = array.axes[old_index].size + if len(new_axes) == 0: - if axis.size == 1: + if axis_size == 1: # just remove the old axis, akin to squeeze new_array = jnp.squeeze(array.array, axis=old_index) - new_axes = array.axes[:old_index] + array.axes[old_index + 1 :] - return NamedArray(new_array, new_axes) + resolved_new_axes = array.axes[:old_index] + array.axes[old_index + 1 :] + return NamedArray(new_array, resolved_new_axes) else: raise ValueError("Must specify at least one axis to split") - if axis.size != prod(ax.size for ax in new_axes): + if axis_size != prod(ax.size for ax in new_axes): raise ValueError(f"Cannot split {axis} into {new_axes}: size mismatch") - new_axes = array.axes[:old_index] + tuple(new_axes) + array.axes[old_index + 1 :] - new_array = jnp.reshape(array.array, [ax.size for ax in new_axes]) - return NamedArray(new_array, new_axes) + resolved_new_axes = array.axes[:old_index] + tuple(new_axes) + array.axes[old_index + 1 :] + new_array = jnp.reshape(array.array, [ax.size for ax in resolved_new_axes]) + return NamedArray(new_array, resolved_new_axes) -def named(a: jnp.ndarray, axis: AxisSpec) -> NamedArray: +def named(a: jnp.ndarray, axis: AxisSelection) -> NamedArray: """Creates a NamedArray from a numpy array and a list of axes""" - if isinstance(axis, Axis): - if a.shape != (axis.size,): - raise ValueError(f"Shape of array {jnp.shape(a)} does not match size of axis {axis.size}") - return NamedArray(a, (axis,)) - else: - shape: Tuple[Axis, ...] = ensure_tuple(axis) - # verify the shape is correct - if jnp.shape(a) != tuple(x.size for x in shape): - raise ValueError(f"Shape of array {jnp.shape(a)} does not match shape of axes {axis}") - - return NamedArray(a, shape) + axes = check_shape(a.shape, axis) + return NamedArray(a, axes) def concat_axis_specs(a1: AxisSpec, a2: AxisSpec) -> AxisSpec: @@ -920,6 +999,7 @@ def broadcast_arrays_and_return_axes( return arrays, full_axes +# TODO: convert to AxisSelection? def broadcast_axis(a: NamedArray, axis: AxisSpec) -> NamedArray: """ Broadcasts a, ensuring that it has all the axes in axis. @@ -931,6 +1011,91 @@ def broadcast_axis(a: NamedArray, axis: AxisSpec) -> NamedArray: return broadcast_to(a, axis, enforce_no_extra_axes=False, ensure_order=True) +def check_shape(jnp_shape: Sequence[int], hax_axes: AxisSelection) -> Tuple[Axis, ...]: + """Check that the shape of a jax array matches the axes of a NamedArray""" + axes: Tuple[AxisSelector, ...] = ensure_tuple(hax_axes) + if len(jnp_shape) != len(axes): + raise ValueError(f"Shape mismatch: jnp_shape={jnp_shape} hax_axes={hax_axes}") + result_axes: List[haliax.Axis] = [] + for i in range(len(axes)): + ax = axes[i] + if isinstance(ax, Axis): + if ax.size != jnp_shape[i]: + raise ValueError(f"Shape mismatch: jnp_shape={jnp_shape} hax_axes={hax_axes}") + result_axes.append(ax) # type: ignore + elif isinstance(ax, str): + result_axes.append(Axis(ax, jnp_shape[i])) + else: + raise ValueError(f"Invalid axis spec: {ax}") + + return tuple(result_axes) + + +class _Sentinel: + ... + + +def is_axis_compatible(ax1: AxisSelector, ax2: AxisSelector): + if isinstance(ax1, str): + if isinstance(ax2, str): + return ax1 == ax2 + return ax1 == ax2.name + if isinstance(ax2, str): + return ax1.name == ax2 + return ax1.name == ax2.name + + +def selects_axis(selector: AxisSelection, selected: AxisSelection) -> bool: + """Returns true if the selector has every axis in selected and, if dims are given, that they match""" + if isinstance(selector, Axis) or isinstance(selector, str): + selected = ensure_tuple(selected) + try: + index = index_where(lambda ax: is_axis_compatible(ax, selector), selected) # type: ignore + return index >= 0 + except ValueError: + return False + + selector_dict = _spec_to_dict(selector) + + selected_tuple = ensure_tuple(selected) # type: ignore + for ax in selected_tuple: + if isinstance(ax, Axis): + selector_size = selector_dict.get(ax.name, _Sentinel) + if selector_size is not None and selector_size != ax.size: + return False + elif isinstance(ax, str): + if ax not in selector_dict: + return False + else: + raise ValueError(f"Invalid axis spec: {ax}") + + return True + + +@overload +def _spec_to_dict(axis_spec: AxisSpec) -> Mapping[str, int]: + ... + + +@overload +def _spec_to_dict(axis_spec: AxisSelection) -> Mapping[str, Optional[int]]: + ... + + +def _spec_to_dict(axis_spec: AxisSelection) -> Mapping[str, Optional[int]]: + spec = ensure_tuple(axis_spec) # type: ignore + shape_dict: Dict[str, Optional[int]] = {} + for ax in spec: + if isinstance(ax, Axis): + shape_dict[ax.name] = ax.size + elif isinstance(ax, str): + shape_dict[ax] = None + else: + raise ValueError(f"Invalid axis spec: {ax}") + + return shape_dict + + __all__ = [ "NamedArray", "concat_axis_specs", @@ -950,4 +1115,5 @@ __all__ = [ "broadcast_arrays", "enable_shape_checks", "are_shape_checks_enabled", + "check_shape", ] diff --git a/src/haliax/hof.py b/src/haliax/hof.py index 7b29581..496618c 100644 --- a/src/haliax/hof.py +++ b/src/haliax/hof.py @@ -9,11 +9,11 @@ import jax.lax as lax from equinox.custom_types import BoolAxisSpec from jaxtyping import PyTree -from .core import NamedArray +from .core import NamedArray, selects_axis from .jax_utils import broadcast_prefix, combine, is_jax_array_like from .partitioning import physical_axis_name -from .types import Axis -from .util import is_jax_or_hax_array_like, is_named_array +from .types import Axis, AxisSelector +from .util import index_where, is_jax_or_hax_array_like, is_named_array Carry = TypeVar("Carry") @@ -23,7 +23,7 @@ Y = TypeVar("Y") def scan( f: Callable[[Carry, X], Tuple[Carry, Y]], - axis: Axis, + axis: AxisSelector, *, reverse=False, unroll=1, @@ -48,7 +48,7 @@ def scan( def is_scanned_with_axis(leaf): if is_named_array(leaf): - return axis in leaf.axes and is_scanned(leaf) + return selects_axis(leaf.axes, axis) and is_scanned(leaf) else: return is_scanned(leaf) @@ -85,7 +85,8 @@ def scan( leaves = jax.tree_util.tree_leaves(axis_first_xs) carry, ys = lax.scan(wrapped_fn, init, leaves, reverse=reverse, unroll=unroll) - ys = jax.tree_util.tree_map(_prepend_named_batch_axis(axis), ys, is_leaf=_is_passive_array) + true_axis = _infer_axis_size_from_result(ys, axis) + ys = jax.tree_util.tree_map(_prepend_named_batch_axis(true_axis), ys, is_leaf=_is_passive_array) return carry, ys @@ -94,7 +95,7 @@ def scan( def fold( fn: Callable[[Carry, X], Carry], - axis: Axis, + axis: AxisSelector, *, reverse: bool = False, unroll: int = 1, @@ -136,7 +137,7 @@ def _zero_if_array_else_none(x: Any) -> ResolvedUnnamedAxisSpec: def vmap( fn, - axis: Axis, + axis: AxisSelector, *, default: PyTree[UnnamedAxisSpec] = _zero_if_array_else_none, args: PyTree[UnnamedAxisSpec] = (), @@ -243,16 +244,38 @@ def vmap( wrapped_fn, in_axes=(arg_axis_specs, kwarg_axis_specs), out_axes=0, - axis_size=axis.size, + axis_size=axis.size if isinstance(axis, Axis) else None, spmd_axis_name=spmd_axis_name, )(args, kwargs) - result = jax.tree_util.tree_map(_prepend_named_batch_axis(axis), result, is_leaf=_is_passive_array) + # if we were passed in a string arg, we need to get its axis size out from some result + true_axis = _infer_axis_size_from_result(result, axis) + if true_axis is None: + raise ValueError("vmap failed to infer axis size from result") + + result = jax.tree_util.tree_map(_prepend_named_batch_axis(true_axis), result, is_leaf=_is_passive_array) return result return wrapped_vmap_fn +def _infer_axis_size_from_result(result, axis): + if isinstance(axis, str): + result_leaves = jax.tree_util.tree_leaves(result, is_leaf=_is_passive_array) + if len(result_leaves) == 0: + # this really shouldn't happen + return None + if isinstance(result_leaves[0], _PassiveNamedArray): + true_axis_size = result_leaves[0].array.shape[0] # batch axis is defined to be 0 above + true_axis = Axis(axis, true_axis_size) + else: + true_axis_size = result_leaves[0].shape[0] # batch axis is defined to be 0 above + true_axis = Axis(axis, true_axis_size) + else: + true_axis = axis + return true_axis + + @jax.tree_util.register_pytree_node_class @dataclasses.dataclass(frozen=True) class _PassiveNamedArray: @@ -271,8 +294,11 @@ class _PassiveNamedArray: def as_scanned_result(self, scan_axis: Axis): return NamedArray(self.array, (scan_axis,) + self.main_axes) - def strip_axis(self, axis: Axis): - index = self.main_axes.index(axis) + def strip_axis(self, axis: AxisSelector): + if isinstance(axis, Axis): + index = self.main_axes.index(axis) + else: + index = index_where(lambda a: a.name == axis, self.main_axes) return NamedArray(self.array, self.main_axes[:index] + self.main_axes[index + 1 :]) def to_named_array(self): @@ -291,7 +317,7 @@ def _is_passive_array(arr): return isinstance(arr, _PassiveNamedArray) -def _prepend_named_batch_axis(leading_axis): +def _prepend_named_batch_axis(leading_axis: Axis): def to_active_named_array(leaf): if isinstance(leaf, _PassiveNamedArray): return leaf.as_scanned_result(leading_axis) @@ -301,10 +327,10 @@ def _prepend_named_batch_axis(leading_axis): return to_active_named_array -def _to_unbatched_named_array(axis_to_strip: Axis): +def _to_unbatched_named_array(axis_to_strip: AxisSelector): def to_unbatched_named_array(leaf): if isinstance(leaf, _PassiveNamedArray): - if axis_to_strip in leaf.main_axes: + if selects_axis(leaf.main_axes, axis_to_strip): return leaf.strip_axis(axis_to_strip) else: return leaf.to_named_array() diff --git a/src/haliax/nn/attention.py b/src/haliax/nn/attention.py index 868c52d..c1711e6 100644 --- a/src/haliax/nn/attention.py +++ b/src/haliax/nn/attention.py @@ -9,7 +9,7 @@ from jax.random import PRNGKey import haliax import haliax.random as hrandom from haliax.core import NamedArray -from haliax.types import Axis, AxisSpec, PrecisionLike +from haliax.types import Axis, AxisSelection, AxisSpec, PrecisionLike # With attention we usually distinguish between the mask and the bias, though the former is just a special case of the @@ -24,7 +24,7 @@ from haliax.types import Axis, AxisSpec, PrecisionLike def dot_product_attention_weights( Head: Axis, - KSeqLen: AxisSpec, + KSeqLen: AxisSelection, query: NamedArray, key: NamedArray, mask: Optional[NamedArray] = None, @@ -50,7 +50,7 @@ def dot_product_attention_weights( import haliax.nn as hnn orig_dtype = query.dtype - query = query / jnp.sqrt(Head.size) + query = query / jnp.sqrt(query.axis_size(Head)) if attention_dtype is not None: query = query.astype(attention_dtype) diff --git a/src/haliax/ops.py b/src/haliax/ops.py index 4f21a94..7b8e160 100644 --- a/src/haliax/ops.py +++ b/src/haliax/ops.py @@ -4,10 +4,10 @@ import jax import jax.numpy as jnp from .core import NamedArray, NamedOrNumeric, broadcast_arrays, broadcast_arrays_and_return_axes -from .types import Axis +from .types import Axis, AxisSelector -def trace(array: NamedArray, axis1: Axis, axis2: Axis, offset=0, dtype=None) -> NamedArray: +def trace(array: NamedArray, axis1: AxisSelector, axis2: AxisSelector, offset=0, dtype=None) -> NamedArray: """Compute the trace of an array along two named axes.""" a1_index = array._lookup_indices(axis1) a2_index = array._lookup_indices(axis2) diff --git a/src/haliax/partitioning.py b/src/haliax/partitioning.py index b8b3c42..08653a4 100644 --- a/src/haliax/partitioning.py +++ b/src/haliax/partitioning.py @@ -16,7 +16,7 @@ from jaxtyping import PyTree from .core import NamedArray from .jax_utils import filter_eval_shape, is_jax_array_like -from .types import Axis, AxisSpec +from .types import Axis, AxisSelection, AxisSelector from .util import StringHolderEnum, ensure_tuple, is_named_array @@ -289,16 +289,18 @@ def _cached_filter_eval_shape(fun, *args, **kwargs): return _eval_shape_cache[static] -def physical_axis_name(axis: Axis, mapping: Optional[ResourceMapping] = None) -> Optional[PhysicalAxis]: +def physical_axis_name(axis: AxisSelector, mapping: Optional[ResourceMapping] = None) -> Optional[PhysicalAxisSpec]: """Get the physical axis name for a logical axis from the mapping. Returns none if the axis is not mapped.""" mapping = mapping or _mapping_holder.thread_data.resource_mapping if mapping is None: return None + elif isinstance(axis, str): + return mapping.get(axis, None) else: - return mapping.get(axis.name, None) # type: ignore + return mapping.get(axis.name, None) -def physical_axis_size(axis: Axis, mapping: Optional[ResourceMapping] = None) -> Optional[int]: +def physical_axis_size(axis: AxisSelector, mapping: Optional[ResourceMapping] = None) -> Optional[int]: """Get the physical axis size for a logical axis. This is the product of the size of all physical axes that this logical axis is mapped to.""" # TODO: shouldn't be accessing this internal api, but... @@ -318,7 +320,7 @@ def physical_axis_size(axis: Axis, mapping: Optional[ResourceMapping] = None) -> return prod([mesh_shape[n] for n in name]) -def pspec_for_axis(axis: AxisSpec, mapping: Optional[ResourceMapping] = None) -> PartitionSpec: +def pspec_for_axis(axis: AxisSelection, mapping: Optional[ResourceMapping] = None) -> PartitionSpec: """Get the PartitionSpec for a single axis""" axis = ensure_tuple(axis) return PartitionSpec(*(physical_axis_name(a, mapping) for a in axis)) diff --git a/src/haliax/random.py b/src/haliax/random.py index acf148f..c93aaa2 100644 --- a/src/haliax/random.py +++ b/src/haliax/random.py @@ -8,12 +8,12 @@ import jax.numpy as jnp import jax.random as jrandom import haliax -from haliax.core import NamedArray, NamedOrNumeric, broadcast_to +from haliax.core import NamedArray, NamedOrNumeric, broadcast_to, selects_axis from haliax.util import ensure_tuple from .jax_utils import named_call from .partitioning import auto_sharded, physical_axis_name, physical_axis_size, pspec_for_axis -from .types import Axis, AxisSpec +from .types import Axis, AxisSelector, AxisSpec @named_call @@ -129,7 +129,7 @@ _enforce_sharded_generate = False """ mostly for testing: enforces shard generation for all random functions even if not running distributed""" -def generate_sharded(fn, axis: Optional[Axis] = None): +def generate_sharded(fn, axis: Optional[AxisSelector] = None): """ Create a wrapped version of fn (which should be a random generator) that generates the random array in a sharded manner, using vmap over the provided axis, or inferring the "best" one if not provided. @@ -205,7 +205,9 @@ def ball(key, shape: AxisSpec, D: Axis, p: float = 2.0, dtype=jnp.float_): @named_call -def choice(key, shape: AxisSpec, a: NamedArray, axis: Axis, replace: bool = True, p: Optional[NamedArray] = None): +def choice( + key, shape: AxisSpec, a: NamedArray, axis: AxisSelector, replace: bool = True, p: Optional[NamedArray] = None +): """ Selects random elements from an array along the given axis. If p is provided, the elements are selected with probability proportional to their weights and it must be a 1-d array with its only axis being the axis. @@ -219,7 +221,7 @@ def choice(key, shape: AxisSpec, a: NamedArray, axis: Axis, replace: bool = True shape = ensure_tuple(shape) if p is not None: - assert p.axes == (axis,), f"p must have axis {axis} or be None" + assert p.resolve_axes(axis) == p.axes, f"p must be 1D with axis {axis} or be None" jax_shape = _to_jax_shape(shape) jax_p = p.array if p is not None else None @@ -232,7 +234,7 @@ def choice(key, shape: AxisSpec, a: NamedArray, axis: Axis, replace: bool = True @named_call -def categorical(key, shape: AxisSpec, logits: NamedArray, axis: Axis): +def categorical(key, shape: AxisSpec, logits: NamedArray, axis: AxisSelector): """Sample random values from categorical distributions. Args: @@ -248,7 +250,7 @@ def categorical(key, shape: AxisSpec, logits: NamedArray, axis: Axis): shape = ensure_tuple(shape) # TODO: could alias the axis and rename at end - if axis in shape: + if selects_axis(shape, axis): raise ValueError(f"axis {axis} cannot be in shape {shape}") logits = logits.broadcast_axis(shape) @@ -271,7 +273,7 @@ def gumbel(key, shape: AxisSpec, dtype=jnp.float_): @named_call -def permutation(key, x: NamedArray, axis: Axis, independent: bool = False): +def permutation(key, x: NamedArray, axis: AxisSelector, independent: bool = False): axis_index = x._lookup_indices(axis) jax_array = jrandom.permutation(key, x.array, axis_index, independent=independent) return auto_sharded(NamedArray(jax_array, x.axes)) diff --git a/src/haliax/types.py b/src/haliax/types.py index 4eb6e1b..89c973c 100644 --- a/src/haliax/types.py +++ b/src/haliax/types.py @@ -6,6 +6,8 @@ from jax.lax import Precision @dataclass(frozen=True) class Axis: + """Axis is a dataclass that represents an axis of an NamedArray. It has a name and a size.""" + name: str size: int @@ -13,7 +15,14 @@ class Axis: return Axis(new_name, self.size) +AxisSelector = Union[Axis, str] +"""AxisSelector is a type that can be used to select a single axis from an array. str or Axis""" +AxisSelection = Union[AxisSelector, Sequence[AxisSelector]] +"""AxisSelection is a type that can be used to select multiple axes from an array. str, Axis, or sequence of mixed +str and Axis""" AxisSpec = Union[Axis, Sequence[Axis]] +"""AxisSpec is a type that can be used to specify the axes of an array, usually for creation or adding a new axis + whose size can't be determined another way. Axis or sequence of Axis""" Scalar = Union[float, int] PrecisionLike = Union[None, str, Precision, Tuple[str, str], Tuple[Precision, Precision]] diff --git a/src/haliax/util.py b/src/haliax/util.py index dfc7d21..ce0f180 100644 --- a/src/haliax/util.py +++ b/src/haliax/util.py @@ -1,4 +1,4 @@ -from typing import Sequence, Tuple, TypeVar, Union +from typing import Callable, Sequence, Tuple, TypeVar, Union from haliax.jax_utils import is_jax_array_like @@ -14,7 +14,9 @@ def is_named_array(leaf): def ensure_tuple(x: Union[Sequence[T], T]) -> Tuple[T, ...]: - if isinstance(x, Sequence): + if isinstance(x, str): + return (x,) # type: ignore + elif isinstance(x, Sequence): return tuple(x) return (x,) @@ -38,3 +40,10 @@ class StringHolderEnum(type): def is_jax_or_hax_array_like(x): return is_jax_array_like(x) or is_named_array(x) + + +def index_where(pred: Callable[[T], bool], xs: Sequence[T]) -> int: + for i, x in enumerate(xs): + if pred(x): + return i + raise ValueError("No element satisfies predicate") diff --git a/src/haliax/wrap.py b/src/haliax/wrap.py index 39fa2ab..746f6ab 100644 --- a/src/haliax/wrap.py +++ b/src/haliax/wrap.py @@ -4,10 +4,10 @@ from typing import Optional import jax import jax.numpy as jnp -from haliax.core import NamedArray, _broadcast_order, broadcast_to +from haliax.core import NamedArray, _broadcast_order, broadcast_to, selects_axis from haliax.util import ensure_tuple -from .types import AxisSpec +from .types import AxisSelection def wrap_elemwise_unary(f): @@ -25,7 +25,7 @@ def wrap_elemwise_unary(f): def wrap_reduction_call(fn, single_axis_only: bool = False, supports_where: bool = True): @functools.wraps(fn) - def wrapper(a, axis: Optional[AxisSpec] = None, where: NamedArray = None, **kwargs): + def wrapper(a, axis: Optional[AxisSelection] = None, where: NamedArray = None, **kwargs): kwargs = dict(kwargs) if where is not None and not supports_where: raise ValueError(f"where is not supported by {fn.__name__}") @@ -57,7 +57,7 @@ def wrap_reduction_call(fn, single_axis_only: bool = False, supports_where: bool indices = a._lookup_indices(axis) if indices is None or any(x is None for x in indices): raise ValueError(f"axis {axis} is not in {a.axes}") - new_axes = [ax for ax in a.axes if ax not in axis] + new_axes = [ax for ax in a.axes if not selects_axis(axis, ax)] if single_axis_only: result = fn(a.array, axis=indices[0], **kwargs) else: @@ -86,7 +86,7 @@ def wrap_reduction_call(fn, single_axis_only: bool = False, supports_where: bool def wrap_axiswise_call(fn, single_axis_only: bool): @functools.wraps(fn) - def wrapper(a, axis: Optional[AxisSpec] = None, **kwargs): + def wrapper(a, axis: Optional[AxisSelection] = None, **kwargs): if isinstance(a, NamedArray): if axis is None: return NamedArray(fn(a.array, axis=None, **kwargs), a.axes) diff --git a/tests/core_test.py b/tests/core_test.py index 280c2f7..fc36077 100644 --- a/tests/core_test.py +++ b/tests/core_test.py @@ -30,6 +30,29 @@ def test_dot(): ) +def test_dot_string_selection(): + Height = Axis("Height", 2) + Width = Axis("Width", 3) + Depth = Axis("Depth", 4) + + m1 = NamedArray(jnp.ones((Height.size, Width.size, Depth.size)), (Height, Width, Depth)) + m2 = NamedArray(jnp.ones((Depth.size, Width.size, Height.size)), (Depth, Width, Height)) + + assert jnp.all(jnp.equal(hax.dot("Height", m1, m2).array, jnp.einsum("ijk,kji->jk", m1.array, m2.array))) + assert jnp.all( + jnp.equal( + hax.dot(("Height", "Width"), m1, m2).array, + jnp.einsum("ijk,kji->k", m1.array, m2.array), + ) + ) + assert jnp.all( + jnp.equal( + hax.dot(("Height", "Width", "Depth"), m1, m2).array, + jnp.einsum("ijk,kji->", m1.array, m2.array), + ) + ) + + def test_unary_np_functions(): Height = Axis("Height", 2) Width = Axis("Width", 3) @@ -91,13 +114,13 @@ def test_reduction_functions(): def test_reduction_functions_with_where(): - Height = Axis("Height", 2) - Width = Axis("Width", 3) - Depth = Axis("Depth", 4) + H = Axis("H", 2) + W = Axis("W", 3) + D = Axis("D", 4) - rand_m = jax.random.uniform(PRNGKey(0), (Height.size, Width.size, Depth.size)) + rand_m = jax.random.uniform(PRNGKey(0), (H.size, W.size, D.size)) - m1 = NamedArray(rand_m, (Height, Width, Depth)) + m1 = NamedArray(rand_m, (H, W, D)) mask = m1 > 0.5 jmask = m1.array > 0.5 @@ -106,34 +129,38 @@ def test_reduction_functions_with_where(): assert jnp.all(jnp.equal(hax.sum(m1, where=mask).array, jnp.sum(rand_m, where=jmask))) # ensure it's a scalar - assert jnp.all(jnp.equal(hax.sum(m1, axis=Height, where=mask).array, jnp.sum(rand_m, axis=0, where=jmask))) - assert jnp.all(jnp.equal(hax.sum(m1, axis=Width, where=mask).array, jnp.sum(rand_m, axis=1, where=jmask))) + assert jnp.all(jnp.equal(hax.sum(m1, axis=H, where=mask).array, jnp.sum(rand_m, axis=0, where=jmask))) + assert jnp.all(jnp.equal(hax.sum(m1, axis=W, where=mask).array, jnp.sum(rand_m, axis=1, where=jmask))) + + assert jnp.all(jnp.equal(hax.sum(m1, axis="H", where=mask).array, jnp.sum(rand_m, axis=0, where=jmask))) # sum out two axes + assert jnp.all(jnp.equal(hax.sum(m1, axis=(H, W), where=mask).array, jnp.sum(rand_m, axis=(0, 1), where=jmask))) + assert jnp.all(jnp.equal(hax.sum(m1, axis=(W, H), where=mask).array, jnp.sum(rand_m, axis=(1, 0), where=jmask))) + assert jnp.all(jnp.equal(hax.sum(m1, axis=(H, D), where=mask).array, jnp.sum(rand_m, axis=(0, 2), where=jmask))) + assert jnp.all( - jnp.equal(hax.sum(m1, axis=(Height, Width), where=mask).array, jnp.sum(rand_m, axis=(0, 1), where=jmask)) - ) - assert jnp.all( - jnp.equal(hax.sum(m1, axis=(Width, Height), where=mask).array, jnp.sum(rand_m, axis=(1, 0), where=jmask)) - ) - assert jnp.all( - jnp.equal(hax.sum(m1, axis=(Height, Depth), where=mask).array, jnp.sum(rand_m, axis=(0, 2), where=jmask)) + jnp.equal(hax.sum(m1, axis=("H", "W"), where=mask).array, jnp.sum(rand_m, axis=(0, 1), where=jmask)) ) # sum out three axes assert jnp.all( jnp.equal( - hax.sum(m1, axis=(Height, Width, Depth), where=mask).array, + hax.sum(m1, axis=(H, W, D), where=mask).array, jnp.sum(rand_m, axis=(0, 1, 2), where=jmask), ) ) assert jnp.all( jnp.equal( - hax.sum(m1, axis=(Width, Height, Depth), where=mask).array, + hax.sum(m1, axis=(W, H, D), where=mask).array, jnp.sum(rand_m, axis=(1, 0, 2), where=jmask), ) ) + assert jnp.all( + jnp.equal(hax.sum(m1, axis=("H", "W", "D"), where=mask).array, jnp.sum(rand_m, axis=(0, 1, 2), where=jmask)) + ) + def test_split(): Height = Axis("Height", 2) @@ -155,6 +182,11 @@ def test_split(): for i in range(10): assert jnp.all(jnp.equal(splits[i].array, usplits[i])) + # double check string axis + splits_str = hax.split(rand_m, axis="Depth", new_axes=[Depth] * 10) + for i in range(10): + assert jnp.all(jnp.equal(splits_str[i].array, usplits[i])) + def test_take(): Height = Axis("Height", 2) @@ -170,7 +202,7 @@ def test_take(): named2 = hax.take(named1, Height, indices) assert named2.axes == (Index, Width, Depth) - named2 = hax.take(named1, Width, indices) + named2 = hax.take(named1, "Width", indices) assert named2.axes == (Height, Index, Depth) named2 = hax.take(named1, Depth, indices) @@ -183,7 +215,7 @@ def test_take(): named2 = hax.take(named1, Height, indices2) assert named2.axes == (Index, Index2, Width, Depth) - named2 = hax.take(named1, Width, indices2) + named2 = hax.take(named1, "Width", indices2) assert named2.axes == (Height, Index, Index2, Depth) named2 = hax.take(named1, Depth, indices2) @@ -223,16 +255,24 @@ def test_cumsum_etc(): def test_rearrange(): - H = Axis("Height", 2) - W = Axis("Width", 3) - D = Axis("Depth", 4) - C = Axis("Channel", 5) + H = Axis("H", 2) + W = Axis("W", 3) + D = Axis("D", 4) + C = Axis("C", 5) named1 = hax.random.uniform(PRNGKey(0), (H, W, D, C)) assert jnp.all(jnp.equal(hax.rearrange(named1, (C, W, D, H)).array, jnp.transpose(named1.array, (3, 1, 2, 0)))) assert hax.rearrange(named1, (C, W, D, H)).axes == (C, W, D, H) + # test str args + assert jnp.all( + jnp.equal(hax.rearrange(named1, ("C", "W", "D", "H")).array, jnp.transpose(named1.array, (3, 1, 2, 0))) + ) + assert hax.rearrange(named1, ("C", "W", "D", "H")).axes == (C, W, D, H) + # test mixed str and Axis args + assert jnp.all(jnp.equal(hax.rearrange(named1, ("C", W, "D", H)).array, jnp.transpose(named1.array, (3, 1, 2, 0)))) + # test ellipsis assert jnp.all(jnp.equal(hax.rearrange(named1, (C, ..., D)).array, jnp.transpose(named1.array, (3, 0, 1, 2)))) @@ -286,19 +326,40 @@ def test_arange(): def test_stack(): - B = Axis("Batch", 2) - H = Axis("Height", 4) - W = Axis("Width", 3) + H = Axis("H", 4) + W = Axis("W", 3) named1 = hax.random.uniform(PRNGKey(0), (H, W)) named2 = hax.random.uniform(PRNGKey(1), (H, W)) - assert jnp.all(jnp.equal(hax.stack(B, (named1, named2)).array, jnp.stack((named1.array, named2.array), axis=0))) + assert jnp.all(jnp.equal(hax.stack("B", (named1, named2)).array, jnp.stack((named1.array, named2.array), axis=0))) named3 = hax.random.uniform(PRNGKey(2), (W, H)) # test that this rearranges fine - assert jnp.all( - jnp.equal( - hax.stack(B, (named1, named3)).array, jnp.stack((named1.array, named3.array.transpose(1, 0)), axis=0) - ) - ) + reord_stack = hax.stack("B", (named1, named3)) + assert jnp.all(jnp.equal(reord_stack.array, jnp.stack((named1.array, named3.array.transpose(1, 0)), axis=0))) + assert reord_stack.axes == (Axis("B", 2), H, W) + + +def test_unflatten_axis(): + H = Axis("Height", 2) + W = Axis("Width", 3) + D = Axis("Depth", 4) + + named1 = hax.random.uniform(PRNGKey(0), (H, W, D)) + flattened_HW = named1.flatten_axes((H, W), "Z") + + assert jnp.all(jnp.equal(hax.unflatten_axis(flattened_HW, "Z", (H, W)).array, named1.array)) + assert hax.unflatten_axis(flattened_HW, "Z", (H, W)).axes == (H, W, D) + + assert jnp.all(jnp.equal(hax.unflatten_axis(flattened_HW, "Z", (H, W)).array, named1.array)) + + # test that we can unflatten to a different order + # in general, this won't be equivalent to the original array + assert not jnp.all(jnp.equal(hax.unflatten_axis(flattened_HW, "Z", (W, H)).array, named1.array.transpose(1, 0, 2))) + assert hax.unflatten_axis(flattened_HW, "Z", (W, H)).axes == (W, H, D) + + # flatten non-consecutive axes + flattened_HD = named1.flatten_axes((H, D), "Z") + assert jnp.all(jnp.equal(hax.unflatten_axis(flattened_HD, "Z", (H, D)).array, named1.array.transpose(0, 2, 1))) + assert hax.unflatten_axis(flattened_HD, "Z", (H, D)).axes == (H, D, W) diff --git a/tests/test_hof.py b/tests/test_hof.py index 590eee7..9d11a1d 100644 --- a/tests/test_hof.py +++ b/tests/test_hof.py @@ -20,6 +20,11 @@ def test_scan(): assert jnp.all(jnp.isclose(total, jnp.sum(named1.array, axis=(0, 1, 2)))) assert jnp.all(jnp.equal(selected.array, named1.take(Width, 2).array)) + total, selected = hax.scan(scan_fun, "Height")(0.0, named1) + + assert jnp.all(jnp.isclose(total, jnp.sum(named1.array, axis=(0, 1, 2)))) + assert jnp.all(jnp.equal(selected.array, named1.take("Width", 2).array)) + def test_scan_not_0th_axis(): Height = Axis("Height", 10) @@ -36,6 +41,21 @@ def test_scan_not_0th_axis(): assert jnp.all(jnp.equal(selected.array, named1.take(Width, 2).rearrange(selected.axes).array)) +def test_scan_str_arg(): + Height = Axis("Height", 10) + Width = Axis("Width", 3) + Depth = Axis("Depth", 4) + named1 = hax.random.uniform(PRNGKey(0), (Height, Width, Depth)) + + def scan_fun(acc, x): + return acc + jnp.sum(x.array), x.take("Width", 2) + + total, selected = hax.scan(scan_fun, "Height")(0.0, named1) + + assert jnp.all(jnp.isclose(total, jnp.sum(named1.array, axis=(0, 1, 2)))) + assert jnp.all(jnp.equal(selected.array, named1.take(Width, 2).array)) + + def test_scan_static_args(): Height = Axis("Height", 10) Width = Axis("Width", 3) @@ -66,6 +86,19 @@ def test_reduce(): assert jnp.all(jnp.isclose(total.rearrange(acc.axes).array, jnp.sum(named1.array, axis=2))) +def test_reduce_str_args(): + Height = Axis("Height", 10) + Width = Axis("Width", 3) + Depth = Axis("Depth", 4) + named1 = hax.random.uniform(PRNGKey(0), (Height, Width, Depth)) + + acc = hax.zeros((Height, Width)) + + total = hax.fold(lambda x, y: x + y, "Depth")(acc, named1) + + assert jnp.all(jnp.isclose(total.rearrange(acc.axes).array, jnp.sum(named1.array, axis=2))) + + def test_reduce_static_args(): Height = Axis("Height", 10) Width = Axis("Width", 3) @@ -120,6 +153,32 @@ def test_vmap_mapped_args(): assert selected.axes == expected_names +def test_vmap_str_args(): + Batch = Axis("Batch", 10) + Width = Axis("Width", 3) + Depth = Axis("Depth", 4) + named1 = hax.random.uniform(PRNGKey(0), (Batch, Width, Depth)) + + def vmap_fun(x): + return x.sum(Width) + + selected = hax.vmap(vmap_fun, "Batch")(named1) + + expected_jax = jnp.array([named1.sum(Width).array for _ in range(Batch.size)]) + expected_names = (Batch, Depth) + + assert jnp.all(jnp.equal(selected.array, expected_jax)) + assert selected.axes == expected_names + + # also ensure that this works when we return a non-haliax array + def vmap_fun(x): + return x.sum(Width).array + + selected = hax.vmap(vmap_fun, "Batch")(named1) + + assert jnp.all(jnp.equal(selected, expected_jax)) + + def test_vmap_mapped_kwarg(): Batch = Axis("Batch", 10) Width = Axis("Width", 3) diff --git a/tests/test_ops.py b/tests/test_ops.py index 2f65a7f..80a7860 100644 --- a/tests/test_ops.py +++ b/tests/test_ops.py @@ -14,12 +14,20 @@ def test_trace(): assert jnp.all(jnp.isclose(trace1.array, jnp.trace(named1.array))) assert len(trace1.axes) == 0 + trace1 = hax.trace(named1, "Width", "Depth") + assert jnp.all(jnp.isclose(trace1.array, jnp.trace(named1.array))) + assert len(trace1.axes) == 0 + Height = Axis("Height", 10) named2 = hax.random.uniform(PRNGKey(0), (Height, Width, Depth)) trace2 = hax.trace(named2, Width, Depth) assert jnp.all(jnp.isclose(trace2.array, jnp.trace(named2.array, axis1=1, axis2=2))) assert trace2.axes == (Height,) + trace2 = hax.trace(named2, "Width", "Depth") + assert jnp.all(jnp.isclose(trace2.array, jnp.trace(named2.array, axis1=1, axis2=2))) + assert trace2.axes == (Height,) + def test_add(): Height = Axis("Height", 10) diff --git a/tests/test_random.py b/tests/test_random.py index 9a2f49d..c077461 100644 --- a/tests/test_random.py +++ b/tests/test_random.py @@ -237,6 +237,12 @@ def test_choice(): lambda k, s: hax.random.choice(k, s, digits, Digit, p=weights), ) + # test str selector + check_gen_is_equal( + lambda k, s: jax.random.choice(k, digits.array, shape=s, p=weights.array), + lambda k, s: hax.random.choice(k, s, digits, "Digit", p=weights), + ) + def test_categorical(): logits = hax.random.uniform( @@ -273,18 +279,27 @@ def test_categorical(): lambda k, s: hax.random.categorical(k, s, logits, Digit), ) + # check str arg for selector + check_gen_is_equal( + lambda k, s: jax.random.categorical(k, raw_logits, shape=s, axis=-1), + lambda k, s: hax.random.categorical(k, s, logits, "Digit"), + ) + def test_permutation(): data = hax.random.uniform(jax.random.PRNGKey(0), (Width, Height)) hax_perm = hax.random.permutation(jax.random.PRNGKey(0), data, Height) jax_perm = jax.random.permutation(jax.random.PRNGKey(0), data.array, 1) - assert jnp.all(hax_perm.array == jax_perm) hax_perm = hax.random.permutation(jax.random.PRNGKey(0), data, Width) jax_perm = jax.random.permutation(jax.random.PRNGKey(0), data.array, 0) + assert jnp.all(hax_perm.array == jax_perm) + # test str arg for selector + hax_perm = hax.random.permutation(jax.random.PRNGKey(0), data, "Height") + jax_perm = jax.random.permutation(jax.random.PRNGKey(0), data.array, 1) assert jnp.all(hax_perm.array == jax_perm) commit 8e5204e73971d8ff9f7822dde66dd6d10b6d8091 Date: 2023-04-29T13:58:32-07:00 Factor out "next_token_loss" and use it everywhere (#129) diff --git a/src/haliax/__init__.py b/src/haliax/__init__.py index aedcfba..65e89b7 100644 --- a/src/haliax/__init__.py +++ b/src/haliax/__init__.py @@ -1,4 +1,4 @@ -from typing import Sequence +from typing import Optional, Protocol, Sequence import jax import jax.numpy as jnp @@ -153,21 +153,36 @@ tanh = wrap_elemwise_unary(jnp.tanh) trunc = wrap_elemwise_unary(jnp.trunc) # Reduction functions -all = wrap_reduction_call(jnp.all) -amax = wrap_reduction_call(jnp.amax) -any = wrap_reduction_call(jnp.any) -argmax = wrap_reduction_call(jnp.argmax, single_axis_only=True, supports_where=False) -argmin = wrap_reduction_call(jnp.argmin, single_axis_only=True, supports_where=False) -max = wrap_reduction_call(jnp.max) -mean = wrap_reduction_call(jnp.mean) -min = wrap_reduction_call(jnp.min) -prod = wrap_reduction_call(jnp.prod) -ptp = wrap_reduction_call(jnp.ptp) -product = wrap_reduction_call(jnp.product) -sometrue = wrap_reduction_call(jnp.sometrue) -std = wrap_reduction_call(jnp.std) -sum = wrap_reduction_call(jnp.sum) -var = wrap_reduction_call(jnp.var) + + +class ReductionFunction(Protocol): + def __call__( + self, array: NamedArray, axis: Optional[AxisSelection] = None, where: Optional[NamedArray] = None, **kwargs + ) -> NamedArray: + ... + + +class SimpleReductionFunction(Protocol): + def __call__(self, array: NamedArray, axis: Optional[AxisSelector] = None, **kwargs) -> NamedArray: + ... + + +all: ReductionFunction = wrap_reduction_call(jnp.all) +amax: ReductionFunction = wrap_reduction_call(jnp.amax) +any: ReductionFunction = wrap_reduction_call(jnp.any) +argmax: SimpleReductionFunction = wrap_reduction_call(jnp.argmax, single_axis_only=True, supports_where=False) +argmin: SimpleReductionFunction = wrap_reduction_call(jnp.argmin, single_axis_only=True, supports_where=False) +max: ReductionFunction = wrap_reduction_call(jnp.max) +mean: ReductionFunction = wrap_reduction_call(jnp.mean) +min: ReductionFunction = wrap_reduction_call(jnp.min) +prod: ReductionFunction = wrap_reduction_call(jnp.prod) +ptp: ReductionFunction = wrap_reduction_call(jnp.ptp) +product: ReductionFunction = wrap_reduction_call(jnp.product) +sometrue: ReductionFunction = wrap_reduction_call(jnp.sometrue) +std: ReductionFunction = wrap_reduction_call(jnp.std) +sum: ReductionFunction = wrap_reduction_call(jnp.sum) +var: ReductionFunction = wrap_reduction_call(jnp.var) + # "Normalization" functions that use an axis but don't change the shape cumsum = wrap_axiswise_call(jnp.cumsum, True) diff --git a/src/haliax/core.py b/src/haliax/core.py index 3be1b90..3440a72 100644 --- a/src/haliax/core.py +++ b/src/haliax/core.py @@ -75,21 +75,6 @@ class NamedArray: if s != tuple(a.size for a in self.axes): raise ValueError(f"Shape of underlying array {s} does not match shape of axes {self.axes}") - def resolve_axes(self, axes: AxisSelection) -> Tuple[Axis, ...]: - """Returns the axes corresponding to the given axis selection.""" - indices = self._lookup_indices(axes) - if isinstance(indices, int): - return (self.axes[indices],) - elif indices is None: - raise ValueError(f"Axis {axes} not found") - else: - result = [] - for i in indices: - if i is None: - raise ValueError(f"Axis {axes} not found") - result.append(self.axes[i]) - return tuple(result) - def item(self): return self.array.item() @@ -150,6 +135,29 @@ class NamedArray: result.append(self.axes[i].size) return tuple(result) + @overload + def resolve_axis(self, axis: AxisSelector) -> Axis: # type: ignore + ... + + @overload + def resolve_axis(self, axis: Sequence[AxisSelector]) -> Tuple[Axis, ...]: # type: ignore + ... + + def resolve_axis(self, axes: AxisSelection) -> AxisSpec: # type: ignore + """Returns the axes corresponding to the given axis selection.""" + indices = self._lookup_indices(axes) + if isinstance(indices, int): + return self.axes[indices] + elif indices is None: + raise ValueError(f"Axis {axes} not found") + else: + result = [] + for i in indices: + if i is None: + raise ValueError(f"Axis {axes} not found") + result.append(self.axes[i]) + return tuple(result) + @overload def _lookup_indices(self, axis: AxisSelector) -> Optional[int]: # type: ignore ... @@ -177,6 +185,17 @@ class NamedArray: return axis_index except ValueError: return None + elif isinstance(axis, str): + try: + return index_where(lambda a: a.name == axis, self.axes) + except ValueError: + try: + axis_index = index_where(lambda a: a.name == ax_name, self.axes) + if axis_index >= 0: + warnings.warn("Found axis with same name but different size.", UserWarning) + return axis_index + except ValueError: + return None elif isinstance(axis, str): try: return index_where(lambda a: a.name == axis, self.axes) @@ -331,21 +350,8 @@ class NamedArray: def sort(self, axis: AxisSelector, kind="quicksort") -> Any: return haliax.sort(self, axis=axis, kind=kind) - def std( - self, - axis: Optional[AxisSelection] = None, - *, - dtype=None, - ddof=0, - where=None, - ) -> "NamedArray": - return haliax.std( - self, - axis=axis, - dtype=dtype, - ddof=ddof, - where=where, - ) + def std(self, axis: Optional[AxisSelection] = None, *, dtype=None, ddof=0, where=None) -> "NamedArray": + return haliax.std(self, axis=axis, dtype=dtype, ddof=ddof, where=where) def sum( self, @@ -729,7 +735,7 @@ def flatten_axes(array: NamedArray, old_axes: Sequence[AxisSelector], new_axis: if len(old_axes) == 0: raise ValueError("Must specify at least one axis to merge") - old_axes = array.resolve_axes(old_axes) + old_axes = array.resolve_axis(old_axes) if isinstance(new_axis, Axis): if new_axis.size != prod(array.axis_size(ax) for ax in old_axes): diff --git a/src/haliax/nn/__init__.py b/src/haliax/nn/__init__.py index 467df6e..45bc23e 100644 --- a/src/haliax/nn/__init__.py +++ b/src/haliax/nn/__init__.py @@ -9,7 +9,7 @@ import haliax as hax import haliax.nn.attention as attention from ..core import NamedArray -from ..types import Axis, AxisSpec +from ..types import Axis, AxisSelector, AxisSpec from ..wrap import unwrap_namedarrays, wrap_axiswise_call, wrap_elemwise_unary, wrap_reduction_call from .dropout import Dropout from .linear import Linear @@ -80,7 +80,7 @@ def one_hot(x: Union[NamedArray, int], class_axis: Axis, *, dtype=jnp.float_) -> def cross_entropy_loss( pred_y: NamedArray, - Label: Axis, + Label: AxisSelector, target_y: NamedArray, ) -> NamedArray: loss, _ = cross_entropy_loss_and_log_normalizers(pred_y, Label, target_y) @@ -89,7 +89,7 @@ def cross_entropy_loss( def cross_entropy_loss_and_log_normalizers( pred_y: NamedArray, - Label: Axis, + Label: AxisSelector, target_y: NamedArray, ) -> Tuple[NamedArray, NamedArray]: """ diff --git a/src/haliax/random.py b/src/haliax/random.py index c93aaa2..7decb7a 100644 --- a/src/haliax/random.py +++ b/src/haliax/random.py @@ -221,7 +221,7 @@ def choice( shape = ensure_tuple(shape) if p is not None: - assert p.resolve_axes(axis) == p.axes, f"p must be 1D with axis {axis} or be None" + assert p.resolve_axis(ensure_tuple(axis)) == p.axes, f"p must be 1D with axis {axis} or be None" jax_shape = _to_jax_shape(shape) jax_p = p.array if p is not None else None commit 40ae5f856aaa4f7c1c702bc9709169dcfdb40247 Date: 2023-05-01T22:46:01-07:00 missing name diff --git a/src/haliax/core.py b/src/haliax/core.py index 3440a72..db2b57b 100644 --- a/src/haliax/core.py +++ b/src/haliax/core.py @@ -190,7 +190,7 @@ class NamedArray: return index_where(lambda a: a.name == axis, self.axes) except ValueError: try: - axis_index = index_where(lambda a: a.name == ax_name, self.axes) + axis_index = index_where(lambda a: a.name == axis, self.axes) if axis_index >= 0: warnings.warn("Found axis with same name but different size.", UserWarning) return axis_index commit 1c8603c22ef3ea64f1d517a564411eda0e187d74 Date: 2023-05-01T22:47:18-07:00 i'm a dummy diff --git a/src/haliax/core.py b/src/haliax/core.py index db2b57b..dadf685 100644 --- a/src/haliax/core.py +++ b/src/haliax/core.py @@ -189,13 +189,7 @@ class NamedArray: try: return index_where(lambda a: a.name == axis, self.axes) except ValueError: - try: - axis_index = index_where(lambda a: a.name == axis, self.axes) - if axis_index >= 0: - warnings.warn("Found axis with same name but different size.", UserWarning) - return axis_index - except ValueError: - return None + return None elif isinstance(axis, str): try: return index_where(lambda a: a.name == axis, self.axes) commit 22c48b5bcbf8d6e11e8b0b9ddf3611325eff7e01 Date: 2023-05-12T09:54:36-07:00 sharded reading/writing via Ray (#112) partial for #112. fixes #118 diff --git a/requirements.txt b/requirements.txt index c46bcbd..203dc25 100644 --- a/requirements.txt +++ b/requirements.txt @@ -5,7 +5,7 @@ wandb pyrallis pyarrow zstandard -datasets~=2.6.0 +datasets==2.11.0 gcsfs==2023.3.0 braceexpand jmp @ git+https://github.com/deepmind/jmp#7b3ae548154625a56a6dbdb03bc07d4f599c37b2 @@ -16,4 +16,6 @@ humanfriendly requests safetensors[numpy] matplotlib -filelock +tblib +dataclasses_json +ray[default] diff --git a/tests/test_attention.py b/tests/test_attention.py index 62de3cc..db321b9 100644 --- a/tests/test_attention.py +++ b/tests/test_attention.py @@ -1,6 +1,6 @@ import numpy as np from jax.random import PRNGKey -from utils import skip_if_no_torch +from test_utils import skip_if_no_torch import haliax as hax from haliax.nn.attention import alibi_attention_bias, dot_product_attention_weights, forgetful_causal_mask diff --git a/tests/test_partitioning.py b/tests/test_partitioning.py index 6bb6ce2..0cd0c07 100644 --- a/tests/test_partitioning.py +++ b/tests/test_partitioning.py @@ -6,7 +6,7 @@ from jax.interpreters import pxla from jax.interpreters.pxla import PartitionSpec from jax.sharding import SingleDeviceSharding from jaxtyping import Array -from utils import skip_if_not_enough_devices +from test_utils import skip_if_not_enough_devices import haliax as hax from haliax import Axis, NamedArray commit acd2fc3f9f9abd6c1a2039fb25cb8ca3c3006d75 Date: 2023-05-16T23:46:59-07:00 Small fixes to partitioning.py from working on mpt (#146) * allow {} for axis_resources * allow shard_with_axis_mapping outside of pjit * use array_from_callback when necessary for auto_sharded diff --git a/src/haliax/partitioning.py b/src/haliax/partitioning.py index 08653a4..3992cba 100644 --- a/src/haliax/partitioning.py +++ b/src/haliax/partitioning.py @@ -3,11 +3,11 @@ import functools import threading import typing from math import prod -from typing import List, Mapping, Optional, Sequence, TypeVar, Union +from typing import Mapping, Optional, Sequence, TypeVar, Union import equinox as eqx import jax -from equinox import is_array +import jax.numpy as jnp from equinox.compile_utils import compile_cache, get_fun_names, hashable_combine, hashable_partition from jax.experimental.pjit import pjit, with_sharding_constraint from jax.interpreters.pxla import PartitionSpec @@ -85,28 +85,55 @@ def auto_sharded(x: T) -> T: def shard_with_axis_mapping(x: T, mapping: ResourceMapping) -> T: """ Shard a PyTree using the provided axis mapping. NamedArrays in the PyTree are sharded using the axis mapping. - Other arrays are not sharded. + Other arrays are not sharded (unless they're already sharded). + + Inside of a jit context, this method grounds out in calls to `with_sharding_constraint`. Outside of a jit + context, this method grounds out in either device_put or make_array_from_callback, depending on whether the + resulting sharding spans more than one host. :param x: :param mapping: :return: """ - def _as_pspec(x): - if isinstance(x, NamedArray): - physical_names: List[Optional[PhysicalAxisSpec]] = [mapping.get(a.name, None) for a in x.axes] - elif is_array(x): - physical_names = [None] * len(x.shape) - else: - return None + if _is_jit_context(): - spec = PartitionSpec( - *tuple(tuple(p) if not (isinstance(p, str)) and isinstance(p, Sequence) else p for p in physical_names) - ) - return spec + def _shard_leaf(x): + if isinstance(x, NamedArray): + pspec = pspec_for_axis(x.axes, mapping) + return with_sharding_constraint(x, pspec) + else: + return x - pspec = jax.tree_util.tree_map(_as_pspec, x, is_leaf=is_named_array) - return with_sharding_constraint(x, pspec) + return jax.tree_util.tree_map(_shard_leaf, x, is_leaf=is_named_array) + else: + # use device_put or make_array_from_callback instead + mesh = _get_mesh() + + def _do_device_put(x): + if not is_named_array(x): + return x + + pspec = pspec_for_axis(x.axes, mapping) + sharding = jax.sharding.NamedSharding(mesh, pspec) + + raw_x = x.array + current_sharding = raw_x.sharding + + if current_sharding == sharding: + return x + elif sharding.is_fully_addressable: + raw_x = jax.device_put(raw_x, sharding) + return NamedArray(raw_x, x.axes) + else: + # if the sharding is not fully addressable, we can't use device_put, so we use this hacky workaround. + # TODO: we lose "src" information, but i think that's only for autodiff, and this isn't an autodiff + # context, I think? + shape = raw_x.shape + raw_x = jax.make_array_from_callback(shape, sharding, lambda index: raw_x[index]) + return NamedArray(raw_x, x.axes) + + return jax.tree_util.tree_map(_do_device_put, x, is_leaf=is_named_array) def infer_resource_partitions(tree: PyTree, resource_mapping: Optional[ResourceMapping] = None) -> PyTree: @@ -123,12 +150,10 @@ def infer_resource_partitions(tree: PyTree, resource_mapping: Optional[ResourceM if resource_mapping is None: raise ValueError("No resource mapping found") - _resource_mapping = typing.cast(ResourceMapping, resource_mapping) # for mypy - def partition_spec(node: typing.Any): if isinstance(node, NamedArray): return NamedArray( - PartitionSpec(*tuple(_resource_mapping.get(axis.name, None) for axis in node.axes)), # type: ignore + pspec_for_axis(node.axes, resource_mapping), # type: ignore node.axes, ) # elif isinstance(node, GlobalDeviceArray): @@ -186,7 +211,8 @@ def named_pjit( **pjit_args, ) - axis_resources = axis_resources or _mapping_holder.thread_data.resource_mapping + if axis_resources is None: + axis_resources = _mapping_holder.thread_data.resource_mapping if in_axis_resources is None: in_axis_resources = axis_resources @@ -336,6 +362,16 @@ def round_axis_for_partitioning(axis: Axis, mapping: Optional[ResourceMapping] = return Axis(axis.name, new_size) +def _get_mesh(): + from jax.experimental.maps import thread_resources + + return thread_resources.env.physical_mesh + + +def _is_jit_context(): + return isinstance(jnp.zeros(1), jax.core.Tracer) + + __all__ = [ "LogicalAxisName", "PhysicalAxis", diff --git a/tests/test_partitioning.py b/tests/test_partitioning.py index 0cd0c07..9b2d9b5 100644 --- a/tests/test_partitioning.py +++ b/tests/test_partitioning.py @@ -4,7 +4,7 @@ import jax.numpy as jnp import numpy as np from jax.interpreters import pxla from jax.interpreters.pxla import PartitionSpec -from jax.sharding import SingleDeviceSharding +from jax.sharding import Mesh, NamedSharding, SingleDeviceSharding from jaxtyping import Array from test_utils import skip_if_not_enough_devices @@ -127,3 +127,17 @@ def test_infer_resource_partition_gda_bug(): finally: jax.config.update("jax_parallel_functions_output_gda", False) + + +@skip_if_not_enough_devices(4) +def test_shard_with_axis_mapping_outside_pjit(): + devices = jax.devices() + with Mesh(np.array(devices).reshape(-1, 2), (ResourceAxis.DATA, ResourceAxis.MODEL)) as mesh: + x = hax.ones((Dim1, Dim2)) + y = hax.ones((Dim2, Dim3)) + + x = hax.shard_with_axis_mapping(x, resource_map) + assert x.array.sharding == NamedSharding(mesh, PartitionSpec(None, ResourceAxis.DATA)) + + y = hax.shard_with_axis_mapping(y, resource_map) + assert y.array.sharding == NamedSharding(mesh, PartitionSpec(ResourceAxis.DATA, ResourceAxis.MODEL)) commit cf938275aca4693405421b9cfcd45eb9c468146c Date: 2023-05-17T19:46:07-07:00 Logging for Ray preprocessing (#127) diff --git a/requirements.txt b/requirements.txt index 203dc25..1e0e15b 100644 --- a/requirements.txt +++ b/requirements.txt @@ -19,3 +19,4 @@ matplotlib tblib dataclasses_json ray[default] +rich commit b3b2f234773878294025b08ff28a5db2686e167f Date: 2023-05-17T22:46:07-07:00 Tutorial fixes + MPT fixes (#147) * fix rename to handle str args * export Stacked and Embedding from nn * export named_pjit * allow un/flatten_axis to handle single element axes even when "that doesn't make sense" * fix rename for string selectors * allow separate control of bias vs weight in LayerNorm * stupid circular imports * kmcklamlf diff --git a/src/haliax/__init__.py b/src/haliax/__init__.py index 65e89b7..f33792e 100644 --- a/src/haliax/__init__.py +++ b/src/haliax/__init__.py @@ -28,7 +28,7 @@ from .core import ( ) from .hof import fold, scan, vmap from .ops import clip, isclose, pad_left, trace, tril, triu, where -from .partitioning import auto_sharded, axis_mapping, shard_with_axis_mapping +from .partitioning import auto_sharded, axis_mapping, named_pjit, shard_with_axis_mapping from .types import Axis, AxisSelection, AxisSelector, AxisSpec from .wrap import wrap_axiswise_call, wrap_elemwise_binary, wrap_elemwise_unary, wrap_reduction_call @@ -382,6 +382,7 @@ __all__ = [ "auto_sharded", "axis_mapping", "shard_with_axis_mapping", + "named_pjit", "enable_shape_checks", "are_shape_checks_enabled", "isclose", diff --git a/src/haliax/core.py b/src/haliax/core.py index dadf685..630670e 100644 --- a/src/haliax/core.py +++ b/src/haliax/core.py @@ -212,10 +212,10 @@ class NamedArray: def split(self, axis: AxisSelector, new_axes: Sequence[Axis]) -> Sequence["NamedArray"]: return haliax.split(self, axis=axis, new_axes=new_axes) - def flatten_axes(self, old_axes: Sequence[AxisSelector], new_axis: AxisSelector) -> "NamedArray": + def flatten_axes(self, old_axes: AxisSelection, new_axis: AxisSelector) -> "NamedArray": return haliax.flatten_axes(self, old_axes=old_axes, new_axis=new_axis) - def unflatten_axis(self, axis: AxisSelector, new_axes: Sequence[Axis]) -> "NamedArray": + def unflatten_axis(self, axis: AxisSelector, new_axes: AxisSpec) -> "NamedArray": return haliax.unflatten_axis(self, axis=axis, new_axes=new_axes) def unbind(self, axis: AxisSelector) -> Sequence["NamedArray"]: @@ -721,16 +721,17 @@ def rename(array: NamedArray, renames: Mapping[AxisSelector, AxisSelector]) -> N return NamedArray(array.array, new_axes) -def flatten_axes(array: NamedArray, old_axes: Sequence[AxisSelector], new_axis: AxisSelector) -> NamedArray: +def flatten_axes(array: NamedArray, old_axes: AxisSelection, new_axis: AxisSelector) -> NamedArray: """ Merge a sequence of axes into a single axis. The new axis must have the same size as the product of the old axes. For now the new axis will always be the last axis """ + old_axes = ensure_tuple(old_axes) + old_axes = array.resolve_axis(old_axes) + if len(old_axes) == 0: raise ValueError("Must specify at least one axis to merge") - old_axes = array.resolve_axis(old_axes) - if isinstance(new_axis, Axis): if new_axis.size != prod(array.axis_size(ax) for ax in old_axes): raise ValueError(f"Cannot merge {old_axes} into {new_axis}: size mismatch") @@ -760,7 +761,7 @@ def flatten_axes(array: NamedArray, old_axes: Sequence[AxisSelector], new_axis: return NamedArray(raw_array, tuple(new_axes)) -def unflatten_axis(array: NamedArray, axis: AxisSelector, new_axes: Sequence[Axis]) -> NamedArray: +def unflatten_axis(array: NamedArray, axis: AxisSelector, new_axes: AxisSpec) -> NamedArray: """ Split an axis into a sequence of axes. The old axis must have the same size as the product of the new axes. """ @@ -770,6 +771,8 @@ def unflatten_axis(array: NamedArray, axis: AxisSelector, new_axes: Sequence[Axi axis_size = array.axes[old_index].size + new_axes = ensure_tuple(new_axes) + if len(new_axes) == 0: if axis_size == 1: # just remove the old axis, akin to squeeze @@ -793,17 +796,38 @@ def named(a: jnp.ndarray, axis: AxisSelection) -> NamedArray: return NamedArray(a, axes) -def concat_axis_specs(a1: AxisSpec, a2: AxisSpec) -> AxisSpec: +@overload +def concat_axis_specs(a1: AxisSpec, a2: AxisSpec) -> Sequence[Axis]: + pass + + +@overload +def concat_axis_specs(a1: AxisSelection, a2: AxisSelection) -> Sequence[Union[Axis, str]]: + pass + + +def concat_axis_specs(a1: AxisSelection, a2: AxisSelection) -> AxisSelection: """Concatenates two AxisSpec. Raises ValueError if any axis is present in both specs""" + + def _ax_name(ax: AxisSelector) -> str: + if isinstance(ax, Axis): + return ax.name + else: + return ax + if isinstance(a1, Axis) and isinstance(a2, Axis): - if a1 == a2: + if _ax_name(a1) == _ax_name(a2): raise ValueError(f"Axis {a1} specified twice") return (a1, a2) else: a1 = ensure_tuple(a1) a2 = ensure_tuple(a2) - if any(x in a2 for x in a1) or any(x in a1 for x in a2): - overlap = set(a1).intersection(set(a2)) + + a1_names = [_ax_name(ax) for ax in a1] + a2_names = [_ax_name(ax) for ax in a2] + + if len(set(a1_names) & set(a2_names)) > 0: + overlap = [ax for ax in a1_names if ax in a2_names] raise ValueError(f"AxisSpecs overlap! {' '.join(str(x) for x in overlap)}") return a1 + a2 diff --git a/src/haliax/nn/__init__.py b/src/haliax/nn/__init__.py index 45bc23e..501bfd8 100644 --- a/src/haliax/nn/__init__.py +++ b/src/haliax/nn/__init__.py @@ -12,8 +12,10 @@ from ..core import NamedArray from ..types import Axis, AxisSelector, AxisSpec from ..wrap import unwrap_namedarrays, wrap_axiswise_call, wrap_elemwise_unary, wrap_reduction_call from .dropout import Dropout +from .embedding import Embedding from .linear import Linear from .normalization import LayerNorm +from .scan import Stacked relu = wrap_elemwise_unary(jnn.relu) @@ -142,4 +144,6 @@ __all__ = [ "Dropout", "LayerNorm", "Linear", + "Embedding", + "Stacked", ] diff --git a/src/haliax/nn/embedding.py b/src/haliax/nn/embedding.py new file mode 100644 index 0000000..fccde93 --- /dev/null +++ b/src/haliax/nn/embedding.py @@ -0,0 +1,40 @@ +import equinox as eqx + +import haliax as hax + +from ..core import Axis, NamedArray +from ..jax_utils import named_call + + +class Embedding(eqx.Module): + weight: NamedArray + + # axes + Vocab: Axis = eqx.static_field() + Embed: Axis = eqx.static_field() + + def __init__( + self, + Vocab: Axis, + Embed: Axis, + initializer_range: float = 0.02, + *, + key, + ): + super().__init__() + + self.Vocab = Vocab + self.Embed = Embed + + self.weight = hax.random.generate_sharded(hax.random.normal)(key, (Vocab, Embed)) * initializer_range + + @named_call + def __call__(self, input_ids, inference, *, key): + return self.embed(input_ids) + + def embed(self, input_ids): + input_embeds = self.weight.take(self.Vocab, input_ids) + return input_embeds + + def unembed(self, input_embeds): + return input_embeds.dot(self.Embed, self.weight) diff --git a/src/haliax/nn/normalization.py b/src/haliax/nn/normalization.py index 9d76f15..0d98937 100644 --- a/src/haliax/nn/normalization.py +++ b/src/haliax/nn/normalization.py @@ -19,13 +19,18 @@ class LayerNorm(eqx.Module): weight: Optional[NamedArray] bias: Optional[NamedArray] - def __init__(self, axis: AxisSpec, eps: float = 1e-5, elementwise_affine: bool = True): + def __init__(self, axis: AxisSpec, eps: float = 1e-5, use_weight: bool = True, use_bias: bool = True): self.axis = axis self.eps = eps - if elementwise_affine: + if use_weight: self.weight = hax.ones(axis) + else: + self.weight = None + if use_bias: self.bias = hax.zeros(axis) + else: + self.bias = None def __call__(self, x: NamedArray) -> NamedArray: mean = x.mean(self.axis) @@ -34,5 +39,7 @@ class LayerNorm(eqx.Module): out = (x - mean) * inv if self.weight is not None: - out = self.weight * out + self.bias + out = self.weight * out + if self.bias is not None: + out = out + self.bias return out diff --git a/src/haliax/nn/scan.py b/src/haliax/nn/scan.py index 5640d1d..08b9b82 100644 --- a/src/haliax/nn/scan.py +++ b/src/haliax/nn/scan.py @@ -3,7 +3,7 @@ from typing import Dict, Generic, Optional, Type, TypeVar import equinox as eqx import haliax -from haliax import Axis +from haliax.core import Axis from haliax.jax_utils import filter_checkpoint @@ -39,7 +39,7 @@ class Stacked(eqx.Module, Generic[M]): ... def __call__(self, x): ... return self.layers.fold(x) # applies each layer in sequence ... - >>> Hidden = Axis("hidden", 10) + >>> Hidden = hax.Axis("hidden", 10) >>> mod = MyModule(5, Hidden) >>> mod(hax.ones(Hidden)) """ commit 49372557f1d1e2cc79f441252b5299ba67a3e6c6 Date: 2023-05-17T23:47:55-07:00 fix rename, for good? (#148) diff --git a/src/haliax/core.py b/src/haliax/core.py index 630670e..d328375 100644 --- a/src/haliax/core.py +++ b/src/haliax/core.py @@ -709,13 +709,25 @@ def rename(array: NamedArray, renames: Mapping[AxisSelector, AxisSelector]) -> N if isinstance(old, Axis) and isinstance(new, Axis) and old.size != new.size: raise ValueError(f"Cannot rename axis {old} to {new}: size mismatch") - def _rename(ax: Axis) -> Axis: - new_axis = renames.get(ax, ax) - if isinstance(new_axis, Axis): + def _rename(ax: AxisSelector) -> Axis: + new_axis = renames.get(ax, None) + if new_axis is None and isinstance(ax, Axis): + new_axis_name = renames.get(ax.name, None) + if isinstance(new_axis_name, str): + new_axis = Axis(new_axis_name, ax.size) + return new_axis + elif isinstance(new_axis_name, Axis): + if new_axis_name.size != ax.size: + raise ValueError(f"Cannot rename axis {ax} to {new_axis_name}: size mismatch") + return new_axis_name + else: + return ax + elif isinstance(new_axis, Axis): return new_axis else: assert isinstance(new_axis, str) - return Axis(new_axis, ax.size) + ax_size = array.axis_size(ax) + return Axis(new_axis, ax_size) new_axes = tuple(_rename(ax) for ax in array.axes) return NamedArray(array.array, new_axes) diff --git a/tests/core_test.py b/tests/core_test.py index fc36077..ff957de 100644 --- a/tests/core_test.py +++ b/tests/core_test.py @@ -363,3 +363,24 @@ def test_unflatten_axis(): flattened_HD = named1.flatten_axes((H, D), "Z") assert jnp.all(jnp.equal(hax.unflatten_axis(flattened_HD, "Z", (H, D)).array, named1.array.transpose(0, 2, 1))) assert hax.unflatten_axis(flattened_HD, "Z", (H, D)).axes == (H, D, W) + + +def test_rename(): + H = Axis("H", 2) + W = Axis("W", 3) + D = Axis("D", 4) + + H2 = Axis("H2", 2) + W2 = Axis("W2", 3) + D2 = Axis("D2", 4) + + named1 = hax.random.uniform(PRNGKey(0), (H, W, D)) + + assert jnp.all(jnp.equal(hax.rename(named1, {"H": "H2", "W": "W2", "D": "D2"}).array, named1.array)) + assert hax.rename(named1, {"H": "H2", "W": "W2", "D": "D2"}).axes == (H2, W2, D2) + + assert jnp.all(jnp.equal(hax.rename(named1, {"H": H2, "W": "W2"}).array, named1.array)) + assert hax.rename(named1, {"H": H2, "W": "W2"}).axes == (H2, W2, D) + + assert jnp.all(jnp.equal(hax.rename(named1, {H: H2, "W": "W2"}).array, named1.array)) + assert hax.rename(named1, {H: H2, "W": "W2"}).axes == (H2, W2, D) commit c3c97b6da4c32d49a6d2255b11bc05c7cff89978 Date: 2023-05-18T16:35:33-07:00 WIP blogpost and complete-ish architecture draft (#136) * draft * wip * rename * wip * minor * wip updating fsdp in overview * FSDP overview almost done * wip * simple initial training loop * ok, first complete draft? * cleanup * cleanup * fix rename to handle str args * wip * Ivan's PR comments diff --git a/src/haliax/__init__.py b/src/haliax/__init__.py index f33792e..b0931bf 100644 --- a/src/haliax/__init__.py +++ b/src/haliax/__init__.py @@ -381,6 +381,7 @@ __all__ = [ "true_divide", "auto_sharded", "axis_mapping", + "named_pjit", "shard_with_axis_mapping", "named_pjit", "enable_shape_checks", diff --git a/src/haliax/nn/attention.py b/src/haliax/nn/attention.py index c1711e6..0b90110 100644 --- a/src/haliax/nn/attention.py +++ b/src/haliax/nn/attention.py @@ -24,7 +24,7 @@ from haliax.types import Axis, AxisSelection, AxisSpec, PrecisionLike def dot_product_attention_weights( Head: Axis, - KSeqLen: AxisSelection, + KPos: AxisSelection, query: NamedArray, key: NamedArray, mask: Optional[NamedArray] = None, @@ -34,17 +34,17 @@ def dot_product_attention_weights( ) -> NamedArray: """ NamedArray version of dot product attention. Computes the logits for the attention weights. Note that the - "SeqLen" axis in query must be distinct from the "SeqLen" axis in key. + "Pos" axis in query must be distinct from the "Pos" axis in key. :param Head: Axis of head dimension - :param KSeqLen: Axis of key sequence length. Can be an AxisSpec to attend along more than one axis. - :param query: NamedArray of shape (QSeqLen, HeadDim) - :param key: NamedArray of shape (KSeqLen, HeadDim) - :param mask: Optional[NamedArray] broadcast compatible with (HeadDim, QSeqLen, KSeqLen). Should be boolean - :param bias: Optional[NamedArray] broadcast compatible with (HeadDim, QSeqLen, KSeqLen). Should be float + :param KPos: Axis of key sequence. Can be an AxisSpec to attend along more than one axis. + :param query: NamedArray of shape (QPos, HeadDim) + :param key: NamedArray of shape (KPos, HeadDim) + :param mask: Optional[NamedArray] broadcast compatible with (HeadDim, QPos, KPos). Should be boolean + :param bias: Optional[NamedArray] broadcast compatible with (HeadDim, QPos, KPos). Should be float :param attention_dtype: Optional dtype to use for attention :param precision: PrecisionLike for dot product. See precision argument to jax.lax.dot_general - :return: NamedArray of shape (QSeqLen, KSeqLen) + :return: NamedArray of shape (QPos, KPos) """ # cf https://github.com/google/flax/blob/509bf97ea272e130d932920f45307ac98947d994/flax/linen/attention.py#L40 import haliax.nn as hnn @@ -63,14 +63,14 @@ def dot_product_attention_weights( if mask is not None: weights = haliax.where(mask, weights, -1e9) - weights = hnn.softmax(weights, axis=KSeqLen) + weights = hnn.softmax(weights, axis=KPos) return weights.astype(orig_dtype) def dot_product_attention( - QSeqLen: Axis, - KSeqLen: Axis, + QPos: Axis, + KPos: Axis, HeadDim: Axis, query: NamedArray, key: NamedArray, @@ -83,33 +83,33 @@ def dot_product_attention( """ NamedArray version of dot product attention. This can be multi-headed or not. - :param QSeqLen: Axis of sequence length - :param KSeqLen: Axis of key sequence length + :param QPos: Axis of sequence length + :param KPos: Axis of key sequence length :param HeadDim: Axis of head dimension - :param query: NamedArray of shape (QSeqLen, HeadDim) - :param key: NamedArray of shape (KSeqLen, HeadDim) - :param value: NamedArray of shape (KSeqLen, HeadDim) - :param mask: Optional[NamedArray] broadcast compatible with (HeadDim, QSeqLen, KSeqLen). Should be boolean - :param bias: Optional[NamedArray] broadcast compatible with (HeadDim, QSeqLen, KSeqLen). Should be float + :param query: NamedArray of shape (QPos, HeadDim) + :param key: NamedArray of shape (KPos, HeadDim) + :param value: NamedArray of shape (KPos, HeadDim) + :param mask: Optional[NamedArray] broadcast compatible with (HeadDim, QPos, KPos). Should be boolean + :param bias: Optional[NamedArray] broadcast compatible with (HeadDim, QPos, KPos). Should be float :param attention_dtype: Optional dtype to use for attention :param precision: PrecisionLike for dot product. See precision argument to jax.lax.dot_general - :return: NamedArray of shape (QSeqLen, HeadDim) + :return: NamedArray of shape (QPos, HeadDim) Mask and bias are given as separate arguments because they are often computed separately and have different shapes. - For example, mask is frequently just a boolean array of shape (QSeqLen, KSeqLen), while bias is frequently a float - array of shape (HeadDim, QSeqLen, KSeqLen) or (HeadDim, KSeqLen) + For example, mask is frequently just a boolean array of shape (QPos, KPos), while bias is frequently a float + array of shape (HeadDim, QPos, KPos) or (HeadDim, KPos) """ # cf https://github.com/google/flax/blob/509bf97ea272e130d932920f45307ac98947d994/flax/linen/attention.py#L125 # rename key/value length axis if it's the same as the query length axis - if KSeqLen == QSeqLen: - KSeqLen = QSeqLen.alias(KSeqLen.name + "_key") - key = key.rename({KSeqLen: QSeqLen}) - value = value.rename({KSeqLen: QSeqLen}) + if KPos == QPos: + KPos = QPos.alias(KPos.name + "_key") + key = key.rename({KPos: QPos}) + value = value.rename({KPos: QPos}) - weights = dot_product_attention_weights(HeadDim, KSeqLen, query, key, mask, bias, attention_dtype, precision) + weights = dot_product_attention_weights(HeadDim, KPos, query, key, mask, bias, attention_dtype, precision) - return haliax.dot(KSeqLen, weights, value) + return haliax.dot(KPos, weights, value) def mask_to_bias(mask: NamedArray, mask_value: float = -1e9) -> NamedArray: @@ -132,46 +132,46 @@ def combine_masks_or(mask1: Optional[NamedArray], mask2: Optional[NamedArray]) - return mask1 | mask2 -def causal_mask(QSeqLen: Axis, KSeqLen: Axis) -> NamedArray: +def causal_mask(QPos: Axis, KPos: Axis) -> NamedArray: """ Creates a causal mask for attention. - :param QSeqLen: Axis of query sequence length - :param KSeqLen: Axis of key sequence length - :return: NamedArray of shape (QSeqLen, KSeqLen) + :param QPos: Axis of query sequence length + :param KPos: Axis of key sequence length + :return: NamedArray of shape (QPos, KPos) """ # copilot wrote this and i'm just blown away - return haliax.arange(QSeqLen).broadcast_axis(KSeqLen) >= haliax.arange(KSeqLen).broadcast_axis(QSeqLen) + return haliax.arange(QPos).broadcast_axis(KPos) >= haliax.arange(KPos).broadcast_axis(QPos) def dropout_mask(axes: AxisSpec, dropout_rate: float, *, key: PRNGKey) -> NamedArray: """ - Really just an alias for haliax.random.bernoulli. You can pass in e.g. Head, QSeqLen and KSeqLen + Really just an alias for haliax.random.bernoulli. You can pass in e.g. Head, QPos and KPos """ return hrandom.bernoulli(key, shape=axes, p=1 - dropout_rate) -def forgetful_causal_mask(KSeqLen: Axis, mask_prob: float, sample_prob: bool = True, *, key: PRNGKey) -> NamedArray: +def forgetful_causal_mask(KPos: Axis, mask_prob: float, sample_prob: bool = True, *, key: PRNGKey) -> NamedArray: """ Forgetful Context Masking a la https://arxiv.org/abs/2210.13432. Randomly drops out positions from the key sequence. Reportedly better than normal attention dropout. Almost certainly faster. You're always allowed to attend to the 0th position. (They say BOS token, but we don't always start with bos) - :param KSeqLen: Axis of key sequence length + :param KPos: Axis of key sequence length :param mask_prob: Probability a position to mask :param sample_prob: If True, sample the prob between 0 and the provided prob (this is what the paper does) """ - zeroth_on = haliax.nn.one_hot(0, KSeqLen, dtype=jnp.bool_) # always allow 0th position + zeroth_on = haliax.nn.one_hot(0, KPos, dtype=jnp.bool_) # always allow 0th position if mask_prob == 0: - return jnp.ones((KSeqLen.size,), dtype=jnp.bool_) + return jnp.ones((KPos.size,), dtype=jnp.bool_) elif mask_prob == 1: return zeroth_on else: if sample_prob: key, subkey = jax.random.split(key) mask_prob = jax.random.uniform(subkey, shape=(), minval=0, maxval=mask_prob) - base: NamedArray = hrandom.bernoulli(key, shape=(KSeqLen,), p=1 - mask_prob) + base: NamedArray = hrandom.bernoulli(key, shape=(KPos,), p=1 - mask_prob) return base | zeroth_on @@ -191,16 +191,16 @@ def _get_alibi_slopes(heads: int) -> List[float]: ) -def alibi_attention_bias(Heads: Axis, SeqLen: Axis, dtype=jnp.float32) -> NamedArray: +def alibi_attention_bias(Heads: Axis, Pos: Axis, dtype=jnp.float32) -> NamedArray: """ Creates an attention bias for alibi attention. - :param SeqLen: Axis of sequence length + :param Pos: Axis of sequence length :param Heads: Axis of heads - :return: NamedArray of shape (Heads, QSeqLen) + :return: NamedArray of shape (Heads, QPos) """ slopes = haliax.named(np.array(_get_alibi_slopes(Heads.size)), Heads) - positions = haliax.arange(SeqLen).broadcast_axis(Heads) + positions = haliax.arange(Pos).broadcast_axis(Heads) biases = slopes * positions return biases.astype(dtype) diff --git a/src/haliax/nn/scan.py b/src/haliax/nn/scan.py index 08b9b82..39574f6 100644 --- a/src/haliax/nn/scan.py +++ b/src/haliax/nn/scan.py @@ -22,6 +22,10 @@ class Stacked(eqx.Module, Generic[M]): the sequential and compiling everything as a giant graph. In Jax, this pattern is often called "scan layers" or "scan over layers". + A further constraint is that the elements of the stack must have the same Python control flow. This is because + Jax's scan primitive requires that the function you pass to it is pure, and the only way to do that is to ensure + that the function has the same control flow for every element of the stack. + Stacked supports both "fold" and "scan" semantics. "fold" is the same as a for loop that accumulates a single output, while "scan" is the same as a for loop that accumulates a list of intermediates as well as the final output. @@ -44,6 +48,8 @@ class Stacked(eqx.Module, Generic[M]): >>> mod(hax.ones(Hidden)) """ + # TODO: we can probably make this module support pipeline parallelism, but that's a whole project in itself + stacked: M Block: Axis = eqx.static_field() # TODO: support fancier gradient checkpointing diff --git a/tests/test_attention.py b/tests/test_attention.py index db321b9..607c6d0 100644 --- a/tests/test_attention.py +++ b/tests/test_attention.py @@ -7,22 +7,22 @@ from haliax.nn.attention import alibi_attention_bias, dot_product_attention_weig def test_alibi_attention_bias(): - KeySeqLen = hax.Axis("KeySeqLen", 20) + KeyPos = hax.Axis("KeyPos", 20) NumHeads = hax.Axis("NumHeads", 1) Hid = hax.Axis("Hid", 8) - bias = alibi_attention_bias(NumHeads, KeySeqLen) + bias = alibi_attention_bias(NumHeads, KeyPos) query = hax.ones((NumHeads, Hid)) - key = hax.ones((KeySeqLen, NumHeads, Hid)) + key = hax.ones((KeyPos, NumHeads, Hid)) - weights_bias = dot_product_attention_weights(Hid, KeySeqLen, query, key, bias=bias) - weights_no_bias = dot_product_attention_weights(Hid, KeySeqLen, query, key) + weights_bias = dot_product_attention_weights(Hid, KeyPos, query, key, bias=bias) + weights_no_bias = dot_product_attention_weights(Hid, KeyPos, query, key) - assert weights_bias.take(KeySeqLen, -1).item() > weights_bias.take(KeySeqLen, -2).item() - assert weights_bias.take(KeySeqLen, -1).item() > weights_no_bias.take(KeySeqLen, -1).item() + assert weights_bias.take(KeyPos, -1).item() > weights_bias.take(KeyPos, -2).item() + assert weights_bias.take(KeyPos, -1).item() > weights_no_bias.take(KeyPos, -1).item() - assert weights_no_bias.take(KeySeqLen, -1).item() == weights_no_bias.take(KeySeqLen, -2).item() + assert weights_no_bias.take(KeyPos, -1).item() == weights_no_bias.take(KeyPos, -2).item() @skip_if_no_torch @@ -44,26 +44,26 @@ def test_alibi_attention_compared_to_hf(): def test_fcm_attention_mask(): - KeySeqLen = hax.Axis("KeySeqLen", 20) + KeyPos = hax.Axis("KeyPos", 20) - mask = forgetful_causal_mask(KeySeqLen, mask_prob=0.6, sample_prob=False, key=PRNGKey(0)) + mask = forgetful_causal_mask(KeyPos, mask_prob=0.6, sample_prob=False, key=PRNGKey(0)) - assert mask.axes == (KeySeqLen,) + assert mask.axes == (KeyPos,) assert mask.array[0].item() == 1 - assert mask.astype(float).sum().item() <= KeySeqLen.size + assert mask.astype(float).sum().item() <= KeyPos.size - QuerySeqLen = hax.Axis("QuerySeqLen", 10) + QueryPos = hax.Axis("QueryPos", 10) Head = hax.Axis("Head", 8) - query = hax.arange(QuerySeqLen).broadcast_axis(Head) - key = hax.arange(KeySeqLen).broadcast_axis(Head) + query = hax.arange(QueryPos).broadcast_axis(Head) + key = hax.arange(KeyPos).broadcast_axis(Head) - weights = dot_product_attention_weights(Head, KeySeqLen, query, key, mask=mask) + weights = dot_product_attention_weights(Head, KeyPos, query, key, mask=mask) # check that all masked out values are zero # TODO: think about how to make this work with named arrays - weights = weights.rearrange((KeySeqLen, QuerySeqLen)).array + weights = weights.rearrange((KeyPos, QueryPos)).array mask = mask.array assert weights[mask == 0].sum() == 0 commit 228f9a91748d6ff90876670f9a66b8c2cd156a79 Date: 2023-05-19T20:43:31-07:00 allow mesh to be an argument to shard_with_axis_mapping diff --git a/src/haliax/partitioning.py b/src/haliax/partitioning.py index 3992cba..08b2046 100644 --- a/src/haliax/partitioning.py +++ b/src/haliax/partitioning.py @@ -11,6 +11,7 @@ import jax.numpy as jnp from equinox.compile_utils import compile_cache, get_fun_names, hashable_combine, hashable_partition from jax.experimental.pjit import pjit, with_sharding_constraint from jax.interpreters.pxla import PartitionSpec +from jax.sharding import Mesh from jaxlib.xla_client import SingleDeviceSharding from jaxtyping import PyTree @@ -67,7 +68,7 @@ def axis_mapping(mapping: ResourceMapping, *, merge: bool = False, **kwargs): T = TypeVar("T", bound=PyTree) -def auto_sharded(x: T) -> T: +def auto_sharded(x: T, mesh: Optional[Mesh] = None) -> T: """ Shard a PyTree using the global axis mapping. NamedArrays in the PyTree are sharded using the axis mapping and the names in the tree. @@ -79,10 +80,10 @@ def auto_sharded(x: T) -> T: if mapping is None: return x - return shard_with_axis_mapping(x, mapping) + return shard_with_axis_mapping(x, mapping, mesh) -def shard_with_axis_mapping(x: T, mapping: ResourceMapping) -> T: +def shard_with_axis_mapping(x: T, mapping: ResourceMapping, mesh: Optional[Mesh] = None) -> T: """ Shard a PyTree using the provided axis mapping. NamedArrays in the PyTree are sharded using the axis mapping. Other arrays are not sharded (unless they're already sharded). @@ -90,10 +91,6 @@ def shard_with_axis_mapping(x: T, mapping: ResourceMapping) -> T: Inside of a jit context, this method grounds out in calls to `with_sharding_constraint`. Outside of a jit context, this method grounds out in either device_put or make_array_from_callback, depending on whether the resulting sharding spans more than one host. - - :param x: - :param mapping: - :return: """ if _is_jit_context(): @@ -108,7 +105,7 @@ def shard_with_axis_mapping(x: T, mapping: ResourceMapping) -> T: return jax.tree_util.tree_map(_shard_leaf, x, is_leaf=is_named_array) else: # use device_put or make_array_from_callback instead - mesh = _get_mesh() + mesh = mesh or _get_mesh() def _do_device_put(x): if not is_named_array(x): commit a6846ba67e146a6b34e61278e679bf91f2116a40 Date: 2023-05-22T12:05:22-07:00 Support choosing a different branch and/or remote when using the setup scripts (#140) * checkout a branch automatically on setup * fix validation path for openwebtext * allow for specifying a git branch in small_fast * force newer tensorstore for newer jax * use preemptible for small_fast diff --git a/requirements.txt b/requirements.txt index 1e0e15b..dea82ef 100644 --- a/requirements.txt +++ b/requirements.txt @@ -10,7 +10,7 @@ gcsfs==2023.3.0 braceexpand jmp @ git+https://github.com/deepmind/jmp#7b3ae548154625a56a6dbdb03bc07d4f599c37b2 fsspec==2023.3.0 # pin this to make gcsfs happy -tensorstore +tensorstore>=0.1.36 pytimeparse humanfriendly requests commit 122138b80e08c2a6e1b24d6632571ed536eab0a3 Date: 2023-05-22T12:22:28-07:00 Separate initialization of nn Modules from ctor (#150) * fix rename, for good? * rename SeqLen->Pos * just pass the gpt config object around a lot more * extract to reduce line nonsense * more cleanup -> putting things in config * more cleanup -> putting things in config * more cleanup -> fewer names to reduce line count * 1 line properties, KeySize->HeadSize * hidden_states -> x * hoist the argument I want first in GPT to be first * separate LayerNorm initialization from constructor * separate Linear initialization from constructor * convert Gpt2 to use "init" static method for initialization diff --git a/src/haliax/nn/attention.py b/src/haliax/nn/attention.py index 0b90110..3e4c1d6 100644 --- a/src/haliax/nn/attention.py +++ b/src/haliax/nn/attention.py @@ -37,11 +37,11 @@ def dot_product_attention_weights( "Pos" axis in query must be distinct from the "Pos" axis in key. :param Head: Axis of head dimension - :param KPos: Axis of key sequence. Can be an AxisSpec to attend along more than one axis. - :param query: NamedArray of shape (QPos, HeadDim) - :param key: NamedArray of shape (KPos, HeadDim) - :param mask: Optional[NamedArray] broadcast compatible with (HeadDim, QPos, KPos). Should be boolean - :param bias: Optional[NamedArray] broadcast compatible with (HeadDim, QPos, KPos). Should be float + :param KPos: Axis of key sequence length. Can be an AxisSpec to attend along more than one axis. + :param query: NamedArray of shape (QPos, KeySize) + :param key: NamedArray of shape (KPos, KeySize) + :param mask: Optional[NamedArray] broadcast compatible with (KeySize, QPos, KPos). Should be boolean + :param bias: Optional[NamedArray] broadcast compatible with (KeySize, QPos, KPos). Should be float :param attention_dtype: Optional dtype to use for attention :param precision: PrecisionLike for dot product. See precision argument to jax.lax.dot_general :return: NamedArray of shape (QPos, KPos) @@ -71,7 +71,7 @@ def dot_product_attention_weights( def dot_product_attention( QPos: Axis, KPos: Axis, - HeadDim: Axis, + KeySize: Axis, query: NamedArray, key: NamedArray, value: NamedArray, @@ -85,19 +85,19 @@ def dot_product_attention( :param QPos: Axis of sequence length :param KPos: Axis of key sequence length - :param HeadDim: Axis of head dimension - :param query: NamedArray of shape (QPos, HeadDim) - :param key: NamedArray of shape (KPos, HeadDim) - :param value: NamedArray of shape (KPos, HeadDim) - :param mask: Optional[NamedArray] broadcast compatible with (HeadDim, QPos, KPos). Should be boolean - :param bias: Optional[NamedArray] broadcast compatible with (HeadDim, QPos, KPos). Should be float + :param KeySize: Axis of head dimension + :param query: NamedArray of shape (QPos, KeySize) + :param key: NamedArray of shape (KPos, KeySize) + :param value: NamedArray of shape (KPos, KeySize) + :param mask: Optional[NamedArray] broadcast compatible with (KeySize, QPos, KPos). Should be boolean + :param bias: Optional[NamedArray] broadcast compatible with (KeySize, QPos, KPos). Should be float :param attention_dtype: Optional dtype to use for attention :param precision: PrecisionLike for dot product. See precision argument to jax.lax.dot_general - :return: NamedArray of shape (QPos, HeadDim) + :return: NamedArray of shape (QPos, KeySize) Mask and bias are given as separate arguments because they are often computed separately and have different shapes. For example, mask is frequently just a boolean array of shape (QPos, KPos), while bias is frequently a float - array of shape (HeadDim, QPos, KPos) or (HeadDim, KPos) + array of shape (KeySize, QPos, KPos) or (KeySize, KPos) """ # cf https://github.com/google/flax/blob/509bf97ea272e130d932920f45307ac98947d994/flax/linen/attention.py#L125 @@ -107,7 +107,7 @@ def dot_product_attention( key = key.rename({KPos: QPos}) value = value.rename({KPos: QPos}) - weights = dot_product_attention_weights(HeadDim, KPos, query, key, mask, bias, attention_dtype, precision) + weights = dot_product_attention_weights(KeySize, KPos, query, key, mask, bias, attention_dtype, precision) return haliax.dot(KPos, weights, value) diff --git a/src/haliax/nn/linear.py b/src/haliax/nn/linear.py index 75b521f..1a10db2 100644 --- a/src/haliax/nn/linear.py +++ b/src/haliax/nn/linear.py @@ -19,13 +19,12 @@ class Linear(eqx.Module): In: AxisSpec = eqx.static_field() Out: AxisSpec = eqx.static_field() - def __init__(self, In: AxisSpec, Out: AxisSpec, *, key, use_bias=True): + @staticmethod + def init(In: AxisSpec, Out: AxisSpec, *, key, use_bias=True) -> "Linear": joint_spec = hax.concat_axis_specs(In, Out) - self.weight = hax.random.generate_sharded(hax.random.normal)(key, joint_spec) * 0.02 - self.bias = hax.zeros(Out) if use_bias else None - - self.In = In - self.Out = Out + weight = hax.random.generate_sharded(hax.random.normal)(key, joint_spec) * 0.02 + bias = hax.zeros(Out) if use_bias else None + return Linear(weight, bias, In, Out) @jax.named_scope(name="linear") def __call__(self, inputs): @@ -34,7 +33,6 @@ class Linear(eqx.Module): if self.bias is not None: q = q + self.bias - - q = hax.auto_sharded(q) + q = hax.auto_sharded(q) return q diff --git a/src/haliax/nn/normalization.py b/src/haliax/nn/normalization.py index 0d98937..000d8c2 100644 --- a/src/haliax/nn/normalization.py +++ b/src/haliax/nn/normalization.py @@ -14,23 +14,23 @@ class LayerNorm(eqx.Module): input along that axis. """ axis: AxisSpec = eqx.static_field() - eps: float = eqx.static_field() - weight: Optional[NamedArray] bias: Optional[NamedArray] - def __init__(self, axis: AxisSpec, eps: float = 1e-5, use_weight: bool = True, use_bias: bool = True): - self.axis = axis - self.eps = eps + eps: float = eqx.static_field(default=1e-5) + @staticmethod + def init(axis: AxisSpec, eps: float = 1e-5, use_weight: bool = True, use_bias: bool = True): if use_weight: - self.weight = hax.ones(axis) + weight = hax.ones(axis) else: - self.weight = None + weight = None if use_bias: - self.bias = hax.zeros(axis) + bias = hax.zeros(axis) else: - self.bias = None + bias = None + + return LayerNorm(axis, weight, bias, eps) def __call__(self, x: NamedArray) -> NamedArray: mean = x.mean(self.axis) diff --git a/src/haliax/nn/scan.py b/src/haliax/nn/scan.py index 39574f6..e93b2c2 100644 --- a/src/haliax/nn/scan.py +++ b/src/haliax/nn/scan.py @@ -1,4 +1,5 @@ -from typing import Dict, Generic, Optional, Type, TypeVar +import functools +from typing import Dict, Generic, Optional, Protocol, Type, TypeVar import equinox as eqx @@ -7,7 +8,12 @@ from haliax.core import Axis from haliax.jax_utils import filter_checkpoint -M = TypeVar("M", bound=eqx.Module) +M = TypeVar("M", bound=eqx.Module, covariant=True) + + +class ModuleInit(Protocol[M]): + def __call__(self, *args, **kwargs) -> M: + ... class Stacked(eqx.Module, Generic[M]): @@ -38,7 +44,7 @@ class Stacked(eqx.Module, Generic[M]): >>> class MyModule(eqx.Module): ... def __init__(self, num_layers: int, hidden: hax.Axis, *, key): ... self.axis = Axis("layer", num_layers) - ... self.layers = Stacked(self.axis, hnn.Linear, In=hidden, Out=hidden, key=key) + ... self.layers = Stacked.init(self.axis, hnn.Linear)(In=hidden, Out=hidden, key=key) ... ... def __call__(self, x): ... return self.layers.fold(x) # applies each layer in sequence @@ -55,11 +61,14 @@ class Stacked(eqx.Module, Generic[M]): # TODO: support fancier gradient checkpointing gradient_checkpointing: bool = eqx.static_field() - def __init__(self, Block: Axis, module: Type[M], *args, gradient_checkpointing: bool = False, **kwargs): - super().__init__() - self.Block = Block - self.stacked = haliax.vmap(module, Block)(*args, **kwargs) - self.gradient_checkpointing = gradient_checkpointing + @staticmethod + def init(Block: Axis, module: Type[M], *, gradient_checkpointing: bool = False) -> ModuleInit["Stacked[M]"]: + @functools.wraps(module) + def fn(*args, **kwargs): + stacked = haliax.vmap(module.init, Block)(*args, **kwargs) + return Stacked(stacked, Block, gradient_checkpointing) + + return fn def scan(self, init, *extra_args, **extra_kwargs): if self.gradient_checkpointing: diff --git a/tests/test_nn.py b/tests/test_nn.py index 52f4b26..7a764e0 100644 --- a/tests/test_nn.py +++ b/tests/test_nn.py @@ -21,7 +21,7 @@ def _compare_eqx_and_haliax(hax_mod: eqx.Module, eqx_mod: eqx.Module): def test_layer_norm(): H = Axis("H", 10) - hax_ln = hax.nn.LayerNorm(H) + hax_ln = hax.nn.LayerNorm.init(H) eqx_ln = eqx.nn.LayerNorm(shape=(H.size,)) f = _compare_eqx_and_haliax(hax_ln, eqx_ln) commit c4968706a70078c612138501f52b01ce1805f972 Date: 2023-05-22T14:06:15-07:00 rename named_pjit to named_jit, make in_axis_resources not default (#154) * rename named_pjit to named_jit, since Jax is going that way. Also change default behavior so that we don't reshard inputs if we don't hav to * use Pos without path b/c we can * update docs for named_jit * update jax version * fix shard_with_axis_mapping outside pjit diff --git a/src/haliax/__init__.py b/src/haliax/__init__.py index b0931bf..8d80679 100644 --- a/src/haliax/__init__.py +++ b/src/haliax/__init__.py @@ -28,7 +28,7 @@ from .core import ( ) from .hof import fold, scan, vmap from .ops import clip, isclose, pad_left, trace, tril, triu, where -from .partitioning import auto_sharded, axis_mapping, named_pjit, shard_with_axis_mapping +from .partitioning import auto_sharded, axis_mapping, named_jit, shard_with_axis_mapping from .types import Axis, AxisSelection, AxisSelector, AxisSpec from .wrap import wrap_axiswise_call, wrap_elemwise_binary, wrap_elemwise_unary, wrap_reduction_call @@ -381,9 +381,9 @@ __all__ = [ "true_divide", "auto_sharded", "axis_mapping", - "named_pjit", + "named_jit", "shard_with_axis_mapping", - "named_pjit", + "named_jit", "enable_shape_checks", "are_shape_checks_enabled", "isclose", diff --git a/src/haliax/partitioning.py b/src/haliax/partitioning.py index 08b2046..7cacb0a 100644 --- a/src/haliax/partitioning.py +++ b/src/haliax/partitioning.py @@ -9,10 +9,11 @@ import equinox as eqx import jax import jax.numpy as jnp from equinox.compile_utils import compile_cache, get_fun_names, hashable_combine, hashable_partition -from jax.experimental.pjit import pjit, with_sharding_constraint +from jax._src.sharding_impls import AUTO +from jax.experimental.pjit import pjit from jax.interpreters.pxla import PartitionSpec +from jax.lax import with_sharding_constraint from jax.sharding import Mesh -from jaxlib.xla_client import SingleDeviceSharding from jaxtyping import PyTree from .core import NamedArray @@ -111,33 +112,40 @@ def shard_with_axis_mapping(x: T, mapping: ResourceMapping, mesh: Optional[Mesh] if not is_named_array(x): return x - pspec = pspec_for_axis(x.axes, mapping) - sharding = jax.sharding.NamedSharding(mesh, pspec) - raw_x = x.array current_sharding = raw_x.sharding - if current_sharding == sharding: + desired_sharding = infer_resource_partitions( + x, mapping, mesh=mesh, preserve_existing_shardings=False + ).array + + if current_sharding == desired_sharding: return x - elif sharding.is_fully_addressable: - raw_x = jax.device_put(raw_x, sharding) + elif desired_sharding.is_fully_addressable: + raw_x = jax.device_put(raw_x, desired_sharding) return NamedArray(raw_x, x.axes) else: # if the sharding is not fully addressable, we can't use device_put, so we use this hacky workaround. # TODO: we lose "src" information, but i think that's only for autodiff, and this isn't an autodiff # context, I think? shape = raw_x.shape - raw_x = jax.make_array_from_callback(shape, sharding, lambda index: raw_x[index]) + raw_x = jax.make_array_from_callback(shape, desired_sharding, lambda index: raw_x[index]) return NamedArray(raw_x, x.axes) return jax.tree_util.tree_map(_do_device_put, x, is_leaf=is_named_array) -def infer_resource_partitions(tree: PyTree, resource_mapping: Optional[ResourceMapping] = None) -> PyTree: +def infer_resource_partitions( + tree: PyTree, + resource_mapping: Optional[ResourceMapping] = None, + preserve_existing_shardings: bool = True, + mesh: Optional[Mesh] = None, +) -> PyTree: """ - Infer the resource partitions for a module, to be used with pjit. + Infer the sharding for a module, to be used with named_jit. The basic idea is to tree all NamedArrays as leaves for the purposes of this function, - and to create PartitionSpecs from those names plus the resource_mapping. + and to create NamedShardings from those names plus the resource_mapping. + If preserve_existing_shardings is True, then NamedArrays that are already sharded are left alone. If resource_mapping is not provided, this function attempts to use the global resource mapping. """ @@ -147,28 +155,37 @@ def infer_resource_partitions(tree: PyTree, resource_mapping: Optional[ResourceM if resource_mapping is None: raise ValueError("No resource mapping found") + mesh = mesh or _get_mesh() + + def _auto_array_sharding(node): + if hasattr(node, "sharding"): + return node.sharding + else: + return None + def partition_spec(node: typing.Any): if isinstance(node, NamedArray): - return NamedArray( - pspec_for_axis(node.axes, resource_mapping), # type: ignore - node.axes, - ) - # elif isinstance(node, GlobalDeviceArray): - # return FROM_GDA - elif hasattr(node, "sharding"): - sharding = node.sharding - # these are usually replicated. Is there a better way to tell? - if isinstance(sharding, SingleDeviceSharding): - return None + if preserve_existing_shardings: + current_sharding = _auto_array_sharding(node) else: - return sharding + current_sharding = None + + if current_sharding is not None: + return NamedArray(current_sharding, node.axes) # type: ignore + else: + sharding = jax.sharding.NamedSharding(mesh, pspec_for_axis(node.axes, resource_mapping)) + return NamedArray(sharding, node.axes) # type: ignore else: - return None + sharding = _auto_array_sharding(node) + if sharding is not None: + return sharding + else: + return AUTO return jax.tree_util.tree_map(partition_spec, tree, is_leaf=is_named_array) -def named_pjit( +def named_jit( fn=None, axis_resources: Optional[ResourceMapping] = None, *, @@ -179,27 +196,26 @@ def named_pjit( **pjit_args, ): """ - A version of pjit that uses NamedArrays and the provided resource mapping to infer the - resource partitions. + A version of pjit that uses NamedArrays and the provided resource mapping to infer the resource partitions. If no resource mapping is provided, this function attempts to use the global resource mapping. - axis_resources will be used for a context-specific resource mapping as well as in_axis_resources and out_axis_resources - if they are not provided. + axis_resources will be used for a context-specific resource mapping. In addition, if in_axis_resources is not + provided, the arguments' own (pre-existing) shardings will be used as the in_axis_resources. + If out_axis_resources is not provided, axis_resources will be used as the out_axis_resources. - :param fn: The function to be pjit'd + :param fn: The function to be jit'd :param axis_resources: A mapping from logical axis names to physical axis names - :param in_axis_resources: A mapping from logical axis names to physical axis names for arguments, defaults to axis_resources + :param in_axis_resources: A mapping from logical axis names to physical axis names for arguments. If not passed, it uses the arguments' own shardings :param out_axis_resources: A mapping from logical axis names to physical axis names for the result, defaults to axis_resources :param donate_args: A PyTree of booleans or function leaf->bool, indicating whether to donate arguments to the computation :param donate_kwargs: A PyTree of booleans or function leaf->bool, indicating whether to donate keyword arguments to the computation """ - # TODO: support jax.Array if fn is None: return functools.partial( - named_pjit, + named_jit, axis_resources=axis_resources, in_axis_resources=in_axis_resources, out_axis_resources=out_axis_resources, @@ -208,25 +224,18 @@ def named_pjit( **pjit_args, ) - if axis_resources is None: - axis_resources = _mapping_holder.thread_data.resource_mapping - - if in_axis_resources is None: - in_axis_resources = axis_resources + @functools.wraps(fn) + def f(*args, **kwargs): + nonlocal axis_resources, in_axis_resources, out_axis_resources, donate_args, donate_kwargs - if out_axis_resources is None: - out_axis_resources = axis_resources + if axis_resources is None: + axis_resources = _mapping_holder.thread_data.resource_mapping - if axis_resources is None and (in_axis_resources is None or out_axis_resources is None): - raise ValueError( - "Must provide axis_resources, or in_axis_resources and out_axis_resources," - " or have a global mapping via axis_mapping" - ) + if out_axis_resources is None: + out_axis_resources = axis_resources - dynamic_fun, static_fun = hashable_partition(fn, is_jax_array_like) + dynamic_fun, static_fun = hashable_partition(fn, is_jax_array_like) - @functools.wraps(fn) - def f(*args, **kwargs): dynamic_argspec, static_argspec = hashable_partition((args, kwargs), is_jax_array_like) dynamic = (dynamic_fun, dynamic_argspec) @@ -249,14 +258,19 @@ def named_pjit( static = (static_fun, static_argspec) output_shape = _cached_filter_eval_shape(fn, *args, **kwargs) - # TODO: with new jax.Array I shouldn't have to specify shardings, but I do... - in_resources = infer_resource_partitions((dynamic_donated, dynamic_reserved), in_axis_resources) + # TODO: with new jax.Array I shouldn't have to specify shardings, but I do for now + # https://github.com/google/jax/issues/15600 + # we don't really need in_shardings though + my_pjit_args = dict(**pjit_args) + + if in_axis_resources is not None: + in_resources = infer_resource_partitions((dynamic_donated, dynamic_reserved), in_axis_resources) + my_pjit_args["in_shardings"] = in_resources + out_resources = infer_resource_partitions(output_shape, out_axis_resources) + my_pjit_args["out_shardings"] = out_resources - my_pjit_args = dict(**pjit_args) - my_pjit_args["in_axis_resources"] = in_resources - my_pjit_args["out_axis_resources"] = out_resources - with axis_mapping(axis_resources or {}): + with axis_mapping(axis_resources): cached_pjitted_fun = _named_pjit_cache(get_fun_names(fn), **my_pjit_args) return cached_pjitted_fun(dynamic_donated, dynamic_reserved, static) @@ -294,6 +308,7 @@ def _named_pjit_cache(fun_names, **jitkwargs): fun_wrapped.__name__ = fun_name fun_wrapped.__qualname__ = fun_qualname + # TODO: jit should work here, but there's a weird error. see if it goes away on its own return pjit(fun_wrapped, donate_argnums=0, static_argnums=2, **jitkwargs) @@ -378,7 +393,7 @@ __all__ = [ "axis_mapping", "auto_sharded", "infer_resource_partitions", - "named_pjit", + "named_jit", "physical_axis_name", "pspec_for_axis", "round_axis_for_partitioning", diff --git a/tests/test_partitioning.py b/tests/test_partitioning.py index 9b2d9b5..06c9b25 100644 --- a/tests/test_partitioning.py +++ b/tests/test_partitioning.py @@ -10,7 +10,7 @@ from test_utils import skip_if_not_enough_devices import haliax as hax from haliax import Axis, NamedArray -from haliax.partitioning import ResourceAxis, axis_mapping, infer_resource_partitions, named_pjit +from haliax.partitioning import ResourceAxis, axis_mapping, infer_resource_partitions, named_jit class MyModule(eqx.Module): @@ -30,12 +30,15 @@ resource_map = { def test_infer_named_axes(): - with axis_mapping(resource_map): + mesh = Mesh(np.array(jax.devices()).reshape(-1, 1), (ResourceAxis.DATA, ResourceAxis.MODEL)) + with axis_mapping(resource_map), mesh: mod = MyModule(named=hax.ones((Dim1, Dim2, Dim3)), unnamed1=jnp.ones(Dim2.size), static_field=1) axes: MyModule = infer_resource_partitions(mod) - assert axes.named.array == PartitionSpec(None, ResourceAxis.DATA, ResourceAxis.MODEL) + spec = PartitionSpec(None, ResourceAxis.DATA, ResourceAxis.MODEL) + + assert axes.named.array == NamedSharding(mesh, spec) assert axes.unnamed1 is None or isinstance(axes.unnamed1, SingleDeviceSharding) @@ -56,8 +59,8 @@ class MyModuleInit(eqx.Module): def test_pjit_class_init(): with axis_mapping(resource_map): devices = jax.devices() - with pxla.Mesh(np.array(devices).reshape(-1, 2), (ResourceAxis.DATA, ResourceAxis.MODEL)): - mod = named_pjit(MyModuleInit)() + with Mesh(np.array(devices).reshape(-1, 2), (ResourceAxis.DATA, ResourceAxis.MODEL)): + mod = named_jit(MyModuleInit)() assert mod.named.array.shape == (Dim2.size, Dim3.size) @@ -76,8 +79,8 @@ def test_pjit_class_nested_init(): self.inner = MyModuleInit() devices = jax.devices() - with pxla.Mesh(np.array(devices).reshape(-1, 2), (ResourceAxis.DATA, ResourceAxis.MODEL)): - mod2 = named_pjit(Mod2)() + with Mesh(np.array(devices).reshape(-1, 2), (ResourceAxis.DATA, ResourceAxis.MODEL)): + mod2 = named_jit(Mod2)() mod = mod2.inner assert mod.named.array.shape == (Dim2.size, Dim3.size) @@ -97,8 +100,8 @@ def test_pjit_class_init_with_args(): self.array2 = hax.zeros(Dim3) devices = jax.devices() - with pxla.Mesh(np.array(devices).reshape(-1, 1), (ResourceAxis.DATA, ResourceAxis.MODEL)): - mod = named_pjit(ModWithArgs)(hax.ones((Dim1, Dim2))) + with Mesh(np.array(devices).reshape(-1, 1), (ResourceAxis.DATA, ResourceAxis.MODEL)): + mod = named_jit(ModWithArgs)(hax.ones((Dim1, Dim2))) assert isinstance(mod, ModWithArgs) assert mod.array.array.shape == (Dim1.size, Dim2.size) assert mod.array2.array.shape == (Dim3.size,) @@ -113,7 +116,7 @@ def test_infer_resource_partition_gda_bug(): def foo(): return hax.zeros((Dim1, Dim2, Dim3)) - pjit_foo = named_pjit(foo, resource_map) + pjit_foo = named_jit(foo, resource_map) r = pjit_foo() assert r.axes == (Dim1, Dim2, Dim3) @@ -121,7 +124,7 @@ def test_infer_resource_partition_gda_bug(): return x # this won't work with GDAs - pjit_bar = named_pjit(bar, resource_map) + pjit_bar = named_jit(bar, resource_map) r = pjit_bar(r) assert r.axes == (Dim1, Dim2, Dim3) commit 9c84f60217dad098dc6b29dec7edc84be2c64781 Date: 2023-05-23T12:33:07-07:00 don't require out_axis_resources for named_jit diff --git a/src/haliax/partitioning.py b/src/haliax/partitioning.py index 7cacb0a..e5c480f 100644 --- a/src/haliax/partitioning.py +++ b/src/haliax/partitioning.py @@ -267,8 +267,9 @@ def named_jit( in_resources = infer_resource_partitions((dynamic_donated, dynamic_reserved), in_axis_resources) my_pjit_args["in_shardings"] = in_resources - out_resources = infer_resource_partitions(output_shape, out_axis_resources) - my_pjit_args["out_shardings"] = out_resources + if out_axis_resources is not None: + out_resources = infer_resource_partitions(output_shape, out_axis_resources) + my_pjit_args["out_shardings"] = out_resources with axis_mapping(axis_resources): cached_pjitted_fun = _named_pjit_cache(get_fun_names(fn), **my_pjit_args) commit a3277ece21b2e68df1dbc57df4e2c415f6246c40 Date: 2023-05-23T13:38:21-07:00 don't use a context manager if we don't have an axis_resources diff --git a/src/haliax/partitioning.py b/src/haliax/partitioning.py index e5c480f..586ec18 100644 --- a/src/haliax/partitioning.py +++ b/src/haliax/partitioning.py @@ -271,7 +271,12 @@ def named_jit( out_resources = infer_resource_partitions(output_shape, out_axis_resources) my_pjit_args["out_shardings"] = out_resources - with axis_mapping(axis_resources): + if axis_resources is not None: + cmanager = axis_mapping(axis_resources) + else: + cmanager = contextlib.nullcontext() + + with cmanager: cached_pjitted_fun = _named_pjit_cache(get_fun_names(fn), **my_pjit_args) return cached_pjitted_fun(dynamic_donated, dynamic_reserved, static) diff --git a/tests/test_partitioning.py b/tests/test_partitioning.py index 06c9b25..c877d9b 100644 --- a/tests/test_partitioning.py +++ b/tests/test_partitioning.py @@ -144,3 +144,24 @@ def test_shard_with_axis_mapping_outside_pjit(): y = hax.shard_with_axis_mapping(y, resource_map) assert y.array.sharding == NamedSharding(mesh, PartitionSpec(ResourceAxis.DATA, ResourceAxis.MODEL)) + + +def test_named_jit_works_without_axis_resources(): + devices = jax.devices() + with Mesh(np.array(devices).reshape(-1, 1), (ResourceAxis.DATA, ResourceAxis.MODEL)) as mesh: + + def foo(x): + return x + + pjit_foo = named_jit(foo) + r = pjit_foo(hax.ones((Dim1, Dim2))) + + assert r.array.sharding.is_fully_replicated + + def foo2(x): + return hax.shard_with_axis_mapping(x, resource_map) + + pjit_foo2 = named_jit(foo2) + r2 = pjit_foo2(hax.ones((Dim1, Dim2))) + + assert r2.array.sharding.is_equivalent_to(NamedSharding(mesh, PartitionSpec(None, ResourceAxis.DATA)), ndim=2) commit a3694ea3360b5b9fb8f70fd758d41eb7bac5bc15 Date: 2023-05-23T22:06:14-07:00 Add rows_per_chunk as a config (#153) diff --git a/.gitignore b/.gitignore index b07acad..57dd433 100644 --- a/.gitignore +++ b/.gitignore @@ -142,4 +142,7 @@ dmypy.json ledger.json /checkpoints -*.jaxpr \ No newline at end of file +*.jaxpr + +# local execution commands +local_*.sh commit b9c3e39eee6c21d9693dd6c67feff4a193fdc245 Date: 2023-05-23T22:43:58-07:00 Update README.md (#159) * Update README.md * typo * more updates * more change * add an example diff --git a/README.md b/README.md index 80e7205..6f4d716 100644 --- a/README.md +++ b/README.md @@ -1,30 +1,106 @@ -# Levanter +# Levanter and Haliax -> You could not prevent a thunderstorm, but you could use the electricity; you could not direct the wind, but you could trim your sail so as to propel your vessel as you pleased, no matter which way the wind blew. <br/> -> — Cora L. V. Hatch +Levanter and Haliax are libraries based on [Jax](https:://github.com/google/jax) and [Equinox](https://github.com/patrick-kidger/equinox) +for training deep learning models, especially [foundation models](https://en.wikipedia.org/wiki/Foundation_models). +Haliax is a named tensor library (modeled on [Tensor Considered Harmful](https://nlp.seas.harvard.edu/NamedTensor)) that focuses on improving the legibility and compositionality of deep learning code while still maintaining efficiency and scalability. +Levanter is a library for training foundation models built on top of Haliax. +In addition to the goals of legibility, efficiency, and scalability, Levanter further strives for bitwise reproducibility, +meaning that the same code with the same data will produce the exact same result, even in the presence of preemption and restarting from checkpoints. - -Levanter is a library based on [Jax](https:://github.com/google/jax) and [Equinox](https://github.com/patrick-kidger/equinox) -for training [foundation models](https://en.wikipedia.org/wiki/Foundation_models) created by [Stanford's Center for Research -on Foundation Models (CRFM)](https://crfm.stanford.edu/). +Levanter and Haliax were created by [Stanford's Center for Research on Foundation Models (CRFM)](https://crfm.stanford.edu/)'s research engineering team. ([We're hiring!](https://crfm.stanford.edu/apply.html)) ## Haliax > Though you don’t seem to be much for listening, it’s best to be careful. If you managed to catch hold of even just a piece of my name, you’d have all manner of power over me.<br/> > — Patrick Rothfuss, *The Name of the Wind* -Haliax is a module (currently) inside Levanter for named tensors, modeled on Alexander Rush's [Tensor Considered Harmful](https://arxiv.org/abs/1803.09868). -It's designed to work with Jax and Equinox to make constructing distributed models easier. +Haliax is a Jax library for building neural networks with named tensors, in the tradition of Alexander Rush's [Tensor Considered Harmful](https://nlp.seas.harvard.edu/NamedTensor). +We use named tensors to improve the legibility and compositionality of our programs without sacrificing performance or scalability. + +Here's a minimal attention module implementation in Haliax. For a more detailed introduction, please see the [Haliax tutorial](https://colab.research.google.com/drive/1TiTcQQ4V5mopbgCu1SVl-oqJtXn7rFnC). + +```python +import equinox as eqx +import jax +import jax.numpy as jnp +import haliax as hax +import haliax.nn as hnn + +Pos = hax.Axis("position", 1024) # sequence length +KPos = Pos.alias("key_position") +Head = hax.Axis("head", 8) # number of attention heads +Key = hax.Axis("key", 64) # key size +Embed = hax.Axis("embed", 512) # embedding size + +def attention_scores(Key, KPos, query, key, mask): + # how similar is each query to each key + scores = hax.dot(Key, query, key) / jnp.sqrt(Key.size) + + if mask is not None: + scores -= 1E9 * (1.0 - mask) + # convert to probabilities + scores = hax.nn.softmax(scores, KPos) + return scores -## Getting Started with Levanter -### Installation +def attention(Key, KPos, query, key, value, mask): + scores = attention_scores(Key, KPos, query, key, mask) + answers = hax.dot(KPos, scores, value) -First install the appropriate version of Jax for your system. See [Jax's installation instructions](https://github.com/google/jax/blob/main/README.md#installation) -as it varies from platform to platform. + return answers -If you're using a TPU, more complete documentation for setting that up is available [here](docs/Getting-Started-TPU-VM.md). +# Causal Mask means that if pos >= key_pos, then pos can attend to key_pos +causal_mask = hax.arange(Pos).broadcast_axis(KPos) >= hax.arange(KPos) + +class Attention(eqx.Module): + proj_qkv: hnn.Linear # input projection from [Embed] -> [(q, k, v), Head, Key] + proj_answer: hnn.Linear # output projection from [Head, Key] -> [Embed] + + @staticmethod + def init(Embed, Head, Key, *, key): + Qkv = hax.Axis("qkv", 3) # create all three at once + + k_qkv, k_ans = jax.random.split(key, 2) + proj_qkv = hnn.Linear.init(In=Embed, Out=(Qkv, Head, Key), key=k_qkv) + proj_answer = hnn.Linear.init(In=(Head, Key), Out=Embed, key=k_ans) + return Attention(proj_qkv, proj_answer) + + def __call__(self, x, mask=None): + qkv_out = self.proj_qkv(x) + q, k, v = qkv_out.unbind("qkv") + + # Rename k and v's Pos as haliax doesn't support unnamed axes or duplicate axes + k = k.rename({"position": "key_position"}) + v = v.rename({"position": "key_position"}) + + answers = attention(Key, KPos, q, k, v, causal_mask) + + x = self.proj_answer(answers) + return x +``` + +### Documentation for Haliax + +Currently we have two tutorials for Haliax: +* [Introduction to Haliax with Transformers](https://colab.research.google.com/drive/1TiTcQQ4V5mopbgCu1SVl-oqJtXn7rFnC) +* [Distributed Training in Haliax](https://colab.research.google.com/drive/1QX4yH3zRFF3Xiibf1aahETcSQ5nbcUMz) (including FSDP) + +## Levanter + +> You could not prevent a thunderstorm, but you could use the electricity; you could not direct the wind, but you could trim your sail so as to propel your vessel as you pleased, no matter which way the wind blew. <br/> +> — Cora L. V. Hatch + +Levanter is a library for training foundation models built on top of Haliax. Levanter strives for bitwise reproducibility, +meaning that the same code with the same data will produce the exact same result, even in the presence of preemption and restarting from checkpoints. +It supports distributed training on TPUs (and, soon, GPUs), including FSDP, tensor parallelism, distributed checkpointing, distributed data loading, and more. +Levanter integrates with WandB for logging and with the Hugging Face ecosystem for tokenizers, datasets, and model import and export. + +### Installing Levanter + +First, install the appropriate version of Jax for your system. See [Jax's installation instructions](https://github.com/google/jax/blob/main/README.md#installation) as it varies from platform to platform. + +If you're using a TPU, more complete documentation for setting that up is available [here](docs/Getting-Started-TPU-VM.md). GPU support is still in-progress; documentation is available [here](docs/Getting-Started-CUDA.md). Now clone this repository and install it with pip: @@ -37,7 +113,6 @@ wandb login # optional, we use wandb for logging TODO: put things on pypi, etc - ### Training a GPT2-nano As a kind of hello world, here's how you can train a GPT-2 "nano"-sized model on a small dataset. @@ -49,8 +124,10 @@ python examples/gpt2_example.py --config_path config/gpt2_nano.yaml This will train a GPT2-nano model on the [WikiText-2](https://blog.einstein.ai/the-wikitext-long-term-dependency-language-modeling-dataset/) dataset. You can change the dataset by changing the `dataset` field in the config file. -The config file is a [Pyrallis](https://github.com/eladrich/pyrallis) config file. Pyrallis is yet-another yaml-to-dataclass library. -You can use `--help` or poke around other configs to see all the options available to you. +For more information about the various configuration options, please see the [Training Getting Started](docs/Getting-Started-Training.md) guide. +You can also use `--help` or poke around other configs to see all the options available to you. + + #### Training on a TPU Cloud VM commit 8dbad4b16d03478858ab50ae04e0a15cdb6aa55b Date: 2023-05-25T15:01:08-07:00 Fix sharding on cpu (#164) * mucking around with sharding b/c of some weird behavior on cpu * fix test for named_jit * fix test diff --git a/src/haliax/partitioning.py b/src/haliax/partitioning.py index 586ec18..72011ab 100644 --- a/src/haliax/partitioning.py +++ b/src/haliax/partitioning.py @@ -13,7 +13,7 @@ from jax._src.sharding_impls import AUTO from jax.experimental.pjit import pjit from jax.interpreters.pxla import PartitionSpec from jax.lax import with_sharding_constraint -from jax.sharding import Mesh +from jax.sharding import Mesh, NamedSharding, SingleDeviceSharding from jaxtyping import PyTree from .core import NamedArray @@ -173,11 +173,14 @@ def infer_resource_partitions( if current_sharding is not None: return NamedArray(current_sharding, node.axes) # type: ignore else: - sharding = jax.sharding.NamedSharding(mesh, pspec_for_axis(node.axes, resource_mapping)) + sharding = NamedSharding(mesh, pspec_for_axis(node.axes, resource_mapping)) return NamedArray(sharding, node.axes) # type: ignore else: sharding = _auto_array_sharding(node) - if sharding is not None: + # TODO: these are usually replicated. Is there a better way to tell? + if isinstance(sharding, SingleDeviceSharding): + return NamedSharding(mesh, PartitionSpec(None)) + elif sharding is not None: return sharding else: return AUTO @@ -248,6 +251,10 @@ def named_jit( dargs = tuple(donate_args) else: dargs = donate_args + + if len(dargs) != len(args): + raise ValueError(f"Expected {len(args)} donate_args, got {len(dargs)}") + dkwargs = donate_kwargs or {k: False for k in kwargs} dkwargs = {k: dkwargs.get(k, False) for k in kwargs} dynamic_donated, dynamic_reserved = eqx.partition(dynamic, (False, (dargs, dkwargs))) @@ -263,8 +270,13 @@ def named_jit( # we don't really need in_shardings though my_pjit_args = dict(**pjit_args) - if in_axis_resources is not None: - in_resources = infer_resource_partitions((dynamic_donated, dynamic_reserved), in_axis_resources) + if in_axis_resources is not None or axis_resources is not None: + in_axis_resources = in_axis_resources or axis_resources + in_resources = infer_resource_partitions( + (dynamic_donated, dynamic_reserved), + in_axis_resources, + preserve_existing_shardings=in_axis_resources is None, + ) my_pjit_args["in_shardings"] = in_resources if out_axis_resources is not None: diff --git a/tests/test_partitioning.py b/tests/test_partitioning.py index c877d9b..143192c 100644 --- a/tests/test_partitioning.py +++ b/tests/test_partitioning.py @@ -4,7 +4,7 @@ import jax.numpy as jnp import numpy as np from jax.interpreters import pxla from jax.interpreters.pxla import PartitionSpec -from jax.sharding import Mesh, NamedSharding, SingleDeviceSharding +from jax.sharding import Mesh, NamedSharding from jaxtyping import Array from test_utils import skip_if_not_enough_devices @@ -39,7 +39,7 @@ def test_infer_named_axes(): spec = PartitionSpec(None, ResourceAxis.DATA, ResourceAxis.MODEL) assert axes.named.array == NamedSharding(mesh, spec) - assert axes.unnamed1 is None or isinstance(axes.unnamed1, SingleDeviceSharding) + assert axes.unnamed1.is_fully_replicated class MyModuleInit(eqx.Module): commit f3e8cc548cce7f7056d87114a07dfb2ac63cb17f Date: 2023-05-30T22:49:58-07:00 Fixed auto_sharded outside of pjit (#170) * fix device_put, again * fix for named array args * add a test inside pjit * fix shard-inside-pjit test for new jit diff --git a/src/haliax/partitioning.py b/src/haliax/partitioning.py index 72011ab..cfa7b63 100644 --- a/src/haliax/partitioning.py +++ b/src/haliax/partitioning.py @@ -7,7 +7,6 @@ from typing import Mapping, Optional, Sequence, TypeVar, Union import equinox as eqx import jax -import jax.numpy as jnp from equinox.compile_utils import compile_cache, get_fun_names, hashable_combine, hashable_partition from jax._src.sharding_impls import AUTO from jax.experimental.pjit import pjit @@ -94,24 +93,14 @@ def shard_with_axis_mapping(x: T, mapping: ResourceMapping, mesh: Optional[Mesh] resulting sharding spans more than one host. """ - if _is_jit_context(): - - def _shard_leaf(x): - if isinstance(x, NamedArray): - pspec = pspec_for_axis(x.axes, mapping) - return with_sharding_constraint(x, pspec) - else: - return x - - return jax.tree_util.tree_map(_shard_leaf, x, is_leaf=is_named_array) - else: - # use device_put or make_array_from_callback instead - mesh = mesh or _get_mesh() - - def _do_device_put(x): - if not is_named_array(x): - return x + def _do_device_put(x): + if not is_named_array(x): + return x + if _is_jit_tracer(x.array): + pspec = pspec_for_axis(x.axes, mapping) + return with_sharding_constraint(x, pspec) + else: raw_x = x.array current_sharding = raw_x.sharding @@ -132,7 +121,7 @@ def shard_with_axis_mapping(x: T, mapping: ResourceMapping, mesh: Optional[Mesh] raw_x = jax.make_array_from_callback(shape, desired_sharding, lambda index: raw_x[index]) return NamedArray(raw_x, x.axes) - return jax.tree_util.tree_map(_do_device_put, x, is_leaf=is_named_array) + return jax.tree_util.tree_map(_do_device_put, x, is_leaf=is_named_array) def infer_resource_partitions( @@ -271,7 +260,8 @@ def named_jit( my_pjit_args = dict(**pjit_args) if in_axis_resources is not None or axis_resources is not None: - in_axis_resources = in_axis_resources or axis_resources + if in_axis_resources is None: + in_axis_resources = axis_resources in_resources = infer_resource_partitions( (dynamic_donated, dynamic_reserved), in_axis_resources, @@ -398,8 +388,10 @@ def _get_mesh(): return thread_resources.env.physical_mesh -def _is_jit_context(): - return isinstance(jnp.zeros(1), jax.core.Tracer) +def _is_jit_tracer(x) -> bool: + if isinstance(x, NamedArray): + x = x.array + return isinstance(x, jax.core.Tracer) __all__ = [ diff --git a/tests/test_partitioning.py b/tests/test_partitioning.py index 143192c..4f0a3a5 100644 --- a/tests/test_partitioning.py +++ b/tests/test_partitioning.py @@ -165,3 +165,32 @@ def test_named_jit_works_without_axis_resources(): r2 = pjit_foo2(hax.ones((Dim1, Dim2))) assert r2.array.sharding.is_equivalent_to(NamedSharding(mesh, PartitionSpec(None, ResourceAxis.DATA)), ndim=2) + + +@skip_if_not_enough_devices(4) +def test_shard_with_axis_mapping_inside_jit(): + devices = jax.devices() + with Mesh(np.array(devices).reshape(-1, 2), (ResourceAxis.DATA, ResourceAxis.MODEL)) as mesh: + x = hax.ones((Dim1, Dim2)) + y = hax.ones((Dim2, Dim3)) + + def assert_inside_pjit(arr, expected: NamedSharding): + def assert_eq(x, y): + assert x == y + + jax.debug.inspect_array_sharding(arr.array, callback=lambda x: assert_eq(x, expected)) + + @named_jit(in_axis_resources={}, out_axis_resources=resource_map) + def do_shard(x, y): + x = hax.shard_with_axis_mapping(x, resource_map) + assert_inside_pjit(x, NamedSharding(mesh, PartitionSpec(None, ResourceAxis.DATA))) + + y = hax.shard_with_axis_mapping(y, resource_map) + assert_inside_pjit(y, NamedSharding(mesh, PartitionSpec(ResourceAxis.DATA, ResourceAxis.MODEL))) + + return x, y + + x, y = do_shard(x, y) + + assert x.array.sharding == NamedSharding(mesh, PartitionSpec(None, ResourceAxis.DATA)) + assert y.array.sharding == NamedSharding(mesh, PartitionSpec(ResourceAxis.DATA, ResourceAxis.MODEL)) commit 61fb8500395b8f4a4551368f5585b35833dd3abf Date: 2023-06-01T12:27:19-07:00 Partitioned Random and Embedding.init (#163) * allow arbitrary jax config settings, set threefry_partitionable by default * don't use generate_sharded now that we have threefry_partitionable * don't use sharded_normal in hax.random diff --git a/.flake8 b/.flake8 index e856b50..d067c43 100644 --- a/.flake8 +++ b/.flake8 @@ -1,7 +1,7 @@ [flake8] exclude = .git -max-line-length = 119 -ignore = E203, E501, W503, W605, F821 +max-line-length = 120 +ignore = E203, E501, W503, W605, F821, E266 per-file-ignores = */__init__.py: F401 examples/*.py: E402 diff --git a/src/haliax/nn/embedding.py b/src/haliax/nn/embedding.py index fccde93..9215bda 100644 --- a/src/haliax/nn/embedding.py +++ b/src/haliax/nn/embedding.py @@ -13,20 +13,11 @@ class Embedding(eqx.Module): Vocab: Axis = eqx.static_field() Embed: Axis = eqx.static_field() - def __init__( - self, - Vocab: Axis, - Embed: Axis, - initializer_range: float = 0.02, - *, - key, - ): - super().__init__() - - self.Vocab = Vocab - self.Embed = Embed - - self.weight = hax.random.generate_sharded(hax.random.normal)(key, (Vocab, Embed)) * initializer_range + # TODO: should allow axisspec for Embed + @staticmethod + def init(Vocab: Axis, Embed: Axis, initializer_range: float = 0.02, *, key): + weight = hax.random.normal(key, (Vocab, Embed)) * initializer_range + return Embedding(weight=weight, Vocab=Vocab, Embed=Embed) @named_call def __call__(self, input_ids, inference, *, key): diff --git a/src/haliax/nn/linear.py b/src/haliax/nn/linear.py index 1a10db2..ec95106 100644 --- a/src/haliax/nn/linear.py +++ b/src/haliax/nn/linear.py @@ -22,7 +22,7 @@ class Linear(eqx.Module): @staticmethod def init(In: AxisSpec, Out: AxisSpec, *, key, use_bias=True) -> "Linear": joint_spec = hax.concat_axis_specs(In, Out) - weight = hax.random.generate_sharded(hax.random.normal)(key, joint_spec) * 0.02 + weight = hax.random.normal(key, joint_spec) * 0.02 bias = hax.zeros(Out) if use_bias else None return Linear(weight, bias, In, Out) commit 291355559e6c76d6dcbaa14c0af18956f0565d44 Date: 2023-06-04T21:24:44-07:00 Fixes imports for Jax 0.4.10->0.4.11 (#179) * update for jax 0.4.11, fixes #178 * fix 0.4.10 * fix #175 (and #178) diff --git a/src/haliax/partitioning.py b/src/haliax/partitioning.py index cfa7b63..1473199 100644 --- a/src/haliax/partitioning.py +++ b/src/haliax/partitioning.py @@ -10,9 +10,8 @@ import jax from equinox.compile_utils import compile_cache, get_fun_names, hashable_combine, hashable_partition from jax._src.sharding_impls import AUTO from jax.experimental.pjit import pjit -from jax.interpreters.pxla import PartitionSpec from jax.lax import with_sharding_constraint -from jax.sharding import Mesh, NamedSharding, SingleDeviceSharding +from jax.sharding import Mesh, NamedSharding, PartitionSpec, SingleDeviceSharding from jaxtyping import PyTree from .core import NamedArray @@ -128,6 +127,7 @@ def infer_resource_partitions( tree: PyTree, resource_mapping: Optional[ResourceMapping] = None, preserve_existing_shardings: bool = True, + use_auto_sharding: bool = True, mesh: Optional[Mesh] = None, ) -> PyTree: """ @@ -137,6 +137,10 @@ def infer_resource_partitions( If preserve_existing_shardings is True, then NamedArrays that are already sharded are left alone. If resource_mapping is not provided, this function attempts to use the global resource mapping. + + If use_auto_sharding is True, then we use the new experimental AUTO-sharding feature, which is not yet + fully supported by JAX. If it is False, then we will guess fully replicated for any unnamed arrays that + don't have a sharding. """ if resource_mapping is None: resource_mapping = _mapping_holder.thread_data.resource_mapping @@ -171,8 +175,16 @@ def infer_resource_partitions( return NamedSharding(mesh, PartitionSpec(None)) elif sharding is not None: return sharding - else: - return AUTO + elif node.shape == (): + return NamedSharding(mesh, PartitionSpec()) + elif use_auto_sharding: + # TODO: auto doesn't seem to really work reliably yet + # compat between 0.4.10 and 0.4.11 + if isinstance(AUTO, typing.Callable): # type: ignore + return AUTO(mesh) + else: + return AUTO + return NamedSharding(mesh, PartitionSpec(None)) return jax.tree_util.tree_map(partition_spec, tree, is_leaf=is_named_array) @@ -270,7 +282,8 @@ def named_jit( my_pjit_args["in_shardings"] = in_resources if out_axis_resources is not None: - out_resources = infer_resource_partitions(output_shape, out_axis_resources) + # TODO: when AUTO is fixed (or eval_shape can give shardings), use it here + out_resources = infer_resource_partitions(output_shape, out_axis_resources, use_auto_sharding=False) my_pjit_args["out_shardings"] = out_resources if axis_resources is not None: diff --git a/tests/test_partitioning.py b/tests/test_partitioning.py index 4f0a3a5..dffbc4a 100644 --- a/tests/test_partitioning.py +++ b/tests/test_partitioning.py @@ -2,9 +2,7 @@ import equinox as eqx import jax import jax.numpy as jnp import numpy as np -from jax.interpreters import pxla -from jax.interpreters.pxla import PartitionSpec -from jax.sharding import Mesh, NamedSharding +from jax.sharding import Mesh, NamedSharding, PartitionSpec from jaxtyping import Array from test_utils import skip_if_not_enough_devices @@ -109,7 +107,7 @@ def test_pjit_class_init_with_args(): def test_infer_resource_partition_gda_bug(): devices = jax.devices() - with pxla.Mesh(np.array(devices).reshape(-1, 1), (ResourceAxis.DATA, ResourceAxis.MODEL)): + with Mesh(np.array(devices).reshape(-1, 1), (ResourceAxis.DATA, ResourceAxis.MODEL)): jax.config.update("jax_parallel_functions_output_gda", True) try: @@ -194,3 +192,35 @@ def test_shard_with_axis_mapping_inside_jit(): assert x.array.sharding == NamedSharding(mesh, PartitionSpec(None, ResourceAxis.DATA)) assert y.array.sharding == NamedSharding(mesh, PartitionSpec(ResourceAxis.DATA, ResourceAxis.MODEL)) + + +def test_shard_scalar_in_module(): + with axis_mapping(resource_map): + + class MyModule(eqx.Module): + scalar: jnp.ndarray + + def __init__(self): + self.scalar = jnp.zeros( + (), + ) + + devices = jax.devices() + with Mesh(np.array(devices).reshape(-1, 1), (ResourceAxis.DATA, ResourceAxis.MODEL)): + mod = named_jit(MyModule)() + assert mod.scalar.sharding.is_fully_replicated + + +def test_shard_plain_array_in_module(): + with axis_mapping(resource_map): + + class MyModule(eqx.Module): + array: jnp.ndarray + + def __init__(self): + self.array = jnp.zeros((8, 8)) + + devices = jax.devices() + with Mesh(np.array(devices).reshape(-1, 1), (ResourceAxis.DATA, ResourceAxis.MODEL)): + mod = named_jit(MyModule)() + assert mod.array.sharding.is_fully_replicated commit 5af161d8512f9c8060c31a2d42d815b33a411895 Date: 2023-06-06T21:38:00-07:00 First steps to pypi package (#181) * initial cut at pyproject.toml * remove requirements.txt in favor of pyproject * pr comments diff --git a/pyproject.toml b/pyproject.toml index f473a39..0513aee 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -1,6 +1,61 @@ +[build-system] +requires = ["setuptools>=61.0"] +build-backend = "setuptools.build_meta" + +[project] +name = "levanter" +version = "0.0.1" +authors = [ + { name="David Hall", email="dlwh@cs.stanford.edu" }, + {name="Ivan Zhou", email="ivanz@stanford.edu"} +] +description = "Scalable Training for Foundation Models with Named Tensors and Jax" +readme = "README.md" +requires-python = ">=3.10" +classifiers = [ + "Programming Language :: Python :: 3", + "License :: OSI Approved :: Apache Software License 2.0", + "Operating System :: Linux", + "Operating System :: MacOS :: MacOS X", + "Development Status :: 3 - Alpha", + "Intended Audience :: Science/Research", +] + +dependencies = [ + # we'll require that you install jax yourself, since the extras vary by system. + # jax = {version = ">=0.4.10,<0.5.0"} + "equinox~=0.9.0", + "transformers>=4.22.0", + "optax", + "wandb", + "pyrallis>=0.3.1", + "pyarrow>=11.0.0", + "zstandard>=0.20.0", + "datasets==2.11.0", + "gcsfs==2023.3.0", + "braceexpand>=0.1.7", + "jmp>=0.0.3", + "fsspec==2023.3.0", # pin this to make gcsfs happy + "tensorstore>=0.1.36", + "pytimeparse>=1.1.8", + "humanfriendly==10.0", + "requests", + "safetensors[numpy]", + "matplotlib>=3.7.0", + "tblib>=1.7.0,<2.0.0", + "dataclasses_json", + "ray[default]", + "rich>=13", +] + +[project.urls] +"Homepage" = "https://github.com/stanford-crfm/levanter" +"Bug Tracker" = "https://github.com/stanford-crfm/levanter/issues" + + [tool.black] line-length = 119 -target-version = ["py36", "py37", "py38"] +target-version = ["py310"] experimental_string_processing = true [tool.isort] diff --git a/requirements.txt b/requirements.txt deleted file mode 100644 index dea82ef..0000000 --- a/requirements.txt +++ /dev/null @@ -1,22 +0,0 @@ -equinox~=0.9.0 -transformers>=4.22.0 -optax -wandb -pyrallis -pyarrow -zstandard -datasets==2.11.0 -gcsfs==2023.3.0 -braceexpand -jmp @ git+https://github.com/deepmind/jmp#7b3ae548154625a56a6dbdb03bc07d4f599c37b2 -fsspec==2023.3.0 # pin this to make gcsfs happy -tensorstore>=0.1.36 -pytimeparse -humanfriendly -requests -safetensors[numpy] -matplotlib -tblib -dataclasses_json -ray[default] -rich commit bf8cc5f9acc03993d9dbf7377622b41058a2a41d Date: 2023-06-06T23:45:04-07:00 MPT support (#188) * refactor to a callback interface * add wandb logging support * reuse functionality for await_finished * double remote by mistake * oops * dumb infinite loop * typo * botched rebase * botched rebase * stupid pycharm * wip * got torch->jax working * produces same results * full roundtrip * full roundtrip * rename * wip * update for latest transformers * wip continued training script for MPT * fix tests on CI * mpt_7b continued pretraining * allow {} for axis_resources * tweak axis resources * try this * cpu ram * allow shard_with_axis_mapping outside of pjit * use new shard_with_axis_mapping to shard the model directly * use array_from_callback when necessary for auto_sharded device_put doesn't work with non-fully-addressable target shardings * dumb * dumb (continued_training) * allow overriding sequence length, don't freak out about vocab size * visualize sharding * test for flatten/unflatten linear layer * dumb thinko in named_pjit * i'm so dumb * missed checkpointing * don't need vocab argument ot Transformer * log a warning * process the pile inband * unbotch the merge * add | to make it clearer what is what * some more logging * moar logging * moar logging:234 * dumb eval script for Mpt * fix loading of old-style caches * stupid * try to fix mpt_eval * fix device_put, again * fix for named array args * add a test inside pjit * finish named_jit rename * fix config * fix cache dir * missed migration step * sigh * klfjmaklf * i'm a dumb dumb * dkmasklfmaklfm print * add concatenate * add resize_axis to let us pad vocab and such * add support for patching vocab size * almost there * missed one * almost there * dumb dumb * dumb dumb * no viz for mpt right now * missed a key * dumb dumb * increase timeout just in case * update mpt_continued_training.py * oops * check more config options in Mpt, updating Embedding call * remove MPTConfig copypaste * add hf config export for Mpt --------- Co-authored-by: Ivan Zhou <ivan.zhouyq@gmail.com> diff --git a/requirements.txt b/requirements.txt new file mode 100644 index 0000000..e69de29 diff --git a/src/haliax/__init__.py b/src/haliax/__init__.py index 8d80679..1faf8ba 100644 --- a/src/haliax/__init__.py +++ b/src/haliax/__init__.py @@ -5,6 +5,7 @@ import jax.numpy as jnp import haliax.random as random from haliax import nn as nn +from haliax import tree_util as tree_util from .core import ( NamedArray, @@ -88,6 +89,29 @@ def stack(axis: AxisSelector, arrays: Sequence[NamedArray]) -> NamedArray: return NamedArray(jnp.stack([a.array for a in arrays], axis=0), (axis,) + arrays[0].axes) +def concatenate(axis: AxisSelector, arrays: Sequence[NamedArray]) -> NamedArray: + """Version of jnp.concatenate that returns a NamedArray""" + total_size = _sum(a.resolve_axis(axis).size for a in arrays) + if isinstance(axis, str): + axis = Axis(axis, total_size) + elif total_size != axis.size: + raise ValueError( + f"Cannot concatenate arrays along axis {axis.name} of size {axis.size} with total size {total_size}" + ) + + if len(arrays) == 0: + return zeros(axis) + + arrays = [a.rearrange(arrays[0].axes) for a in arrays] + axis_index = arrays[0]._lookup_indices(axis.name) + + if axis_index is None: + raise ValueError(f"Axis {axis.name} not found in 0th array {arrays[0]}") + + new_axes = arrays[0].axes[:axis_index] + (axis,) + arrays[0].axes[axis_index + 1 :] + return NamedArray(jnp.concatenate([a.array for a in arrays], axis=axis_index), new_axes) + + # elementwise unary operations abs = wrap_elemwise_unary(jnp.abs) absolute = wrap_elemwise_unary(jnp.absolute) @@ -180,6 +204,7 @@ ptp: ReductionFunction = wrap_reduction_call(jnp.ptp) product: ReductionFunction = wrap_reduction_call(jnp.product) sometrue: ReductionFunction = wrap_reduction_call(jnp.sometrue) std: ReductionFunction = wrap_reduction_call(jnp.std) +_sum = sum sum: ReductionFunction = wrap_reduction_call(jnp.sum) var: ReductionFunction = wrap_reduction_call(jnp.var) @@ -388,4 +413,6 @@ __all__ = [ "are_shape_checks_enabled", "isclose", "pad_left", + "stack", + "concatenate", ] diff --git a/src/haliax/nn/attention.py b/src/haliax/nn/attention.py index 3e4c1d6..06417fe 100644 --- a/src/haliax/nn/attention.py +++ b/src/haliax/nn/attention.py @@ -175,10 +175,13 @@ def forgetful_causal_mask(KPos: Axis, mask_prob: float, sample_prob: bool = True return base | zeroth_on -def _get_alibi_slopes(heads: int) -> List[float]: +def _get_alibi_slopes(heads: int, bias_max: float) -> List[float]: + # Mosaic supports "bias_max" + log_bias_max = math.log2(bias_max) # from https://github.com/ofirpress/attention_with_linear_biases/blob/a35aaca144e0eb6b789dfcb46784c4b8e31b7983/fairseq/models/transformer.py#L742 + def get_slopes_power_of_2(n: int): - start = 2 ** (-(2 ** -(math.log2(n) - 3))) + start = 2 ** (-(2 ** -(math.log2(n) - log_bias_max))) ratio = start return [start * ratio**i for i in range(n)] @@ -191,16 +194,16 @@ def _get_alibi_slopes(heads: int) -> List[float]: ) -def alibi_attention_bias(Heads: Axis, Pos: Axis, dtype=jnp.float32) -> NamedArray: +def alibi_attention_bias(Heads: Axis, KPos: Axis, bias_max: float = 8, dtype=jnp.float32) -> NamedArray: """ Creates an attention bias for alibi attention. - :param Pos: Axis of sequence length + :param KPos: Axis of (key) sequence length :param Heads: Axis of heads - :return: NamedArray of shape (Heads, QPos) + :return: NamedArray of shape (Heads, KPos) """ - slopes = haliax.named(np.array(_get_alibi_slopes(Heads.size)), Heads) - positions = haliax.arange(Pos).broadcast_axis(Heads) + slopes = haliax.named(np.array(_get_alibi_slopes(Heads.size, bias_max)), Heads) + positions = haliax.arange(KPos).broadcast_axis(Heads) biases = slopes * positions return biases.astype(dtype) diff --git a/src/haliax/tree_util.py b/src/haliax/tree_util.py new file mode 100644 index 0000000..da204da --- /dev/null +++ b/src/haliax/tree_util.py @@ -0,0 +1,49 @@ +import jax +from jax.random import PRNGKey +from jaxtyping import PyTree + +from .core import Axis, NamedArray +from .util import is_named_array + + +def resize_axis(tree: PyTree[NamedArray], axis: Axis, key: PRNGKey): + """Resizes the NamedArrays of a PyTree along a given axis. If the array needs to grow, then the new elements are + sampled from a truncated normal distribution with the same mean and standard deviation as the existing elements. + If the array needs to shrink, then it's truncated.""" + import haliax.random + + def _resize_one(x, key): + if not is_named_array(x): + return x + + assert isinstance(x, NamedArray) + + try: + current_axis = x.resolve_axis(axis.name) + except ValueError: + return x + + if axis.size == current_axis.size: + return x + elif current_axis.size > axis.size: + return x.slice(current_axis, axis) + else: + num_padding = axis.size - current_axis.size + + mean = x.mean(current_axis) + std = x.std(current_axis) + + # the shape of the padding is the same as the original array, except with the axis size changed + padding_axes = list(x.axes) + padding_axes[padding_axes.index(current_axis)] = axis.resize(num_padding) + + padding = haliax.random.truncated_normal(key, padding_axes, lower=-2, upper=2) * std + mean + + return haliax.concatenate(axis, [x, padding]) + + leaves, structure = jax.tree_util.tree_flatten(tree, is_leaf=is_named_array) + keys = jax.random.split(key, len(leaves)) + + new_leaves = [_resize_one(x, key) for x, key in zip(leaves, keys)] + + return jax.tree_util.tree_unflatten(structure, new_leaves) diff --git a/src/haliax/types.py b/src/haliax/types.py index 89c973c..72a4d43 100644 --- a/src/haliax/types.py +++ b/src/haliax/types.py @@ -14,6 +14,9 @@ class Axis: def alias(self, new_name: str): return Axis(new_name, self.size) + def resize(self, size): + return Axis(self.name, size) + AxisSelector = Union[Axis, str] """AxisSelector is a type that can be used to select a single axis from an array. str or Axis""" diff --git a/tests/core_test.py b/tests/core_test.py index ff957de..a5bd01b 100644 --- a/tests/core_test.py +++ b/tests/core_test.py @@ -341,6 +341,36 @@ def test_stack(): assert reord_stack.axes == (Axis("B", 2), H, W) +def test_concatenate(): + H1 = Axis("H", 4) + H2 = Axis("H", 3) + W = Axis("W", 3) + + named1 = hax.random.uniform(PRNGKey(0), (H1, W)) + named2 = hax.random.uniform(PRNGKey(1), (H2, W)) + + assert jnp.all( + jnp.equal(hax.concatenate("H", (named1, named2)).array, jnp.concatenate((named1.array, named2.array), axis=0)) + ) + assert hax.concatenate("H", (named1, named2)).axes == (Axis("H", 7), W) + + # test that this rearranges fine + named3 = hax.random.uniform(PRNGKey(2), (W, H2)) + reord_concat = hax.concatenate("H", (named1, named3)) + assert jnp.all( + jnp.equal(reord_concat.array, jnp.concatenate((named1.array, named3.array.transpose(1, 0)), axis=0)) + ) + + # test we can concatenate along the 2nd axis + named1 = named1.rearrange((W, H1)) + named2 = named2.rearrange((W, H2)) + + assert jnp.all( + jnp.equal(hax.concatenate("H", (named1, named2)).array, jnp.concatenate((named1.array, named2.array), axis=1)) + ) + assert hax.concatenate("H", (named1, named2)).axes == (W, Axis("H", 7)) + + def test_unflatten_axis(): H = Axis("Height", 2) W = Axis("Width", 3) diff --git a/tests/test_tree_util.py b/tests/test_tree_util.py new file mode 100644 index 0000000..0eb6ade --- /dev/null +++ b/tests/test_tree_util.py @@ -0,0 +1,36 @@ +import equinox as eqx +import jax +import jax.numpy as jnp + +import haliax as hax +import haliax.tree_util as htu +from haliax import Axis + + +def test_resize_axis(): + + A = hax.Axis("A", 10) + B = hax.Axis("B", 20) + C = hax.Axis("C", 30) + + class Module(eqx.Module): + name1: hax.NamedArray + name2: hax.NamedArray + name3: hax.NamedArray + + module = Module( + name1=hax.random.normal(jax.random.PRNGKey(0), (B, A, C)), + name2=hax.zeros((B, C)), + name3=hax.zeros((Axis("A", 20),)), + ) + + NewA = A.resize(15) + + module2 = htu.resize_axis(module, NewA, jax.random.PRNGKey(1)) + + assert module2.name1.axes == (B, NewA, C) + assert module2.name2.axes == (B, C) + assert module2.name3.axes == (NewA,) + + # we don't mess with the mean or std of the original array too much + assert jnp.allclose(module2.name1.mean().array, module.name1.mean().array, rtol=1e-1, atol=1e-2) commit e356dbdf899d7ee830492c2941a53234158dffe9 Date: 2023-06-08T16:40:46-07:00 Wire up on demand preprocessing (#174) diff --git a/src/haliax/partitioning.py b/src/haliax/partitioning.py index 1473199..7436c30 100644 --- a/src/haliax/partitioning.py +++ b/src/haliax/partitioning.py @@ -107,7 +107,7 @@ def shard_with_axis_mapping(x: T, mapping: ResourceMapping, mesh: Optional[Mesh] x, mapping, mesh=mesh, preserve_existing_shardings=False ).array - if current_sharding == desired_sharding: + if current_sharding.is_equivalent_to(desired_sharding, ndim=raw_x.ndim): return x elif desired_sharding.is_fully_addressable: raw_x = jax.device_put(raw_x, desired_sharding) commit 9cf79966178d9b04e351367ea3e03c7885abbcd2 Date: 2023-06-12T10:23:39-07:00 introduce HFCheckpointConverter to unify hf serialization (#191) * wip round trip test for backpacks * almost there * torch roundtrip * hf pretrained -> lev -> hf, but no lev.save_pretrained just yet * load tokenizer * abstract abc for HF compat configs * abstract abc for HF compat configs * more config abstraction * abstract out an LM class * wip moving gpt2 roundtrip to converter * converted loading of HF GPT checkpoints * fully convert loading of gpt2 checkpoints in tests * cleanup * wip saving local model * wip saving local model * saving to hf hub even * convert gpt2_eval to new serialization * rename to RepoRef * use the new converter for the checkpoint callback * fix black deprecation warning * convert convert_gpt2_to_hf.py to new converter lol convert * delete old gpt serialization methods * use converter more * use converter more for backpacks * use converter more for backpacks * docs * explicitly do ctor so we can do argument coercion * cut at code and tokenizer saving * convert MPT to the new regime * test saving for things that need code * double check HF serialization * bring back code saving, since i think it's necessary for backpacks, but not mpt * almost there? * docs * missing import * docs * add a replace and config overrides method * fix frozen * fix tests * fix tests, rename LmWithHFSer * vocab size patching * skip if no torch * Fix backpack convert (#193) * cleanup the gpt2 to hf export script * cleanup * cleanup * temporary mpt export * widen what we accept * sigh * something * log vocab size * keep the tokenizer * use save_model_local in backpack test * use save_model_local in mpt test * rename save_model* to save_pretrained * rename load_lm_model* to load_pretrained --------- Co-authored-by: Ivan Zhou <ivan.zhouyq@gmail.com> diff --git a/pyproject.toml b/pyproject.toml index 0513aee..b09c3e4 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -56,7 +56,7 @@ dependencies = [ [tool.black] line-length = 119 target-version = ["py310"] -experimental_string_processing = true +preview = true [tool.isort] profile = "black" commit 9f1d48e109dd00edfbc6409e112ff81e428a7a4d Date: 2023-06-13T14:09:13-07:00 factor out a dropout function (#195) diff --git a/src/haliax/nn/__init__.py b/src/haliax/nn/__init__.py index 501bfd8..e7de597 100644 --- a/src/haliax/nn/__init__.py +++ b/src/haliax/nn/__init__.py @@ -11,7 +11,7 @@ import haliax.nn.attention as attention from ..core import NamedArray from ..types import Axis, AxisSelector, AxisSpec from ..wrap import unwrap_namedarrays, wrap_axiswise_call, wrap_elemwise_unary, wrap_reduction_call -from .dropout import Dropout +from .dropout import Dropout, dropout from .embedding import Embedding from .linear import Linear from .normalization import LayerNorm @@ -142,6 +142,7 @@ __all__ = [ "cross_entropy_loss_and_log_normalizers", "quick_gelu", "Dropout", + "dropout", "LayerNorm", "Linear", "Embedding", diff --git a/src/haliax/nn/dropout.py b/src/haliax/nn/dropout.py index 1dc4960..5afff9d 100644 --- a/src/haliax/nn/dropout.py +++ b/src/haliax/nn/dropout.py @@ -9,6 +9,48 @@ from haliax.types import AxisSpec from haliax.util import ensure_tuple +def dropout(x, pdrop, broadcast_axes=None, *, inference=False, key=None): + """Applies dropout. + + **Arguments:** + + - `x`: An any-dimensional JAX array to dropout. + - `pdrop`: The fraction of entries to set to zero. + - `broadcast_axes`: The dimensions to broadcast the dropout mask over. If set, these axes will share the same mask + - `key`: A `jax.random.PRNGKey` used to provide randomness for calculating + which elements to dropout. (Keyword only argument.) + - `inference`: As per [`equinox.nn.Dropout.__init__`][]. If `True` or + `False` then it will take priority over `self.inference`. If `None` + then the value from `self.inference` will be used. + """ + if inference: + return x + elif isinstance(pdrop, (int, float)) and pdrop == 0: + return x + elif isinstance(pdrop, (int, float)) and pdrop == 1: + return haliax.zeros_like(x) + elif key is None: + raise RuntimeError("Dropout requires a key when running in non-deterministic mode.") + else: + with jax.named_scope(name="dropout"): + if broadcast_axes is None: + if isinstance(x, NamedArray): + shape_to_generate = x.axes + else: + shape_to_generate = x.shape + else: + axes = ensure_tuple(broadcast_axes) + shape_to_generate = tuple(ax for ax in x.axes if ax not in axes) + + q = 1 - pdrop + mask = haliax.random.bernoulli(key, shape_to_generate, q) + q = x.dtype.type(q) + + out = haliax.where(mask, x / q, 0) + assert out.dtype == x.dtype + return out + + class Dropout(eqx.Module): """Applies dropout. @@ -46,30 +88,10 @@ class Dropout(eqx.Module): then the value from `self.inference` will be used. - `deterministic`: Deprecated alternative to `inference`. """ - - if isinstance(self.pdrop, (int, float)) and self.pdrop == 0: - return x - elif isinstance(self.pdrop, (int, float)) and self.pdrop == 1: - return haliax.zeros_like(x) - elif inference: - return x - elif key is None: - raise RuntimeError("Dropout requires a key when running in non-deterministic mode.") - else: - with jax.named_scope(name="dropout"): - if self.broadcast_axes is None: - if isinstance(x, NamedArray): - shape_to_generate = x.axes - else: - shape_to_generate = x.shape - else: - axes = ensure_tuple(self.broadcast_axes) - shape_to_generate = tuple(ax for ax in x.axes if ax not in axes) - - q = 1 - self.pdrop - mask = haliax.random.bernoulli(key, shape_to_generate, q) - q = x.dtype.type(q) - - out = haliax.where(mask, x / q, 0) - assert out.dtype == x.dtype - return out + return dropout( + x, + self.pdrop, + broadcast_axes=self.broadcast_axes, + inference=inference, + key=key, + ) commit 78fc05079a9d97a8b40398b735cbab46a51b9633 Date: 2023-06-14T16:21:38-07:00 Registration for Model Configs (#200) * Introduce LMHeadModel supertype for models * rm palm_lite * add short docstring for lmheadmodel * add LmConfig and make everyone implement it * add abstract properties for pos axes * don't reregister types * register lm configs * convert gpt2_example to use new configs * remove old comment * rename TrainGpt2Config to TrainLmConfig * factor out config path stuff for config tests * rename gpt2_example.py to train_lm.py, update docs diff --git a/README.md b/README.md index 6f4d716..1dc916f 100644 --- a/README.md +++ b/README.md @@ -118,7 +118,7 @@ TODO: put things on pypi, etc As a kind of hello world, here's how you can train a GPT-2 "nano"-sized model on a small dataset. ```bash -python examples/gpt2_example.py --config_path config/gpt2_nano.yaml +python src/levanter/main/train_lm.py --config_path config/gpt2_nano.yaml ``` This will train a GPT2-nano model on the [WikiText-2](https://blog.einstein.ai/the-wikitext-long-term-dependency-language-modeling-dataset/) dataset. diff --git a/src/haliax/nn/dropout.py b/src/haliax/nn/dropout.py index 5afff9d..935df53 100644 --- a/src/haliax/nn/dropout.py +++ b/src/haliax/nn/dropout.py @@ -9,7 +9,7 @@ from haliax.types import AxisSpec from haliax.util import ensure_tuple -def dropout(x, pdrop, broadcast_axes=None, *, inference=False, key=None): +def dropout(x, pdrop, broadcast_axes=None, *, inference, key=None): """Applies dropout. **Arguments:** commit 8da8a249f139ae4cc5916b8f048c46e0f4504fea Date: 2023-06-15T14:46:59-07:00 Update packages and mains, along with getting started info (#205) * tweaks diff --git a/README.md b/README.md index 1dc916f..7ce5f85 100644 --- a/README.md +++ b/README.md @@ -9,7 +9,7 @@ meaning that the same code with the same data will produce the exact same result Levanter and Haliax were created by [Stanford's Center for Research on Foundation Models (CRFM)](https://crfm.stanford.edu/)'s research engineering team. ([We're hiring!](https://crfm.stanford.edu/apply.html)) -## Haliax +# Haliax > Though you don’t seem to be much for listening, it’s best to be careful. If you managed to catch hold of even just a piece of my name, you’d have all manner of power over me.<br/> > — Patrick Rothfuss, *The Name of the Wind* @@ -80,13 +80,13 @@ class Attention(eqx.Module): return x ``` -### Documentation for Haliax +## Documentation for Haliax -Currently we have two tutorials for Haliax: +Currently, we have two tutorials for Haliax: * [Introduction to Haliax with Transformers](https://colab.research.google.com/drive/1TiTcQQ4V5mopbgCu1SVl-oqJtXn7rFnC) * [Distributed Training in Haliax](https://colab.research.google.com/drive/1QX4yH3zRFF3Xiibf1aahETcSQ5nbcUMz) (including FSDP) -## Levanter +# Levanter > You could not prevent a thunderstorm, but you could use the electricity; you could not direct the wind, but you could trim your sail so as to propel your vessel as you pleased, no matter which way the wind blew. <br/> > — Cora L. V. Hatch @@ -96,6 +96,11 @@ meaning that the same code with the same data will produce the exact same result It supports distributed training on TPUs (and, soon, GPUs), including FSDP, tensor parallelism, distributed checkpointing, distributed data loading, and more. Levanter integrates with WandB for logging and with the Hugging Face ecosystem for tokenizers, datasets, and model import and export. +## Getting Started + +Here is a small set of examples to get you started. For more information about the various configuration options, please see the [Training Getting Started](docs/Getting-Started-Training.md) guide. +You can also use `--help` or poke around other configs to see all the options available to you. + ### Installing Levanter First, install the appropriate version of Jax for your system. See [Jax's installation instructions](https://github.com/google/jax/blob/main/README.md#installation) as it varies from platform to platform. @@ -118,28 +123,96 @@ TODO: put things on pypi, etc As a kind of hello world, here's how you can train a GPT-2 "nano"-sized model on a small dataset. ```bash -python src/levanter/main/train_lm.py --config_path config/gpt2_nano.yaml +python -m levanter.main.train_lm --config_path config/gpt2_nano.yaml + +# alternatively, if you didn't use -e and are in a different directory +python -m levanter.main.train_lm --config_path gpt2_nano ``` -This will train a GPT2-nano model on the [WikiText-2](https://blog.einstein.ai/the-wikitext-long-term-dependency-language-modeling-dataset/) dataset. -You can change the dataset by changing the `dataset` field in the config file. +This will train a GPT2-nano model on the [WikiText-103](https://blog.einstein.ai/the-wikitext-long-term-dependency-language-modeling-dataset/) dataset. -For more information about the various configuration options, please see the [Training Getting Started](docs/Getting-Started-Training.md) guide. -You can also use `--help` or poke around other configs to see all the options available to you. +### Training a GPT2-small on your own data + +You can also change the dataset by changing the `dataset` field in the config file. +If your dataset is a [Hugging Face dataset](https://huggingface.co/docs/datasets/loading_datasets.html), you can use the `data.id` field to specify it: + +```bash +python -m levanter.main.train_lm --config_path config/gpt2_small.yaml --data.id openwebtext +# optionally, you may specify a tokenizer and/or a cache directory, which may be local or on gcs +python -m levanter.main.train_lm --config_path config/gpt2_small.yaml --data.id openwebtext --data.tokenizer "EleutherAI/gpt-neox-20b" --data.cache_dir "gs://path/to/cache/dir" +``` +If instead your data is a list of URLs, you can use the `data.train_urls` and `data.validation_urls` fields to specify them. +Data URLS can be local files, gcs files, or http(s) URLs, or anything that [fsspec](https://filesystem-spec.readthedocs.io/en/latest/) supports. +Levanter (really, fsspec) will automatically uncompress `.gz` and `.zstd` files, and probably other formats too. -#### Training on a TPU Cloud VM +```bash +python -m levanter.main.train_lm --config_path config/gpt2_small.yaml --data.train_urls ["https://path/to/train/data_*.jsonl.gz"] --data.validation_urls ["https://path/to/val/data_*.jsonl.gz"] +``` -Please see the [TPU Getting Started](docs/Getting-Started-TPU-VM.md) guide for more information on how to set up a TPU Cloud VM and run Levanter there. +### Customizing a Config File + +You can modify the config file to change the model, the dataset, the training parameters, and more. Here's +the `gpt2_small.yaml` file: + +```yaml +data: + train_urls: + - "gs://pubmed-mosaic/openwebtext-sharded/openwebtext_train.{1..128}-of-128.jsonl.gz" + validation_urls: + - "gs://pubmed-mosaic/openwebtext-sharded/openwebtext_val.{1..8}-of-8.jsonl.gz" + cache_dir: "gs://pubmed-mosaic/tokenized/openwebtext/" +model: + gpt2: + hidden_dim: 768 + num_heads: 12 + num_layers: 12 + seq_len: 1024 + gradient_checkpointing: true + scale_attn_by_inverse_layer_idx: true +trainer: + wandb: + project: "levanter" + tags: [ "openwebtext", "gpt2"] + + mp: p=f32,c=bfloat16 + model_axis_size: 1 + per_device_parallelism: 4 + + train_batch_size: 512 +optimizer: + learning_rate: 6E-4 + weight_decay: 0.1 + min_lr_ratio: 0.1 +``` -#### Training with CUDA +### Other Architectures -Please see the [CUDA Getting Started](docs/Getting-Started-CUDA.md) guide for more information on how to set up a CUDA environment and run Levanter there. +Currently, we support GPT-2, [Backpacks](http://backpackmodels.science/) and MosaicML's [MPT](https://www.mosaicml.com/blog/mpt-7b) +architectures. We plan to add more in the future. -### Understanding Levanter and Haliax +#### A Tiny Backpack Model -Please see the [Overview](docs/Overview.md) guide for more information on how Levanter and Haliax work, their inspirations, etc. +```bash +python -m levanter.main.train_lm --config_path config/backpack_nano.yaml +``` + +#### Continued Pretraining with MPT + +```bash +python -m levanter.main.train_lm --config_path config/mpt_7b_continued.yaml +``` + +## Distributed and Cloud Training + +### Training on a TPU Cloud VM + +Please see the [TPU Getting Started](docs/Getting-Started-TPU-VM.md) guide for more information on how to set up a TPU Cloud VM and run Levanter there. + +### Training with CUDA + +Please see the [CUDA Getting Started](docs/Getting-Started-CUDA.md) guide for more information on how to set up a CUDA environment and run Levanter there. ## Contributing diff --git a/pyproject.toml b/pyproject.toml index b09c3e4..2d19dcf 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -1,6 +1,6 @@ [build-system] -requires = ["setuptools>=61.0"] -build-backend = "setuptools.build_meta" +requires = ["hatchling"] +build-backend = "hatchling.build" [project] name = "levanter" @@ -9,18 +9,17 @@ authors = [ { name="David Hall", email="dlwh@cs.stanford.edu" }, {name="Ivan Zhou", email="ivanz@stanford.edu"} ] -description = "Scalable Training for Foundation Models with Named Tensors and Jax" +description = "Scalable Training for Foundation Models with Named Tensors and JAX" readme = "README.md" requires-python = ">=3.10" classifiers = [ "Programming Language :: Python :: 3", - "License :: OSI Approved :: Apache Software License 2.0", - "Operating System :: Linux", + "License :: OSI Approved :: Apache Software License", + "Operating System :: POSIX :: Linux", "Operating System :: MacOS :: MacOS X", - "Development Status :: 3 - Alpha", + "Development Status :: 4 - Beta", "Intended Audience :: Science/Research", ] - dependencies = [ # we'll require that you install jax yourself, since the extras vary by system. # jax = {version = ">=0.4.10,<0.5.0"} @@ -48,6 +47,20 @@ dependencies = [ "rich>=13", ] +[tool.hatch.build] +include = [ + "config/*.yaml", "config/*/*.yaml" +] + +[tool.hatch.build.sources] +"src/levanter" = "levanter" +"src/haliax" = "haliax" +"config" = "levanter/config" + + +[tool.hatch.build.targets.wheel] +packages = ["src/levanter", "src/haliax", "config"] + [project.urls] "Homepage" = "https://github.com/stanford-crfm/levanter" "Bug Tracker" = "https://github.com/stanford-crfm/levanter/issues" commit 5a470bac39b4818aa956aa7ebbdf1f69703144fa Date: 2023-06-15T23:11:25-07:00 Introduce Mkdocs (#137) * initial mkdocs * initial mkdocs * wip * Update README.md * Update readme, index.md, and installation.md * update readme * remove dummy ref and dev guide from HELM * make list * update link according to new changes * tweak docs --------- Co-authored-by: David Hall <dlwh@stanford.edu> Co-authored-by: Ivan Zhou <ivan.zhouyq@@gmail.com> diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 82f9c2f..7188235 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -62,7 +62,7 @@ When your changes are operational you should verify that the current tests are p Set up your environment for running the tests: - export PYTHONPATH=/path/to/levanter/src + export PYTHONPATH=/path/to/levanter/src:path/to/levanter/tests:$PYTHONPATH wandb offline You can run the tests with this command: diff --git a/README.md b/README.md index 7ce5f85..e60a630 100644 --- a/README.md +++ b/README.md @@ -1,4 +1,5 @@ # Levanter and Haliax +<!--intro-start--> Levanter and Haliax are libraries based on [Jax](https:://github.com/google/jax) and [Equinox](https://github.com/patrick-kidger/equinox) for training deep learning models, especially [foundation models](https://en.wikipedia.org/wiki/Foundation_models). @@ -9,9 +10,12 @@ meaning that the same code with the same data will produce the exact same result Levanter and Haliax were created by [Stanford's Center for Research on Foundation Models (CRFM)](https://crfm.stanford.edu/)'s research engineering team. ([We're hiring!](https://crfm.stanford.edu/apply.html)) +<!--intro-end--> + # Haliax +<!--haliax-intro-start--> -> Though you don’t seem to be much for listening, it’s best to be careful. If you managed to catch hold of even just a piece of my name, you’d have all manner of power over me.<br/> +> *Though you don’t seem to be much for listening, it’s best to be careful. If you managed to catch hold of even just a piece of my name, you’d have all manner of power over me.*<br/> > — Patrick Rothfuss, *The Name of the Wind* Haliax is a Jax library for building neural networks with named tensors, in the tradition of Alexander Rush's [Tensor Considered Harmful](https://nlp.seas.harvard.edu/NamedTensor). @@ -83,18 +87,22 @@ class Attention(eqx.Module): ## Documentation for Haliax Currently, we have two tutorials for Haliax: + * [Introduction to Haliax with Transformers](https://colab.research.google.com/drive/1TiTcQQ4V5mopbgCu1SVl-oqJtXn7rFnC) * [Distributed Training in Haliax](https://colab.research.google.com/drive/1QX4yH3zRFF3Xiibf1aahETcSQ5nbcUMz) (including FSDP) -# Levanter +<!--haliax-intro-end--> -> You could not prevent a thunderstorm, but you could use the electricity; you could not direct the wind, but you could trim your sail so as to propel your vessel as you pleased, no matter which way the wind blew. <br/> +# Levanter +<!--levanter-intro-start--> +> *You could not prevent a thunderstorm, but you could use the electricity; you could not direct the wind, but you could trim your sail so as to propel your vessel as you pleased, no matter which way the wind blew.* <br/> > — Cora L. V. Hatch Levanter is a library for training foundation models built on top of Haliax. Levanter strives for bitwise reproducibility, meaning that the same code with the same data will produce the exact same result, even in the presence of preemption and restarting from checkpoints. It supports distributed training on TPUs (and, soon, GPUs), including FSDP, tensor parallelism, distributed checkpointing, distributed data loading, and more. Levanter integrates with WandB for logging and with the Hugging Face ecosystem for tokenizers, datasets, and model import and export. +<!--levanter-intro-end--> ## Getting Started @@ -103,20 +111,11 @@ You can also use `--help` or poke around other configs to see all the options av ### Installing Levanter -First, install the appropriate version of Jax for your system. See [Jax's installation instructions](https://github.com/google/jax/blob/main/README.md#installation) as it varies from platform to platform. +Please refer to the [Installation Guide](docs/Installation.md) for more information on how to install Levanter. If you're using a TPU, more complete documentation for setting that up is available [here](docs/Getting-Started-TPU-VM.md). GPU support is still in-progress; documentation is available [here](docs/Getting-Started-CUDA.md). -Now clone this repository and install it with pip: - -```bash -git clone https://github.com/stanford-crfm/levanter.git -cd levanter -pip install -e . -wandb login # optional, we use wandb for logging -``` - -TODO: put things on pypi, etc +<!--levanter-user-guide-start--> ### Training a GPT2-nano @@ -204,6 +203,7 @@ python -m levanter.main.train_lm --config_path config/backpack_nano.yaml python -m levanter.main.train_lm --config_path config/mpt_7b_continued.yaml ``` + ## Distributed and Cloud Training ### Training on a TPU Cloud VM @@ -214,6 +214,8 @@ Please see the [TPU Getting Started](docs/Getting-Started-TPU-VM.md) guide for m Please see the [CUDA Getting Started](docs/Getting-Started-CUDA.md) guide for more information on how to set up a CUDA environment and run Levanter there. +<!--levanter-user-guide-end--> + ## Contributing We welcome contributions! Please see [CONTRIBUTING.md](CONTRIBUTING.md) for more information. diff --git a/docs/Haliax.md b/docs/Haliax.md new file mode 100644 index 0000000..d8dea7c --- /dev/null +++ b/docs/Haliax.md @@ -0,0 +1,5 @@ +{% + include-markdown "../README.md" + start="<!--haliax-intro-start-->" + end="<!--haliax-intro-end-->" +%} diff --git a/docs/index.md b/docs/index.md new file mode 100644 index 0000000..415d2af --- /dev/null +++ b/docs/index.md @@ -0,0 +1,17 @@ +{% + include-markdown "../README.md" + start="<!--intro-start-->" + end="<!--intro-end-->" +%} + +The code is released on GitHub: [Levanter Repository](https://github.com/stanford-crfm/levanter/). + +To get started, please refer to the User Guide's chapters: + +- [Getting Started with CUDA](Getting-Started-CUDA.md) +- [Getting Started with TPU](Getting-Started-TPU-VM.md) +- [Getting Started to launch model training](Getting-Started-Training.md) + +For a more detailed dive into how Levanter works, please refer to the [Overview](Overview.md). + +To contribute, please refer to the [Contributing Guide](https://github.com/stanford-crfm/levanter/blob/main/CONTRIBUTING.md). diff --git a/mkdocs.yml b/mkdocs.yml new file mode 100644 index 0000000..fa4af39 --- /dev/null +++ b/mkdocs.yml @@ -0,0 +1,54 @@ +site_name: CRFM Levanter +repo_url: https://github.com/stanford-crfm/levanter/ +edit_uri: blob/main/docs/ +theme: + name: readthedocs + highlightjs: false +plugins: + - search + - mkdocstrings: + handlers: + python: + options: + show_root_heading: true + show_signature_annotations: true + show_bases: false + show_source: false + show_root_full_path: false + show_if_no_docstring: true + members_order: source + merge_init_into_class: true + docstring_options: + ignore_init_summary: true + + - include-markdown +extra_css: + - docstrings.css +markdown_extensions: + - pymdownx.magiclink + - pymdownx.arithmatex: # Render LaTeX via MathJax + generic: true + - pymdownx.superfences # Seems to enable syntax highlighting when used with the Material theme. + - pymdownx.details # Allowing hidden expandable regions denoted by ??? + - pymdownx.snippets: # Include one Markdown file into another + base_path: docs + - admonition + - toc: + permalink: "¤" # Adds a clickable permalink to each section heading + toc_depth: 4 +watch: + - src + - scripts + - infra + - config +nav: + - 'Home': 'index.md' + - 'User Guide': 'Getting-Started-Training.md' + - Haliax: 'Haliax.md' + - 'Installation and Setup': + - 'Installation.md' + - 'Getting-Started-TPU-VM.md' + - 'Getting-Started-CUDA.md' + - Technical Documentation: + - 'Overview.md' + - 'design/Data-Loader-Design.md' commit 28b5cb04b023a21931bf6788c1f113a756b50b74 Date: 2023-06-15T23:11:45-07:00 Fix Training Documentation - add a missing `src/` (#206) commit 8c5205b911b9313a139df15410d400cb300b5233 Date: 2023-06-16T09:03:43-07:00 levanter 1.0 diff --git a/pyproject.toml b/pyproject.toml index 2d19dcf..a9382c9 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -4,7 +4,7 @@ build-backend = "hatchling.build" [project] name = "levanter" -version = "0.0.1" +version = "1.0" authors = [ { name="David Hall", email="dlwh@cs.stanford.edu" }, {name="Ivan Zhou", email="ivanz@stanford.edu"} commit 17266b734a4c098f13fe32fe6573f00f143074b6 Date: 2023-06-16T11:48:35-07:00 add discord link diff --git a/README.md b/README.md index e60a630..117c7b0 100644 --- a/README.md +++ b/README.md @@ -8,7 +8,7 @@ Levanter is a library for training foundation models built on top of Haliax. In addition to the goals of legibility, efficiency, and scalability, Levanter further strives for bitwise reproducibility, meaning that the same code with the same data will produce the exact same result, even in the presence of preemption and restarting from checkpoints. -Levanter and Haliax were created by [Stanford's Center for Research on Foundation Models (CRFM)](https://crfm.stanford.edu/)'s research engineering team. ([We're hiring!](https://crfm.stanford.edu/apply.html)) +Levanter and Haliax were created by [Stanford's Center for Research on Foundation Models (CRFM)](https://crfm.stanford.edu/)'s research engineering team. ([We're hiring!](https://crfm.stanford.edu/apply.html)) You can also find us in the #levanter channel on the unofficial [Jax LLM Discord](https://discord.gg/FkRGNX3ND) <!--intro-end--> commit 2cfe3fd86c93ce35867ad5bd2511567e4b9a70d6 Date: 2023-06-20T17:36:41-07:00 Introduce indexing/slicing syntax for Haliax (#208) * wip * basic slice_nd * implement and test so-called "advanced" indexing * test weird edge case, add docs for slice_nd * add docs for indexing, scalar return, fix a bug in advanced indexing * fix test * improve docs * add shorthand notation for indexing diff --git a/docs/haliax/indexing.md b/docs/haliax/indexing.md new file mode 100644 index 0000000..8bee511 --- /dev/null +++ b/docs/haliax/indexing.md @@ -0,0 +1,96 @@ +# Indexing in Haliax + +Haliax supports Numpy-style indexing, including advanced indexing, though the syntax is necessarily different. +Most forms of indexing are supporting, except we don't support indexing with booleans right now. (JAX doesn't support indexing with non-constant bool arrays anyway, +so I don't think it's worth the effort to implement it in Haliax.) + +## Basic Indexing + +Basic indexing works basically like you would expect: you can use integers or slices to index into an array. +Haliax supports two syntaxes for indexing: one accepts a dict of axis names and indices, and the other accepts +an alternating sequence of axis names and indices. The latter is useful for indexing with a small number of indices. + + +```python +import haliax as hax +import jax + +X = hax.Axis("X", 10) +Y = hax.Axis("Y", 20) +Z = hax.Axis("Z", 30) + +a = hax.random.uniform(jax.random.PRNGKey(0), (X, Y, Z)) + +a[{"X": 1, "Y": 2, "Z": 3}] # returns a scalar jnp.ndarray +a[{"X": 1, "Y": 2, "Z": slice(3, 5)}] # return a NamedArray with axes = Axis("Z", 2) +a[{"X": 1, "Y": slice(2, 4), "Z": slice(3, 5)}] # return a NamedArray with axes = Axis("Y", 2), Axis("Z", 2) + +a["X", 1, "Y", 2, "Z", 3] # returns a scalar jnp.ndarray +a["X", 1, "Y", 2, "Z", 3:5] # return a NamedArray with axes = Axis("Z", 2) +a["X", 1, "Y", 2:4, "Z", 3:5] # return a NamedArray with axes = Axis("Y", 2), Axis("Z", 2) +``` + +Unfortunately, Python won't let us use `:` slice syntax inside of a dictionary, so we have to use `slice` instead. +This is why we have the second syntax, which is a bit less idiomatic in some ways, but it's more convenient. + +Otherwise, the idea is pretty straightforward: any unspecified axes are treated as though indexed with `:` in NumPy, +slices are kept in reduced dimensions, and integers eliminate dimensions. If all dimensions are eliminated, a scalar +JAX ndarray is returned. + +## Advanced Indexing + +NumPy's [Advanced Indexing](https://numpy.org/doc/stable/user/basics.indexing.html#advanced-indexing) is supported, +though we use named arrays for the indices instead of normal arrays. In NumPy, the indexed arrays much be +broadcastable to the same shape. Advanced indexing in Haliax is similar, except that they follow Haliax's broadcasting rules, +meaning that the axis names determine broadcasting. Axes with the same name must have the same size. + +```python +import haliax as hax +import jax + +X = hax.Axis("X", 10) +Y = hax.Axis("Y", 20) +Z = hax.Axis("Z", 30) + +a = hax.random.uniform(jax.random.PRNGKey(0), (X, Y, Z)) + +I1 = hax.Axis("I1", 5) +I2 = hax.Axis("I2", 5) +I3 = hax.Axis("I3", 5) +ind1 = hax.random.randint(jax.random.PRNGKey(0), (I1,), 0, 10) +ind2 = hax.random.randint(jax.random.PRNGKey(0), (I2, I3), 0, 20) + +a[{"X": ind1}] # returns a NamedArray with axes = Axis("I1", 5), Axis("Y", 20), Axis("Z", 30) + +a[{"X": ind1, "Y": ind2}] # returns a NamedArray with axes = Axis("I1", 5), Axis("I2", 5), Axis("I3", 5), Axis("Z", 30) +a[{"X": ind1, "Y": ind2, "Z": 3}] # returns a NamedArray with axes = Axis("I1", 5), Axis("I2", 5), Axis("I3", 5) +``` + +The order of the indices in the dictionary doesn't matter, and you can mix and match basic and advanced indexing. +The actual sequence of axes is a bit complex, both in Haliax and in NumPy. If you need a specific order, it's probably +best to use rearrange. + +In keeping with the one-axis-per-name rule, you are allowed to index using axes with a name present in the array, +if it would be eliminated by the indexing operation. For example: + +```python +import haliax as hax +import jax + +X = hax.Axis("X", 10) +Y = hax.Axis("Y", 20) +Z = hax.Axis("Z", 30) + +X2 = hax.Axis("X", 5) +Y2 = hax.Axis("Y", 5) + +a = hax.random.uniform(jax.random.PRNGKey(0), (X, Y, Z)) +ind1 = hax.random.randint(jax.random.PRNGKey(0), (X2,), 0, 10) +ind2 = hax.random.randint(jax.random.PRNGKey(0), (Y2,), 0, 10) + +a[{"X": ind1, "Y": ind2}] # returns a NamedArray with axes = Axis("X", 5), Axis("Y", 5), Axis("Z", 30) + +a[{"Y": ind1}] # error, "X" is not eliminated by the indexing operation + +a[{"X": ind2, "Y": ind1}] # ok, because X and Y are eliminated by the indexing operation +``` diff --git a/src/haliax/__init__.py b/src/haliax/__init__.py index 1faf8ba..9d75011 100644 --- a/src/haliax/__init__.py +++ b/src/haliax/__init__.py @@ -22,6 +22,7 @@ from .core import ( rename, roll, slice, + slice_nd, split, take, unbind, @@ -268,6 +269,7 @@ __all__ = [ "split", "flatten_axes", "slice", + "slice_nd", "take", "unbind", "rename", diff --git a/src/haliax/core.py b/src/haliax/core.py index d328375..89efa16 100644 --- a/src/haliax/core.py +++ b/src/haliax/core.py @@ -13,7 +13,7 @@ import numpy as np import haliax from haliax.jax_utils import is_jax_array_like -from haliax.util import ensure_tuple, index_where +from haliax.util import ensure_tuple, index_where, py_slice, slice_t from .types import Axis, AxisSelection, AxisSelector, AxisSpec, PrecisionLike, Scalar @@ -224,6 +224,8 @@ class NamedArray: def rename(self, renames: Mapping[AxisSelector, AxisSelector]) -> "NamedArray": return haliax.rename(self, renames=renames) + # slicing + # TOOD: AxisSelector-ify new_axis def slice(self, axis: AxisSelector, new_axis: Axis, start: int = 0) -> "NamedArray": return haliax.slice(self, axis=axis, new_axis=new_axis, start=start) @@ -231,6 +233,56 @@ class NamedArray: def take(self, axis: AxisSelector, index: Union[int, "NamedArray"]) -> "NamedArray": return haliax.take(self, axis=axis, index=index) + @overload + def __getitem__(self, item: Tuple[str, Union[int, slice_t, "NamedArray"]]) -> Union["NamedArray", jnp.ndarray]: + ... # pragma: no cover + + @overload + def __getitem__( + self, item: Tuple[str, Union[int, slice_t, "NamedArray"], str, Union[int, slice_t, "NamedArray"]] + ) -> Union["NamedArray", jnp.ndarray]: + ... + + @overload + def __getitem__(self, item: Mapping[str, Union[int, slice_t, "NamedArray"]]) -> Union["NamedArray", jnp.ndarray]: + ... + + def __getitem__(self, idx) -> Union["NamedArray", jnp.ndarray]: + """Syntactic sugar for slice_nd, which is the actual implementation. + + Supports indexing like: + + >>> X = Axis("x", 10) + >>> Y = Axis("y", 20) + >>> arr = haliax.random.randint(jax.random.PRNGKey(0), (X, Y), 0, X.size) + # slice with ints or slices + >>> arr[{"x": 1, "y": slice(0, 10, 2)}] + >>> Z = Axis("z", 3) + # so-called "advanced indexing" with NamedArrays. + >>> index_arr = NamedArray(np.array([1, 2, 3]), Z) + >>> arr[{"x": 1, "y": index_arr}] + + A shorthand is provided that works with Python's slicing syntax: + >>> arr["x", :] == arr[{"x": slice(None, None, None)}] + >>> arr["y", slice(0, 10, 2)] == arr[{"y": slice(0, 10, 2)}] + + Advanced indexing is implemented by broadcasting all index arrays to the same shape (using Haliax's + usual broadcasting rules). + + This returns a NamedArray if any axes remain, or a scalar (0-dimensional) jnp.ndarray if all axes are indexed out. + """ + if isinstance(idx, tuple): + if len(idx) == 1: + idx = idx[0] + else: + if len(idx) % 2 != 0: + raise ValueError( + "Must provide an even number of arguments to __getitem__ when using the shorthand syntax." + ) + idx = {idx[i]: idx[i + 1] for i in range(0, len(idx), 2)} + + return slice_nd(self, idx) + # np.ndarray methods: def all(self, axis: Optional[AxisSelection] = None) -> "NamedArray": return haliax.all(self, axis=axis) @@ -557,6 +609,90 @@ def slice(array: NamedArray, axis: AxisSelector, new_axis: Axis, start: int = 0) return NamedArray(sliced, new_axes) +def slice_nd( + array: NamedArray, slices: Mapping[AxisSelector, Union[int, slice_t, NamedArray]] +) -> Union[NamedArray, jnp.ndarray]: + """ + Selects elements from an array along an axis, by an index or by another named array. + Typically, you would call this via `array[...]` syntax. For example, you might call + `array[{"batch": slice(0, 10)}]` to select the first 10 elements of the batch axis. + :param array: + :param slices: + :return: a scalar jnp.ndarray is all axes are sliced with ints, otherwise a NamedArray + """ + # indices where we have array args + array_slice_indices = [] + ordered_slices: list = [py_slice(None, None, None)] * len(array.axes) # type: ignore + kept_axes = [True] * len(array.axes) + for axis, slice_ in slices.items(): + axis_index = array._lookup_indices(axis) + if axis_index is None: + raise ValueError(f"axis {axis} not found in {array}") + ordered_slices[axis_index] = slice_ + kept_axes[axis_index] = isinstance(slice_, py_slice) + if isinstance(slice_, NamedArray): + array_slice_indices.append(axis_index) + + # advanced indexing + if len(array_slice_indices) > 0: + # this requires broadcasting + broadcasted_arrays, broadcasted_axes = broadcast_arrays_and_return_axes( + *[ordered_slices[i] for i in array_slice_indices], require_subset=False, ensure_order=True + ) + # this is tricky. NumPy distinguishes two cases when mixing advanced and basic indexing: + # https://numpy.org/doc/stable/user/basics.indexing.html#combining-advanced-and-basic-indexing + # The first is when the advanced indices are all contiguous, and the second is when they are not. + # (NB that integers count as advanced indices, so this is a bit more complicated than it seems.) + # When contiguous, the new axes go in the same place as the advanced indices, and the old axes surround them. + # When not contiguous, the new axes go to the *front* of the array, and the (other) old axes go after them. + # To tell what case we're in, we check if the advanced indices are contiguous. We can figure out by looking + # at the "kept_axes": the Falses are the advanced indices. + + # check to make sure we're not accidentally duplicating axes + for axis_index in range(len(array.axes)): + if kept_axes[axis_index]: + if selects_axis(broadcasted_axes, array.axes[axis_index].name): + raise ValueError(f"Array Axis {array.axes[axis_index]} is present in slice {slices}") + + for axis_index, selector_array in zip(array_slice_indices, broadcasted_arrays): + ordered_slices[axis_index] = selector_array.array + + is_advanced_contiguous = True + first_advanced_index = index_where(lambda x: not x, kept_axes) + last_advanced_index = first_advanced_index + true_found = False + for i in range(first_advanced_index, len(kept_axes)): + # now find the first True. If any False comes after it, we're not contiguous + if true_found: + if not kept_axes[i]: + is_advanced_contiguous = False + break + elif kept_axes[i]: + true_found = True + last_advanced_index = i - 1 + + if not true_found: + last_advanced_index = len(kept_axes) - 1 + + if is_advanced_contiguous: + # the advanced indices are contiguous, so we can just insert the new axes in the same place + # as the advanced indices + new_axes = array.axes[:first_advanced_index] + broadcasted_axes + array.axes[last_advanced_index + 1 :] + else: + # the advanced indices are not contiguous, so we need to insert the new axes at the front + new_axes = broadcasted_axes + tuple(ax for i, ax in enumerate(array.axes) if kept_axes[i]) + else: + new_axes = tuple(axis.name for axis, keep in zip(array.axes, kept_axes) if keep) + + sliced = array.array[tuple(ordered_slices)] + + if len(new_axes) == 0: + # this is a scalar + return sliced + + return haliax.named(sliced, new_axes) + + def dot(axis: AxisSelection, *arrays: NamedArray, precision: PrecisionLike = None) -> NamedArray: """Returns the tensor product of two NamedArrays. The axes `axis` are contracted over, and any other axes that are shared between the arrays are batched over. Non-contracted Axes in one @@ -1009,7 +1145,7 @@ def broadcast_arrays_and_return_axes( The arrays to broadcast require_subset: bool If True, then one of the arrays must be a subset of the other. This is a bit stricter than numpy's broadcasting - rules, but I've been bitten by numpy's rules too many times. If False is looser than numpy's rules, and allows + rules, but I've been bitten by numpy's rules too many times. False is looser than numpy's rules, and allows broadcasting any pair of arrays (so long as the axes don't overtly conflict with different sizes for the same name.) ensure_order: bool @@ -1139,6 +1275,7 @@ __all__ = [ "named", "rearrange", "slice", + "slice_nd", "take", "split", "flatten_axes", diff --git a/src/haliax/util.py b/src/haliax/util.py index ce0f180..3bd57ef 100644 --- a/src/haliax/util.py +++ b/src/haliax/util.py @@ -1,4 +1,4 @@ -from typing import Callable, Sequence, Tuple, TypeVar, Union +from typing import Callable, Sequence, Tuple, Type, TypeVar, Union from haliax.jax_utils import is_jax_array_like @@ -6,6 +6,11 @@ from haliax.jax_utils import is_jax_array_like T = TypeVar("T") +py_slice = slice + +slice_t = Type[slice] + + def is_named_array(leaf): from .core import NamedArray @@ -47,3 +52,14 @@ def index_where(pred: Callable[[T], bool], xs: Sequence[T]) -> int: if pred(x): return i raise ValueError("No element satisfies predicate") + + +__all__ = [ + "is_named_array", + "ensure_tuple", + "StringHolderEnum", + "is_jax_or_hax_array_like", + "index_where", + "slice_t", + "py_slice", +] diff --git a/tests/core_test.py b/tests/core_test.py index a5bd01b..4f7ae40 100644 --- a/tests/core_test.py +++ b/tests/core_test.py @@ -414,3 +414,170 @@ def test_rename(): assert jnp.all(jnp.equal(hax.rename(named1, {H: H2, "W": "W2"}).array, named1.array)) assert hax.rename(named1, {H: H2, "W": "W2"}).axes == (H2, W2, D) + + +def test_slice_nd(): + H = Axis("H", 20) + W = Axis("W", 30) + D = Axis("D", 40) + + named1 = hax.random.uniform(PRNGKey(0), (H, W, D)) + + assert jnp.all(jnp.equal(hax.slice_nd(named1, {"H": slice(0, 10, 2)}).array, named1.array[0:10:2, :, :])) + assert hax.slice_nd(named1, {"H": slice(0, 10, 2)}).axes == (Axis("H", 5), W, D) + + # try indexing syntax + assert jnp.all(jnp.equal(named1[{"H": slice(0, 10, 2)}].array, named1.array[0:10:2, :, :])) + assert named1[{"H": slice(0, 10, 2)}].axes == (Axis("H", 5), W, D) + + # try indexing syntax with multiple slices + assert jnp.all( + jnp.equal(named1[{"H": slice(3, 13, 2), "W": slice(0, 10, 2)}].array, named1.array[3:13:2, 0:10:2, :]) + ) + + # try indexing with 1 slice and 1 integer + assert jnp.all(jnp.equal(named1[{"H": slice(0, 10, 2), "W": 0}].array, named1.array[0:10:2, 0, :])) + assert named1[{"H": slice(0, 10, 2), "W": 0}].axes == (Axis("H", 5), D) + + # try indexing with 3 integers: returns scalar ndarray + assert jnp.all(jnp.equal(named1[{"H": 0, "W": 0, "D": 0}], named1.array[0, 0, 0])) + + +def test_slice_nd_array_slices(): + # fancier tests with array slices with named array args + H = Axis("H", 10) + W = Axis("W", 20) + D = Axis("D", 30) + C = Axis("C", 40) + Q = Axis("Q", 50) + I0 = Axis("I0", 10) + + named1 = hax.random.uniform(PRNGKey(0), (H, W, D, C, Q)) + index_1 = hax.random.randint(PRNGKey(0), (I0,), 0, H.size) + + assert jnp.all(jnp.equal(named1[{"H": index_1}].array, named1.array[index_1.array, :, :])) + assert named1[{"H": index_1}].axes == (I0, W, D, C, Q) + + # try indexing with 1 array and 1 integer + assert jnp.all(jnp.equal(named1[{"H": index_1, "W": 0}].array, named1.array[index_1.array, 0, :])) + assert named1[{"H": index_1, "W": 0}].axes == (I0, D, C, Q) + + # more complex case: advanced indices aren't contiguous + assert jnp.all(jnp.equal(named1[{"H": index_1, "D": 0}].array, named1.array[index_1.array, :, 0])) + assert named1[{"H": index_1, "D": 0}].axes == (I0, W, C, Q) + + # https://numpy.org/doc/stable/user/basics.indexing.html#combining-advanced-and-basic-indexing + # Example + # Let x.shape be (10, 20, 30, 40, 50) and suppose ind_1 and ind_2 can be broadcast to the shape (2, 3, 4). + I1 = Axis("I1", 2) + I2 = Axis("I2", 3) + I3 = Axis("I3", 4) + + ind_1 = hax.random.randint(PRNGKey(0), (I2, I3), 0, W.size) + ind_2 = hax.random.randint(PRNGKey(0), (I1, I3), 0, D.size) + + # Then x[:, ind_1, ind_2] has shape (10, 2, 3, 4, 40, 50) because the (20, 30)-shaped subspace from X has been replaced with the (2, 3, 4) subspace from the indices. + assert jnp.all( + jnp.equal( + named1[{"W": ind_1, "D": ind_2}].array, + named1.array[:, ind_1.array.reshape(1, 3, 4), ind_2.array.reshape(2, 1, 4), :], + ) + ) + assert named1[{"W": ind_1, "D": ind_2}].axes == (H, I1, I2, I3, C, Q) + + # However, x[:, ind_1, :, ind_2] has shape (2, 3, 4, 10, 30, 50) because there is no unambiguous place to drop in the indexing subspace, thus it is tacked-on to the beginning. It is always possible to use .transpose() to move the subspace anywhere desired. Note that this example cannot be replicated using take. + assert jnp.all( + jnp.equal( + named1[{"W": ind_1, "C": ind_2}].array, + named1.array[:, ind_1.array.reshape(1, 3, 4), :, ind_2.array.reshape(2, 1, 4), :], + ) + ) + assert named1[{"W": ind_1, "C": ind_2}].axes == (I1, I2, I3, H, D, Q) + + +def test_slice_nd_shorthand_syntax(): + # syntax like arr["X", 0:10, "Y", 0:10] is supported + + H = Axis("H", 10) + W = Axis("W", 20) + D = Axis("D", 30) + + named1 = hax.random.uniform(PRNGKey(0), (H, W, D)) + + assert jnp.all(jnp.equal(named1["H", 0:10, "D", 0:10].array, named1.array[0:10, :, 0:10])) + + +def test_slice_nd_array_present_dims(): + # tests slicing with arrays that are already present in the named array, which is sometimes ok + H = Axis("H", 10) + W = Axis("W", 20) + D = Axis("D", 30) + + named1 = hax.random.uniform(PRNGKey(0), (H, W, D)) + + index1 = hax.random.randint(PRNGKey(0), (H,), 0, H.size) + + # this is ok, since the H would be eliminated anyway + assert jnp.all(jnp.equal(named1[{"H": index1}].array, named1.array[index1.array, :, :])) + + # this is not ok, since the H would not be eliminated + with pytest.raises(ValueError): + named1[{W: index1}] + + # this is not ok, but is trickier because the H has a different size + H2 = H.resize(5) + index2 = hax.random.randint(PRNGKey(0), (H2,), 0, H.size) + with pytest.raises(ValueError): + named1[{W: index2}] + + # this is ok, since the H would be eliminated anyway + assert jnp.all(jnp.equal(named1[{"H": index2}].array, named1.array[index2.array, :, :])) + + +def test_full_indexing_returns_scalar(): + H = Axis("H", 10) + W = Axis("W", 20) + D = Axis("D", 30) + + named1 = hax.random.uniform(PRNGKey(0), (H, W, D)) + sliced = named1[{"H": 0, "W": 0, "D": 0}] + + assert isinstance(sliced, jnp.ndarray) + assert sliced.shape == () + + +def test_indexing_bug_from_docs(): + X = hax.Axis("X", 10) + Y = hax.Axis("Y", 20) + Z = hax.Axis("Z", 30) + + a = hax.random.uniform(jax.random.PRNGKey(0), (X, Y, Z)) + + I1 = hax.Axis("I1", 5) + I2 = hax.Axis("I2", 5) + I3 = hax.Axis("I3", 5) + ind1 = hax.random.randint(jax.random.PRNGKey(0), (I1,), 0, 10) + ind2 = hax.random.randint(jax.random.PRNGKey(0), (I2, I3), 0, 20) + + # assert a[{"X": ind1, "Y": ind2}].axes == (I1, I2, I3, Z) + assert a[{"X": ind1, "Y": ind2, "Z": 3}].axes == (I1, I2, I3) + + +def test_duplicate_axis_names_in_slicing(): + X = hax.Axis("X", 10) + Y = hax.Axis("Y", 20) + Z = hax.Axis("Z", 30) + + X2 = hax.Axis("X", 5) + Y2 = hax.Axis("Y", 5) + + a = hax.random.uniform(jax.random.PRNGKey(0), (X, Y, Z)) + ind1 = hax.random.randint(jax.random.PRNGKey(0), (X2,), 0, 10) + ind2 = hax.random.randint(jax.random.PRNGKey(0), (Y2,), 0, 10) + + a[{"X": ind1, "Y": ind2}] # returns a NamedArray with axes = Axis("X", 5), Axis("Y", 5), Axis("Z", 30) + + with pytest.raises(ValueError): + a[{"Y": ind1}] # error, "X" is not eliminated by the indexing operation + + a[{"X": ind2, "Y": ind1}] # ok, because X and Y are eliminated by the indexing operation commit 421a4578c377f75b0c8e5745d62b79ecfe6a2aa0 Date: 2023-06-22T23:14:22-07:00 fix pip install -e diff --git a/pyproject.toml b/pyproject.toml index a9382c9..2dabbef 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -51,6 +51,7 @@ dependencies = [ include = [ "config/*.yaml", "config/*/*.yaml" ] +dev-mode-dirs = [".", "src"] [tool.hatch.build.sources] "src/levanter" = "levanter" @@ -58,6 +59,7 @@ include = [ "config" = "levanter/config" + [tool.hatch.build.targets.wheel] packages = ["src/levanter", "src/haliax", "config"] commit e9f697a6a37e348f39d489c4609dc386350ddb11 Date: 2023-06-26T10:50:12-07:00 remove stray requirements.txt diff --git a/requirements.txt b/requirements.txt deleted file mode 100644 index e69de29..0000000 commit 2167c9c8be52fe0b8f30e65d63b14661d30390e4 Date: 2023-06-26T10:52:55-07:00 update pyproject.toml diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml new file mode 100644 index 0000000..67b877d --- /dev/null +++ b/.pre-commit-config.yaml @@ -0,0 +1,39 @@ +# See https://pre-commit.com for more information +# See https://pre-commit.com/hooks.html for more hooks +exclude: ".git" +default_stages: + - commit +fail_fast: true + +repos: +- repo: https://github.com/pre-commit/pre-commit-hooks + rev: v4.0.1 + hooks: + - id: trailing-whitespace + - id: end-of-file-fixer + - id: check-yaml + - id: check-toml + - id: check-merge-conflict + - id: check-added-large-files + +- repo: https://github.com/psf/black + rev: 22.3.0 + hooks: + - id: black + +- repo: https://github.com/timothycrosley/isort + rev: 5.11.5 + hooks: + - id: isort + +- repo: https://gitlab.com/pycqa/flake8 + rev: 3.9.2 + hooks: + - id: flake8 + additional_dependencies: [flake8-isort] + +- repo: https://github.com/pre-commit/mirrors-mypy + rev: 'v0.960' + hooks: + - id: mypy + args: [--ignore-missing-imports] diff --git a/pyproject.toml b/pyproject.toml index 2dabbef..cb793a5 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -3,7 +3,7 @@ requires = ["hatchling"] build-backend = "hatchling.build" [project] -name = "levanter" +name = "haliax" version = "1.0" authors = [ { name="David Hall", email="dlwh@cs.stanford.edu" }, @@ -24,48 +24,20 @@ dependencies = [ # we'll require that you install jax yourself, since the extras vary by system. # jax = {version = ">=0.4.10,<0.5.0"} "equinox~=0.9.0", - "transformers>=4.22.0", - "optax", - "wandb", - "pyrallis>=0.3.1", - "pyarrow>=11.0.0", - "zstandard>=0.20.0", - "datasets==2.11.0", - "gcsfs==2023.3.0", - "braceexpand>=0.1.7", - "jmp>=0.0.3", - "fsspec==2023.3.0", # pin this to make gcsfs happy - "tensorstore>=0.1.36", - "pytimeparse>=1.1.8", - "humanfriendly==10.0", - "requests", "safetensors[numpy]", - "matplotlib>=3.7.0", - "tblib>=1.7.0,<2.0.0", - "dataclasses_json", - "ray[default]", - "rich>=13", ] -[tool.hatch.build] -include = [ - "config/*.yaml", "config/*/*.yaml" -] -dev-mode-dirs = [".", "src"] [tool.hatch.build.sources] -"src/levanter" = "levanter" "src/haliax" = "haliax" -"config" = "levanter/config" - [tool.hatch.build.targets.wheel] -packages = ["src/levanter", "src/haliax", "config"] +packages = ["src/haliax"] [project.urls] -"Homepage" = "https://github.com/stanford-crfm/levanter" -"Bug Tracker" = "https://github.com/stanford-crfm/levanter/issues" +"Homepage" = "https://github.com/stanford-crfm/haliax" +"Bug Tracker" = "https://github.com/stanford-crfm/haliax/issues/" [tool.black] commit 4b90930a4cf7d954ae732e77cadf9403d4c23fc7 Date: 2023-06-26T11:00:18-07:00 fix tests diff --git a/pyproject.toml b/pyproject.toml index cb793a5..21f26e7 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -25,6 +25,7 @@ dependencies = [ # jax = {version = ">=0.4.10,<0.5.0"} "equinox~=0.9.0", "safetensors[numpy]", + "chex", ] diff --git a/tests/test_utils.py b/tests/test_utils.py new file mode 100644 index 0000000..bd9b779 --- /dev/null +++ b/tests/test_utils.py @@ -0,0 +1,115 @@ +from typing import Callable, List, Optional, TypeVar + +import equinox as eqx +import jax +import pytest +from chex import assert_trees_all_close +from equinox import nn as nn +from equinox import static_field + + +T = TypeVar("T") + + +def skip_if_not_enough_devices(count: int): + return pytest.mark.skipif(len(jax.devices()) < count, reason=f"Not enough devices ({len(jax.devices())})") + + +class MLP(eqx.Module): + """slightly less annoying MLP, used for testing purposes""" + + layers: List[nn.Linear] + activation: Callable = eqx.static_field() + final_activation: Callable = eqx.static_field() + in_size: int = static_field() + out_size: int = static_field() + width_size: int = static_field() + depth: int = static_field() + + def __init__( + self, + in_size: int, + out_size: int, + width_size: int, + depth: int, + activation: Callable = jax.nn.relu, + final_activation: Callable = lambda x: x, + *, + key: "jax.random.PRNGKey", + **kwargs, + ): + """**Arguments**: + + - `in_size`: The size of the input layer. + - `out_size`: The size of the output layer. + - `width_size`: The size of each hidden layer. + - `depth`: The number of hidden layers. + - `activation`: The activation function after each hidden layer. Defaults to + ReLU. + - `final_activation`: The activation function after the output layer. Defaults + to the identity. + - `key`: A `jax.random.PRNGKey` used to provide randomness for parameter + initialisation. (Keyword only argument.) + """ + + super().__init__(**kwargs) + keys = jax.random.split(key, depth + 1) + layers = [] + if depth == 0: + layers.append(nn.Linear(in_size, out_size, key=keys[0])) + else: + layers.append(nn.Linear(in_size, width_size, key=keys[0])) + for i in range(depth - 1): + layers.append(nn.Linear(width_size, width_size, key=keys[i + 1])) + layers.append(nn.Linear(width_size, out_size, key=keys[-1])) + self.layers = layers + self.in_size = in_size + self.out_size = out_size + self.width_size = width_size + self.depth = depth + self.activation = activation # type: ignore + self.final_activation = final_activation # type: ignore + + def __call__(self, x, *, key: Optional["jax.random.PRNGKey"] = None): + """**Arguments:** + + - `x`: A JAX array with shape `(in_size,)`. + - `key`: Ignored; provided for compatibility with the rest of the Equinox API. + (Keyword only argument.) + + **Returns:** + + A JAX array with shape `(out_size,)`. + """ + for layer in self.layers[:-1]: + x = layer(x) + x = self.activation(x) + x = self.layers[-1](x) + x = self.final_activation(x) + return x + + +def assert_trees_not_close(a, b): + try: + assert_trees_all_close(jax.tree_util.tree_leaves(arrays_only(a)), jax.tree_util.tree_leaves(arrays_only(b))) + except AssertionError: + pass + else: + raise AssertionError("Trees are equal") + + +def arrays_only(x): + return eqx.filter(x, eqx.is_inexact_array_like) + + +def has_torch(): + try: + import torch # noqa F401 + + return True + except ImportError: + return False + + +def skip_if_no_torch(f): + return pytest.mark.skipif(not has_torch(), reason="torch not installed")(f) commit 139a88fe478745b4b12e6aaa8fe6957e6250d83d Date: 2023-06-26T11:08:50-07:00 minimize Haliax readme diff --git a/README.md b/README.md index 117c7b0..a7d2ceb 100644 --- a/README.md +++ b/README.md @@ -1,29 +1,16 @@ -# Levanter and Haliax -<!--intro-start--> - -Levanter and Haliax are libraries based on [Jax](https:://github.com/google/jax) and [Equinox](https://github.com/patrick-kidger/equinox) -for training deep learning models, especially [foundation models](https://en.wikipedia.org/wiki/Foundation_models). -Haliax is a named tensor library (modeled on [Tensor Considered Harmful](https://nlp.seas.harvard.edu/NamedTensor)) that focuses on improving the legibility and compositionality of deep learning code while still maintaining efficiency and scalability. -Levanter is a library for training foundation models built on top of Haliax. -In addition to the goals of legibility, efficiency, and scalability, Levanter further strives for bitwise reproducibility, -meaning that the same code with the same data will produce the exact same result, even in the presence of preemption and restarting from checkpoints. - -Levanter and Haliax were created by [Stanford's Center for Research on Foundation Models (CRFM)](https://crfm.stanford.edu/)'s research engineering team. ([We're hiring!](https://crfm.stanford.edu/apply.html)) You can also find us in the #levanter channel on the unofficial [Jax LLM Discord](https://discord.gg/FkRGNX3ND) - -<!--intro-end--> - # Haliax <!--haliax-intro-start--> > *Though you don’t seem to be much for listening, it’s best to be careful. If you managed to catch hold of even just a piece of my name, you’d have all manner of power over me.*<br/> > — Patrick Rothfuss, *The Name of the Wind* -Haliax is a Jax library for building neural networks with named tensors, in the tradition of Alexander Rush's [Tensor Considered Harmful](https://nlp.seas.harvard.edu/NamedTensor). -We use named tensors to improve the legibility and compositionality of our programs without sacrificing performance or scalability. - -Here's a minimal attention module implementation in Haliax. For a more detailed introduction, please see the [Haliax tutorial](https://colab.research.google.com/drive/1TiTcQQ4V5mopbgCu1SVl-oqJtXn7rFnC). +Haliax is a [JAX](https:://github.com/google/jax) library for building neural networks with named tensors, in the tradition of Alexander Rush's [Tensor Considered Harmful](https://nlp.seas.harvard.edu/NamedTensor). +Named tensors improve the legibility and compositionality of tensor programs by using named axes instead of positional indices +as in NumPy, PyTorch, etc. Here's a minimal attention module implementation in Haliax. For a more detailed introduction, +please see the [Haliax tutorial](https://colab.research.google.com/drive/1TiTcQQ4V5mopbgCu1SVl-oqJtXn7rFnC). ```python +# We use the excellent [Equinox](https://github.com/patrick-kidger/equinox) library for its module system and tree transformations. import equinox as eqx import jax import jax.numpy as jnp @@ -84,137 +71,23 @@ class Attention(eqx.Module): return x ``` -## Documentation for Haliax +Haliax is built to be fast: the generated code (using JAX/XLA) should be as fast as handwritten JAX code. Haliax is also built to be scalable: it +can support FSDP and Tensor Parallelism with just a few lines of code. Haliax's powers [Levanter](https://gihub.com/stanford-crfm/levanter), +our companion library for training large language models and other foundation models, with scale proven up to 20B parameters +and up to a TPU v3-256 pod slice. -Currently, we have two tutorials for Haliax: -* [Introduction to Haliax with Transformers](https://colab.research.google.com/drive/1TiTcQQ4V5mopbgCu1SVl-oqJtXn7rFnC) -* [Distributed Training in Haliax](https://colab.research.google.com/drive/1QX4yH3zRFF3Xiibf1aahETcSQ5nbcUMz) (including FSDP) +Haliax was created by [Stanford's Center for Research on Foundation Models (CRFM)](https://crfm.stanford.edu/)'s research engineering team. ([We're hiring!](https://crfm.stanford.edu/apply.html)) +You can find us in the #levanter channel on the unofficial [Jax LLM Discord](https://discord.gg/FkRGNX3ND). <!--haliax-intro-end--> -# Levanter -<!--levanter-intro-start--> -> *You could not prevent a thunderstorm, but you could use the electricity; you could not direct the wind, but you could trim your sail so as to propel your vessel as you pleased, no matter which way the wind blew.* <br/> -> — Cora L. V. Hatch - -Levanter is a library for training foundation models built on top of Haliax. Levanter strives for bitwise reproducibility, -meaning that the same code with the same data will produce the exact same result, even in the presence of preemption and restarting from checkpoints. -It supports distributed training on TPUs (and, soon, GPUs), including FSDP, tensor parallelism, distributed checkpointing, distributed data loading, and more. -Levanter integrates with WandB for logging and with the Hugging Face ecosystem for tokenizers, datasets, and model import and export. -<!--levanter-intro-end--> - -## Getting Started - -Here is a small set of examples to get you started. For more information about the various configuration options, please see the [Training Getting Started](docs/Getting-Started-Training.md) guide. -You can also use `--help` or poke around other configs to see all the options available to you. - -### Installing Levanter - -Please refer to the [Installation Guide](docs/Installation.md) for more information on how to install Levanter. - -If you're using a TPU, more complete documentation for setting that up is available [here](docs/Getting-Started-TPU-VM.md). GPU support is still in-progress; documentation is available [here](docs/Getting-Started-CUDA.md). - -<!--levanter-user-guide-start--> - -### Training a GPT2-nano - -As a kind of hello world, here's how you can train a GPT-2 "nano"-sized model on a small dataset. - -```bash -python -m levanter.main.train_lm --config_path config/gpt2_nano.yaml - -# alternatively, if you didn't use -e and are in a different directory -python -m levanter.main.train_lm --config_path gpt2_nano -``` - -This will train a GPT2-nano model on the [WikiText-103](https://blog.einstein.ai/the-wikitext-long-term-dependency-language-modeling-dataset/) dataset. - -### Training a GPT2-small on your own data - -You can also change the dataset by changing the `dataset` field in the config file. -If your dataset is a [Hugging Face dataset](https://huggingface.co/docs/datasets/loading_datasets.html), you can use the `data.id` field to specify it: - -```bash -python -m levanter.main.train_lm --config_path config/gpt2_small.yaml --data.id openwebtext +## Documentation -# optionally, you may specify a tokenizer and/or a cache directory, which may be local or on gcs -python -m levanter.main.train_lm --config_path config/gpt2_small.yaml --data.id openwebtext --data.tokenizer "EleutherAI/gpt-neox-20b" --data.cache_dir "gs://path/to/cache/dir" -``` - -If instead your data is a list of URLs, you can use the `data.train_urls` and `data.validation_urls` fields to specify them. -Data URLS can be local files, gcs files, or http(s) URLs, or anything that [fsspec](https://filesystem-spec.readthedocs.io/en/latest/) supports. -Levanter (really, fsspec) will automatically uncompress `.gz` and `.zstd` files, and probably other formats too. - -```bash -python -m levanter.main.train_lm --config_path config/gpt2_small.yaml --data.train_urls ["https://path/to/train/data_*.jsonl.gz"] --data.validation_urls ["https://path/to/val/data_*.jsonl.gz"] -``` - -### Customizing a Config File - -You can modify the config file to change the model, the dataset, the training parameters, and more. Here's -the `gpt2_small.yaml` file: - -```yaml -data: - train_urls: - - "gs://pubmed-mosaic/openwebtext-sharded/openwebtext_train.{1..128}-of-128.jsonl.gz" - validation_urls: - - "gs://pubmed-mosaic/openwebtext-sharded/openwebtext_val.{1..8}-of-8.jsonl.gz" - cache_dir: "gs://pubmed-mosaic/tokenized/openwebtext/" -model: - gpt2: - hidden_dim: 768 - num_heads: 12 - num_layers: 12 - seq_len: 1024 - gradient_checkpointing: true - scale_attn_by_inverse_layer_idx: true -trainer: - wandb: - project: "levanter" - tags: [ "openwebtext", "gpt2"] - - mp: p=f32,c=bfloat16 - model_axis_size: 1 - per_device_parallelism: 4 - - train_batch_size: 512 -optimizer: - learning_rate: 6E-4 - weight_decay: 0.1 - min_lr_ratio: 0.1 -``` - -### Other Architectures - -Currently, we support GPT-2, [Backpacks](http://backpackmodels.science/) and MosaicML's [MPT](https://www.mosaicml.com/blog/mpt-7b) -architectures. We plan to add more in the future. - -#### A Tiny Backpack Model - -```bash -python -m levanter.main.train_lm --config_path config/backpack_nano.yaml -``` - -#### Continued Pretraining with MPT - -```bash -python -m levanter.main.train_lm --config_path config/mpt_7b_continued.yaml -``` - - -## Distributed and Cloud Training - -### Training on a TPU Cloud VM - -Please see the [TPU Getting Started](docs/Getting-Started-TPU-VM.md) guide for more information on how to set up a TPU Cloud VM and run Levanter there. - -### Training with CUDA - -Please see the [CUDA Getting Started](docs/Getting-Started-CUDA.md) guide for more information on how to set up a CUDA environment and run Levanter there. +Currently, we have two tutorials for Haliax: -<!--levanter-user-guide-end--> +* [Introduction to Haliax with Transformers](https://colab.research.google.com/drive/1TiTcQQ4V5mopbgCu1SVl-oqJtXn7rFnC) +* [Distributed Training in Haliax](https://colab.research.google.com/drive/1QX4yH3zRFF3Xiibf1aahETcSQ5nbcUMz) (including FSDP) ## Contributing @@ -222,4 +95,4 @@ We welcome contributions! Please see [CONTRIBUTING.md](CONTRIBUTING.md) for more ## License -Levanter is licensed under the Apache License, Version 2.0. See [LICENSE](LICENSE) for the full license text. +Haliax is licensed under the Apache License, Version 2.0. See [LICENSE](LICENSE) for the full license text. commit 63ac4dc3ed73505bbfc35b1672e757f788aae161 Date: 2023-06-26T11:53:19-07:00 misc cleanup for separate haliax diff --git a/README.md b/README.md index a7d2ceb..a10649a 100644 --- a/README.md +++ b/README.md @@ -1,5 +1,5 @@ -# Haliax <!--haliax-intro-start--> +# Haliax > *Though you don’t seem to be much for listening, it’s best to be careful. If you managed to catch hold of even just a piece of my name, you’d have all manner of power over me.*<br/> > — Patrick Rothfuss, *The Name of the Wind* diff --git a/docs/Haliax.md b/docs/Haliax.md deleted file mode 100644 index d8dea7c..0000000 --- a/docs/Haliax.md +++ /dev/null @@ -1,5 +0,0 @@ -{% - include-markdown "../README.md" - start="<!--haliax-intro-start-->" - end="<!--haliax-intro-end-->" -%} diff --git a/docs/index.md b/docs/index.md index 415d2af..4d85141 100644 --- a/docs/index.md +++ b/docs/index.md @@ -1,17 +1,11 @@ {% - include-markdown "../README.md" - start="<!--intro-start-->" - end="<!--intro-end-->" +include-markdown "../README.md" +start="<!--haliax-intro-start-->" +end="<!--haliax-intro-end-->" %} -The code is released on GitHub: [Levanter Repository](https://github.com/stanford-crfm/levanter/). -To get started, please refer to the User Guide's chapters: +The code is released on GitHub: [Haliax Repository](https://github.com/stanford-crfm/haliax/). -- [Getting Started with CUDA](Getting-Started-CUDA.md) -- [Getting Started with TPU](Getting-Started-TPU-VM.md) -- [Getting Started to launch model training](Getting-Started-Training.md) -For a more detailed dive into how Levanter works, please refer to the [Overview](Overview.md). - -To contribute, please refer to the [Contributing Guide](https://github.com/stanford-crfm/levanter/blob/main/CONTRIBUTING.md). +To contribute, please refer to the [Contributing Guide](https://github.com/stanford-crfm/haliax/blob/main/CONTRIBUTING.md). diff --git a/docs/haliax/indexing.md b/docs/indexing.md similarity index 100% rename from docs/haliax/indexing.md rename to docs/indexing.md diff --git a/mkdocs.yml b/mkdocs.yml index fa4af39..175e269 100644 --- a/mkdocs.yml +++ b/mkdocs.yml @@ -1,9 +1,11 @@ -site_name: CRFM Levanter -repo_url: https://github.com/stanford-crfm/levanter/ +site_name: Haliax +repo_url: https://github.com/stanford-crfm/haliax/ edit_uri: blob/main/docs/ theme: - name: readthedocs + name: material highlightjs: false + features: + - content.code.copy plugins: - search - mkdocstrings: @@ -32,23 +34,20 @@ markdown_extensions: - pymdownx.details # Allowing hidden expandable regions denoted by ??? - pymdownx.snippets: # Include one Markdown file into another base_path: docs + - pymdownx.highlight: + anchor_linenums: true + line_spans: __span + pygments_lang_class: true + - pymdownx.inlinehilite + - pymdownx.snippets + - pymdownx.superfences - admonition - toc: permalink: "¤" # Adds a clickable permalink to each section heading toc_depth: 4 watch: - src - - scripts - - infra - - config + - docs nav: - 'Home': 'index.md' - - 'User Guide': 'Getting-Started-Training.md' - - Haliax: 'Haliax.md' - - 'Installation and Setup': - - 'Installation.md' - - 'Getting-Started-TPU-VM.md' - - 'Getting-Started-CUDA.md' - - Technical Documentation: - - 'Overview.md' - - 'design/Data-Loader-Design.md' + - Indexing and Slicing: 'indexing.md' diff --git a/pyproject.toml b/pyproject.toml index 21f26e7..da075d7 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -28,6 +28,18 @@ dependencies = [ "chex", ] +[project.optional-dependencies] +dev=["pytest >= 7.4.0", "mypy >= 0.910", "mkdocs >= 1.4.3", "mkdocs-material >= 7.3.3", "mkdocstrings >= 0.22.0", + "mkdocs-literate-nav >= 0.6.0", "mkdocs-macros-plugin >= 0.7.0", "mkdocstrings-python >= 1.1.2", + "mkdocs-include-markdown-plugin", + "pymdown-extensions", + "pygments", + "pymdown-extensions", +] + + + + [tool.hatch.build.sources] "src/haliax" = "haliax" commit cd5025251b4adf8633b4cedc3834de81cefa3064 Date: 2023-06-26T11:54:36-07:00 update toml diff --git a/pyproject.toml b/pyproject.toml index da075d7..add0079 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -7,9 +7,8 @@ name = "haliax" version = "1.0" authors = [ { name="David Hall", email="dlwh@cs.stanford.edu" }, - {name="Ivan Zhou", email="ivanz@stanford.edu"} ] -description = "Scalable Training for Foundation Models with Named Tensors and JAX" +description = "Named Tensors for legible deep learning in JAX" readme = "README.md" requires-python = ">=3.10" classifiers = [ @@ -38,9 +37,6 @@ dev=["pytest >= 7.4.0", "mypy >= 0.910", "mkdocs >= 1.4.3", "mkdocs-material >= ] - - - [tool.hatch.build.sources] "src/haliax" = "haliax" commit 7d03ff4c208bdbee881015b1856168824088c0a6 Date: 2023-06-26T11:57:21-07:00 forgot workflows diff --git a/.github/workflows/run_tests.yaml b/.github/workflows/run_tests.yaml new file mode 100644 index 0000000..624bfa7 --- /dev/null +++ b/.github/workflows/run_tests.yaml @@ -0,0 +1,33 @@ +name: Python package + +on: [push] + +jobs: + build: + + runs-on: ubuntu-latest + strategy: + matrix: + python-version: ["3.10"] + + steps: + - uses: actions/checkout@v3 + - name: Set up Python ${{ matrix.python-version }} + uses: actions/setup-python@v4 + with: + python-version: ${{ matrix.python-version }} + - name: Install dependencies + run: | + python -m pip install --upgrade pip + pip install flake8 pytest + pip install --upgrade "jax[cpu]==0.4.10" + pip install . +# - name: Lint with flake8 +# run: | +# # stop the build if there are Python syntax errors or undefined names +# flake8 . --count --select=E9,F63,F7,F82 --show-source --statistics +# # exit-zero treats all errors as warnings. The GitHub editor is 127 chars wide +# flake8 . --count --exit-zero --max-complexity=50 --max-line-length=127 --statistics + - name: Test with pytest + run: | + XLA_FLAGS=--xla_force_host_platform_device_count=8 PYTHONPATH=tests:src:. pytest tests diff --git a/pyproject.toml b/pyproject.toml index add0079..67e72fa 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -8,7 +8,7 @@ version = "1.0" authors = [ { name="David Hall", email="dlwh@cs.stanford.edu" }, ] -description = "Named Tensors for legible deep learning in JAX" +description = "Named Tensors for Legible Deep Learning in JAX" readme = "README.md" requires-python = ">=3.10" classifiers = [ commit 19a39b7bec80739eb296887cedd621ba3641d665 Date: 2023-06-26T11:59:16-07:00 call out Equinox diff --git a/README.md b/README.md index a10649a..1fd6711 100644 --- a/README.md +++ b/README.md @@ -10,7 +10,7 @@ as in NumPy, PyTorch, etc. Here's a minimal attention module implementation in H please see the [Haliax tutorial](https://colab.research.google.com/drive/1TiTcQQ4V5mopbgCu1SVl-oqJtXn7rFnC). ```python -# We use the excellent [Equinox](https://github.com/patrick-kidger/equinox) library for its module system and tree transformations. + import equinox as eqx import jax import jax.numpy as jnp @@ -71,6 +71,8 @@ class Attention(eqx.Module): return x ``` +(We use the excellent [Equinox](https://github.com/patrick-kidger/equinox) library for its module system and tree transformations.) + Haliax is built to be fast: the generated code (using JAX/XLA) should be as fast as handwritten JAX code. Haliax is also built to be scalable: it can support FSDP and Tensor Parallelism with just a few lines of code. Haliax's powers [Levanter](https://gihub.com/stanford-crfm/levanter), our companion library for training large language models and other foundation models, with scale proven up to 20B parameters commit 79e06f760229b4b53b6d2faed0e77b3ec71abb4f Date: 2023-06-26T13:06:55-07:00 v1.0.1 diff --git a/pyproject.toml b/pyproject.toml index 67e72fa..185b56b 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -1,10 +1,10 @@ [build-system] -requires = ["hatchling"] -build-backend = "hatchling.build" +requires = ["setuptools>=58.0.4", "wheel"] +build-backend = "setuptools.build_meta" [project] name = "haliax" -version = "1.0" +version = "1.0.1" authors = [ { name="David Hall", email="dlwh@cs.stanford.edu" }, ] @@ -36,36 +36,13 @@ dev=["pytest >= 7.4.0", "mypy >= 0.910", "mkdocs >= 1.4.3", "mkdocs-material >= "pymdown-extensions", ] +[options] +packages = ["haliax", "haliax.*"] -[tool.hatch.build.sources] -"src/haliax" = "haliax" +[options.package_data] +haliax = ["src/haliax/*"] -[tool.hatch.build.targets.wheel] -packages = ["src/haliax"] - [project.urls] "Homepage" = "https://github.com/stanford-crfm/haliax" "Bug Tracker" = "https://github.com/stanford-crfm/haliax/issues/" - - -[tool.black] -line-length = 119 -target-version = ["py310"] -preview = true - -[tool.isort] -profile = "black" -multi_line_output = 3 -lines_after_imports = 2 -include_trailing_comma = true -force_grid_wrap = 0 -use_parentheses = true -ensure_newline_before_comments = true -line_length = 119 - -[tool.mypy] -python_version = "3.10" - -[tool.mypy-haliax.core] -ignore_missing_imports = true commit 23e76fffafa76dde377c07772f3ff53422ba72d0 Date: 2023-06-28T10:58:17-07:00 Support PrefixLM attention mask (#5) diff --git a/src/haliax/nn/attention.py b/src/haliax/nn/attention.py index 06417fe..fd80303 100644 --- a/src/haliax/nn/attention.py +++ b/src/haliax/nn/attention.py @@ -144,6 +144,17 @@ def causal_mask(QPos: Axis, KPos: Axis) -> NamedArray: return haliax.arange(QPos).broadcast_axis(KPos) >= haliax.arange(KPos).broadcast_axis(QPos) +def prefix_lm_mask(QSeqLen: Axis, KSeqLen: Axis, prefix_len: int) -> NamedArray: + """Mask for the PrefixLM objective: fully connected before prefix_len, then causal after.""" + assert prefix_len >= 0 + assert prefix_len <= KSeqLen.size + + causal = causal_mask(QSeqLen, KSeqLen) + prefix = haliax.arange(KSeqLen) < prefix_len + + return prefix | causal + + def dropout_mask(axes: AxisSpec, dropout_rate: float, *, key: PRNGKey) -> NamedArray: """ Really just an alias for haliax.random.bernoulli. You can pass in e.g. Head, QPos and KPos commit 298a2fa63f44a536f60c3f83069c6912dacde745 Date: 2023-06-28T10:59:22-07:00 Merge remote-tracking branch 'origin/main' commit 7714dd7fda4338673a6bc18fdf8ff404f1533ad7 Date: 2023-06-29T00:33:00-07:00 move reductionfunction to its own file diff --git a/pyproject.toml b/pyproject.toml index 185b56b..c522eb7 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -42,6 +42,8 @@ packages = ["haliax", "haliax.*"] [options.package_data] haliax = ["src/haliax/*"] +[tool.isort] +profile = "black" [project.urls] "Homepage" = "https://github.com/stanford-crfm/haliax" diff --git a/src/haliax/__init__.py b/src/haliax/__init__.py index 9d75011..d48736c 100644 --- a/src/haliax/__init__.py +++ b/src/haliax/__init__.py @@ -1,10 +1,9 @@ -from typing import Optional, Protocol, Sequence +from typing import Optional, Sequence import jax import jax.numpy as jnp import haliax.random as random -from haliax import nn as nn from haliax import tree_util as tree_util from .core import ( @@ -32,7 +31,14 @@ from .hof import fold, scan, vmap from .ops import clip, isclose, pad_left, trace, tril, triu, where from .partitioning import auto_sharded, axis_mapping, named_jit, shard_with_axis_mapping from .types import Axis, AxisSelection, AxisSelector, AxisSpec -from .wrap import wrap_axiswise_call, wrap_elemwise_binary, wrap_elemwise_unary, wrap_reduction_call +from .wrap import ( + ReductionFunction, + SimpleReductionFunction, + wrap_axiswise_call, + wrap_elemwise_binary, + wrap_elemwise_unary, + wrap_reduction_call, +) # creation routines @@ -53,10 +59,14 @@ def ones(shape: AxisSpec, dtype=None) -> NamedArray: def full(shape: AxisSpec, fill_value, dtype=None) -> NamedArray: """Creates a NamedArray with all elements set to `fill_value`""" if isinstance(shape, Axis): - return NamedArray(jnp.full(shape=shape.size, fill_value=fill_value, dtype=dtype), (shape,)) + return NamedArray( + jnp.full(shape=shape.size, fill_value=fill_value, dtype=dtype), (shape,) + ) else: x_shape = tuple(x.size for x in shape) - return NamedArray(jnp.full(shape=x_shape, fill_value=fill_value, dtype=dtype), tuple(shape)) + return NamedArray( + jnp.full(shape=x_shape, fill_value=fill_value, dtype=dtype), tuple(shape) + ) def zeros_like(a: NamedArray, dtype=None) -> NamedArray: @@ -87,7 +97,9 @@ def stack(axis: AxisSelector, arrays: Sequence[NamedArray]) -> NamedArray: if len(arrays) == 0: return zeros(axis) arrays = [a.rearrange(arrays[0].axes) for a in arrays] - return NamedArray(jnp.stack([a.array for a in arrays], axis=0), (axis,) + arrays[0].axes) + return NamedArray( + jnp.stack([a.array for a in arrays], axis=0), (axis,) + arrays[0].axes + ) def concatenate(axis: AxisSelector, arrays: Sequence[NamedArray]) -> NamedArray: @@ -110,7 +122,9 @@ def concatenate(axis: AxisSelector, arrays: Sequence[NamedArray]) -> NamedArray: raise ValueError(f"Axis {axis.name} not found in 0th array {arrays[0]}") new_axes = arrays[0].axes[:axis_index] + (axis,) + arrays[0].axes[axis_index + 1 :] - return NamedArray(jnp.concatenate([a.array for a in arrays], axis=axis_index), new_axes) + return NamedArray( + jnp.concatenate([a.array for a in arrays], axis=axis_index), new_axes + ) # elementwise unary operations @@ -178,25 +192,15 @@ tanh = wrap_elemwise_unary(jnp.tanh) trunc = wrap_elemwise_unary(jnp.trunc) # Reduction functions - - -class ReductionFunction(Protocol): - def __call__( - self, array: NamedArray, axis: Optional[AxisSelection] = None, where: Optional[NamedArray] = None, **kwargs - ) -> NamedArray: - ... - - -class SimpleReductionFunction(Protocol): - def __call__(self, array: NamedArray, axis: Optional[AxisSelector] = None, **kwargs) -> NamedArray: - ... - - all: ReductionFunction = wrap_reduction_call(jnp.all) amax: ReductionFunction = wrap_reduction_call(jnp.amax) any: ReductionFunction = wrap_reduction_call(jnp.any) -argmax: SimpleReductionFunction = wrap_reduction_call(jnp.argmax, single_axis_only=True, supports_where=False) -argmin: SimpleReductionFunction = wrap_reduction_call(jnp.argmin, single_axis_only=True, supports_where=False) +argmax: SimpleReductionFunction = wrap_reduction_call( + jnp.argmax, single_axis_only=True, supports_where=False +) +argmin: SimpleReductionFunction = wrap_reduction_call( + jnp.argmin, single_axis_only=True, supports_where=False +) max: ReductionFunction = wrap_reduction_call(jnp.max) mean: ReductionFunction = wrap_reduction_call(jnp.mean) min: ReductionFunction = wrap_reduction_call(jnp.min) diff --git a/src/haliax/nn/__init__.py b/src/haliax/nn/__init__.py index e7de597..476ac74 100644 --- a/src/haliax/nn/__init__.py +++ b/src/haliax/nn/__init__.py @@ -10,14 +10,20 @@ import haliax.nn.attention as attention from ..core import NamedArray from ..types import Axis, AxisSelector, AxisSpec -from ..wrap import unwrap_namedarrays, wrap_axiswise_call, wrap_elemwise_unary, wrap_reduction_call +from ..util import UNSPECIFIED, Unspecified +from ..wrap import ( + ReductionFunction, + unwrap_namedarrays, + wrap_axiswise_call, + wrap_elemwise_unary, + wrap_reduction_call, +) from .dropout import Dropout, dropout from .embedding import Embedding from .linear import Linear from .normalization import LayerNorm from .scan import Stacked - relu = wrap_elemwise_unary(jnn.relu) relu6 = wrap_elemwise_unary(jnn.relu6) sigmoid = wrap_elemwise_unary(jnn.sigmoid) @@ -63,12 +69,16 @@ def standardize( raw_x, mean, variance, where = unwrap_namedarrays(x, mean, variance, where) axis_indices = x._lookup_indices(axis) - plain = jnn.standardize(raw_x, axis_indices, mean=mean, variance=variance, epsilon=epsilon, where=where) + plain = jnn.standardize( + raw_x, axis_indices, mean=mean, variance=variance, epsilon=epsilon, where=where + ) return NamedArray(plain, x.axes) @functools.wraps(jnn.one_hot) -def one_hot(x: Union[NamedArray, int], class_axis: Axis, *, dtype=jnp.float_) -> NamedArray: +def one_hot( + x: Union[NamedArray, int], class_axis: Axis, *, dtype=jnp.float_ +) -> NamedArray: if isinstance(x, NamedArray): array = jnn.one_hot(x.array, num_classes=class_axis.size, dtype=dtype) return NamedArray(array, x.axes + (class_axis,)) @@ -84,8 +94,18 @@ def cross_entropy_loss( pred_y: NamedArray, Label: AxisSelector, target_y: NamedArray, + reduction: Optional[ReductionFunction] | Unspecified = UNSPECIFIED, + where: Optional[NamedArray] = None, + reduction_axis: Optional[AxisSelector] = None, ) -> NamedArray: loss, _ = cross_entropy_loss_and_log_normalizers(pred_y, Label, target_y) + + if reduction is UNSPECIFIED: + reduction = haliax.mean + + if reduction is not None: + loss = reduction(loss, where=where, axis=reduction_axis) + return loss diff --git a/src/haliax/util.py b/src/haliax/util.py index 3bd57ef..f2eb5ca 100644 --- a/src/haliax/util.py +++ b/src/haliax/util.py @@ -1,8 +1,7 @@ -from typing import Callable, Sequence, Tuple, Type, TypeVar, Union +from typing import Callable, Sequence, Tuple, Type, TypeAlias, TypeVar, Union from haliax.jax_utils import is_jax_array_like - T = TypeVar("T") @@ -10,6 +9,9 @@ py_slice = slice slice_t = Type[slice] +Unspecified: TypeAlias = type("NotSpecified", (), {}) # type: ignore +UNSPECIFIED = Unspecified() + def is_named_array(leaf): from .core import NamedArray @@ -34,7 +36,9 @@ class StringHolderEnum(type): def __new__(cls, name, bases, members): # this just iterates through the class dict and removes # all the dunder methods - cls.members = [v for k, v in members.items() if not k.startswith("__") and not callable(v)] + cls.members = [ + v for k, v in members.items() if not k.startswith("__") and not callable(v) + ] return super().__new__(cls, name, bases, members) # giving your class an __iter__ method gives you membership checking diff --git a/src/haliax/wrap.py b/src/haliax/wrap.py index 746f6ab..0709107 100644 --- a/src/haliax/wrap.py +++ b/src/haliax/wrap.py @@ -1,5 +1,5 @@ import functools -from typing import Optional +from typing import Optional, Protocol import jax import jax.numpy as jnp @@ -7,7 +7,7 @@ import jax.numpy as jnp from haliax.core import NamedArray, _broadcast_order, broadcast_to, selects_axis from haliax.util import ensure_tuple -from .types import AxisSelection +from .types import AxisSelection, AxisSelector def wrap_elemwise_unary(f): @@ -23,9 +23,13 @@ def wrap_elemwise_unary(f): return wrapper -def wrap_reduction_call(fn, single_axis_only: bool = False, supports_where: bool = True): +def wrap_reduction_call( + fn, single_axis_only: bool = False, supports_where: bool = True +): @functools.wraps(fn) - def wrapper(a, axis: Optional[AxisSelection] = None, where: NamedArray = None, **kwargs): + def wrapper( + a, axis: Optional[AxisSelection] = None, where: NamedArray = None, **kwargs + ): kwargs = dict(kwargs) if where is not None and not supports_where: raise ValueError(f"where is not supported by {fn.__name__}") @@ -40,7 +44,9 @@ def wrap_reduction_call(fn, single_axis_only: bool = False, supports_where: bool if isinstance(a, NamedArray): if where is not None: if not isinstance(where, NamedArray): - raise TypeError("where must be a NamedArray if a is a NamedArray") + raise TypeError( + "where must be a NamedArray if a is a NamedArray" + ) where = broadcast_to(where, a.axes) kwargs["where"] = where.array @@ -70,7 +76,9 @@ def wrap_reduction_call(fn, single_axis_only: bool = False, supports_where: bool kwargs["where"] = where return fn(a, axis=axis, **kwargs) - return jax.tree_util.tree_map(reduce_one_leaf, a, is_leaf=lambda x: isinstance(x, NamedArray)) + return jax.tree_util.tree_map( + reduce_one_leaf, a, is_leaf=lambda x: isinstance(x, NamedArray) + ) wrapper.__doc__ = ( """ @@ -145,3 +153,21 @@ __all__ = [ "wrap_elemwise_binary", "unwrap_namedarrays", ] + + +class ReductionFunction(Protocol): + def __call__( + self, + array: NamedArray, + axis: Optional[AxisSelection] = None, + where: Optional[NamedArray] = None, + **kwargs, + ) -> NamedArray: + ... + + +class SimpleReductionFunction(Protocol): + def __call__( + self, array: NamedArray, axis: Optional[AxisSelector] = None, **kwargs + ) -> NamedArray: + ... commit d949d1e2a01ab4a401ac8f1bb9e00e663edf1159 Date: 2023-06-29T16:41:17-07:00 cache causal mask?: diff --git a/src/haliax/__init__.py b/src/haliax/__init__.py index d48736c..6a5d0ff 100644 --- a/src/haliax/__init__.py +++ b/src/haliax/__init__.py @@ -3,6 +3,7 @@ from typing import Optional, Sequence import jax import jax.numpy as jnp +import haliax.nn as nn import haliax.random as random from haliax import tree_util as tree_util diff --git a/src/haliax/nn/attention.py b/src/haliax/nn/attention.py index fd80303..91e46ea 100644 --- a/src/haliax/nn/attention.py +++ b/src/haliax/nn/attention.py @@ -1,3 +1,4 @@ +import functools import math from typing import List, Optional @@ -11,7 +12,6 @@ import haliax.random as hrandom from haliax.core import NamedArray from haliax.types import Axis, AxisSelection, AxisSpec, PrecisionLike - # With attention we usually distinguish between the mask and the bias, though the former is just a special case of the # latter. In practice, the mask is a boolean array that is applied using `where` to the logits, while the bias is a # float array that is added to the logits. The mask is usually used to prevent attention to certain positions, while @@ -107,7 +107,9 @@ def dot_product_attention( key = key.rename({KPos: QPos}) value = value.rename({KPos: QPos}) - weights = dot_product_attention_weights(KeySize, KPos, query, key, mask, bias, attention_dtype, precision) + weights = dot_product_attention_weights( + KeySize, KPos, query, key, mask, bias, attention_dtype, precision + ) return haliax.dot(KPos, weights, value) @@ -116,7 +118,9 @@ def mask_to_bias(mask: NamedArray, mask_value: float = -1e9) -> NamedArray: return mask * mask_value -def combine_masks_and(mask1: Optional[NamedArray], mask2: Optional[NamedArray]) -> Optional[NamedArray]: +def combine_masks_and( + mask1: Optional[NamedArray], mask2: Optional[NamedArray] +) -> Optional[NamedArray]: if mask1 is None: return mask2 if mask2 is None: @@ -124,7 +128,9 @@ def combine_masks_and(mask1: Optional[NamedArray], mask2: Optional[NamedArray]) return mask1 & mask2 -def combine_masks_or(mask1: Optional[NamedArray], mask2: Optional[NamedArray]) -> Optional[NamedArray]: +def combine_masks_or( + mask1: Optional[NamedArray], mask2: Optional[NamedArray] +) -> Optional[NamedArray]: if mask1 is None: return mask2 if mask2 is None: @@ -132,6 +138,8 @@ def combine_masks_or(mask1: Optional[NamedArray], mask2: Optional[NamedArray]) - return mask1 | mask2 +# this ends up being surprisingly slow on CPU, so cache it +@functools.lru_cache(maxsize=8) def causal_mask(QPos: Axis, KPos: Axis) -> NamedArray: """ Creates a causal mask for attention. @@ -141,7 +149,9 @@ def causal_mask(QPos: Axis, KPos: Axis) -> NamedArray: :return: NamedArray of shape (QPos, KPos) """ # copilot wrote this and i'm just blown away - return haliax.arange(QPos).broadcast_axis(KPos) >= haliax.arange(KPos).broadcast_axis(QPos) + return haliax.arange(QPos).broadcast_axis(KPos) >= haliax.arange( + KPos + ).broadcast_axis(QPos) def prefix_lm_mask(QSeqLen: Axis, KSeqLen: Axis, prefix_len: int) -> NamedArray: @@ -162,7 +172,9 @@ def dropout_mask(axes: AxisSpec, dropout_rate: float, *, key: PRNGKey) -> NamedA return hrandom.bernoulli(key, shape=axes, p=1 - dropout_rate) -def forgetful_causal_mask(KPos: Axis, mask_prob: float, sample_prob: bool = True, *, key: PRNGKey) -> NamedArray: +def forgetful_causal_mask( + KPos: Axis, mask_prob: float, sample_prob: bool = True, *, key: PRNGKey +) -> NamedArray: """ Forgetful Context Masking a la https://arxiv.org/abs/2210.13432. Randomly drops out positions from the key sequence. Reportedly better than normal attention dropout. Almost certainly faster. @@ -173,12 +185,17 @@ def forgetful_causal_mask(KPos: Axis, mask_prob: float, sample_prob: bool = True :param mask_prob: Probability a position to mask :param sample_prob: If True, sample the prob between 0 and the provided prob (this is what the paper does) """ - zeroth_on = haliax.nn.one_hot(0, KPos, dtype=jnp.bool_) # always allow 0th position if mask_prob == 0: - return jnp.ones((KPos.size,), dtype=jnp.bool_) + return haliax.ones(KPos, dtype=jnp.bool_) elif mask_prob == 1: + zeroth_on = haliax.nn.one_hot( + 0, KPos, dtype=jnp.bool_ + ) # always allow 0th position return zeroth_on else: + zeroth_on = haliax.nn.one_hot( + 0, KPos, dtype=jnp.bool_ + ) # always allow 0th position if sample_prob: key, subkey = jax.random.split(key) mask_prob = jax.random.uniform(subkey, shape=(), minval=0, maxval=mask_prob) @@ -201,11 +218,15 @@ def _get_alibi_slopes(heads: int, bias_max: float) -> List[float]: closest_power_of_2 = 2 ** math.floor(math.log2(heads)) return ( get_slopes_power_of_2(closest_power_of_2) - + get_slopes_power_of_2(2 * closest_power_of_2)[0::2][: heads - closest_power_of_2] + + get_slopes_power_of_2(2 * closest_power_of_2)[0::2][ + : heads - closest_power_of_2 + ] ) -def alibi_attention_bias(Heads: Axis, KPos: Axis, bias_max: float = 8, dtype=jnp.float32) -> NamedArray: +def alibi_attention_bias( + Heads: Axis, KPos: Axis, bias_max: float = 8, dtype=jnp.float32 +) -> NamedArray: """ Creates an attention bias for alibi attention. commit e951593d4c94f5d7a4b7c0b5626ddcf5be06b3d8 Date: 2023-06-29T20:55:21-07:00 Revert "cache causal mask?:" This reverts commit d949d1e2a01ab4a401ac8f1bb9e00e663edf1159. diff --git a/src/haliax/__init__.py b/src/haliax/__init__.py index 6a5d0ff..d48736c 100644 --- a/src/haliax/__init__.py +++ b/src/haliax/__init__.py @@ -3,7 +3,6 @@ from typing import Optional, Sequence import jax import jax.numpy as jnp -import haliax.nn as nn import haliax.random as random from haliax import tree_util as tree_util diff --git a/src/haliax/nn/attention.py b/src/haliax/nn/attention.py index 91e46ea..fd80303 100644 --- a/src/haliax/nn/attention.py +++ b/src/haliax/nn/attention.py @@ -1,4 +1,3 @@ -import functools import math from typing import List, Optional @@ -12,6 +11,7 @@ import haliax.random as hrandom from haliax.core import NamedArray from haliax.types import Axis, AxisSelection, AxisSpec, PrecisionLike + # With attention we usually distinguish between the mask and the bias, though the former is just a special case of the # latter. In practice, the mask is a boolean array that is applied using `where` to the logits, while the bias is a # float array that is added to the logits. The mask is usually used to prevent attention to certain positions, while @@ -107,9 +107,7 @@ def dot_product_attention( key = key.rename({KPos: QPos}) value = value.rename({KPos: QPos}) - weights = dot_product_attention_weights( - KeySize, KPos, query, key, mask, bias, attention_dtype, precision - ) + weights = dot_product_attention_weights(KeySize, KPos, query, key, mask, bias, attention_dtype, precision) return haliax.dot(KPos, weights, value) @@ -118,9 +116,7 @@ def mask_to_bias(mask: NamedArray, mask_value: float = -1e9) -> NamedArray: return mask * mask_value -def combine_masks_and( - mask1: Optional[NamedArray], mask2: Optional[NamedArray] -) -> Optional[NamedArray]: +def combine_masks_and(mask1: Optional[NamedArray], mask2: Optional[NamedArray]) -> Optional[NamedArray]: if mask1 is None: return mask2 if mask2 is None: @@ -128,9 +124,7 @@ def combine_masks_and( return mask1 & mask2 -def combine_masks_or( - mask1: Optional[NamedArray], mask2: Optional[NamedArray] -) -> Optional[NamedArray]: +def combine_masks_or(mask1: Optional[NamedArray], mask2: Optional[NamedArray]) -> Optional[NamedArray]: if mask1 is None: return mask2 if mask2 is None: @@ -138,8 +132,6 @@ def combine_masks_or( return mask1 | mask2 -# this ends up being surprisingly slow on CPU, so cache it -@functools.lru_cache(maxsize=8) def causal_mask(QPos: Axis, KPos: Axis) -> NamedArray: """ Creates a causal mask for attention. @@ -149,9 +141,7 @@ def causal_mask(QPos: Axis, KPos: Axis) -> NamedArray: :return: NamedArray of shape (QPos, KPos) """ # copilot wrote this and i'm just blown away - return haliax.arange(QPos).broadcast_axis(KPos) >= haliax.arange( - KPos - ).broadcast_axis(QPos) + return haliax.arange(QPos).broadcast_axis(KPos) >= haliax.arange(KPos).broadcast_axis(QPos) def prefix_lm_mask(QSeqLen: Axis, KSeqLen: Axis, prefix_len: int) -> NamedArray: @@ -172,9 +162,7 @@ def dropout_mask(axes: AxisSpec, dropout_rate: float, *, key: PRNGKey) -> NamedA return hrandom.bernoulli(key, shape=axes, p=1 - dropout_rate) -def forgetful_causal_mask( - KPos: Axis, mask_prob: float, sample_prob: bool = True, *, key: PRNGKey -) -> NamedArray: +def forgetful_causal_mask(KPos: Axis, mask_prob: float, sample_prob: bool = True, *, key: PRNGKey) -> NamedArray: """ Forgetful Context Masking a la https://arxiv.org/abs/2210.13432. Randomly drops out positions from the key sequence. Reportedly better than normal attention dropout. Almost certainly faster. @@ -185,17 +173,12 @@ def forgetful_causal_mask( :param mask_prob: Probability a position to mask :param sample_prob: If True, sample the prob between 0 and the provided prob (this is what the paper does) """ + zeroth_on = haliax.nn.one_hot(0, KPos, dtype=jnp.bool_) # always allow 0th position if mask_prob == 0: - return haliax.ones(KPos, dtype=jnp.bool_) + return jnp.ones((KPos.size,), dtype=jnp.bool_) elif mask_prob == 1: - zeroth_on = haliax.nn.one_hot( - 0, KPos, dtype=jnp.bool_ - ) # always allow 0th position return zeroth_on else: - zeroth_on = haliax.nn.one_hot( - 0, KPos, dtype=jnp.bool_ - ) # always allow 0th position if sample_prob: key, subkey = jax.random.split(key) mask_prob = jax.random.uniform(subkey, shape=(), minval=0, maxval=mask_prob) @@ -218,15 +201,11 @@ def _get_alibi_slopes(heads: int, bias_max: float) -> List[float]: closest_power_of_2 = 2 ** math.floor(math.log2(heads)) return ( get_slopes_power_of_2(closest_power_of_2) - + get_slopes_power_of_2(2 * closest_power_of_2)[0::2][ - : heads - closest_power_of_2 - ] + + get_slopes_power_of_2(2 * closest_power_of_2)[0::2][: heads - closest_power_of_2] ) -def alibi_attention_bias( - Heads: Axis, KPos: Axis, bias_max: float = 8, dtype=jnp.float32 -) -> NamedArray: +def alibi_attention_bias(Heads: Axis, KPos: Axis, bias_max: float = 8, dtype=jnp.float32) -> NamedArray: """ Creates an attention bias for alibi attention. commit 7a077f0b57e9a2a7da1c5fb4c7c4b1296364bcc1 Date: 2023-06-30T00:35:25-07:00 remove an assert in prefix_lm_mask so it can be jitted diff --git a/src/haliax/nn/attention.py b/src/haliax/nn/attention.py index fd80303..f2910cd 100644 --- a/src/haliax/nn/attention.py +++ b/src/haliax/nn/attention.py @@ -11,7 +11,6 @@ import haliax.random as hrandom from haliax.core import NamedArray from haliax.types import Axis, AxisSelection, AxisSpec, PrecisionLike - # With attention we usually distinguish between the mask and the bias, though the former is just a special case of the # latter. In practice, the mask is a boolean array that is applied using `where` to the logits, while the bias is a # float array that is added to the logits. The mask is usually used to prevent attention to certain positions, while @@ -107,7 +106,9 @@ def dot_product_attention( key = key.rename({KPos: QPos}) value = value.rename({KPos: QPos}) - weights = dot_product_attention_weights(KeySize, KPos, query, key, mask, bias, attention_dtype, precision) + weights = dot_product_attention_weights( + KeySize, KPos, query, key, mask, bias, attention_dtype, precision + ) return haliax.dot(KPos, weights, value) @@ -116,7 +117,9 @@ def mask_to_bias(mask: NamedArray, mask_value: float = -1e9) -> NamedArray: return mask * mask_value -def combine_masks_and(mask1: Optional[NamedArray], mask2: Optional[NamedArray]) -> Optional[NamedArray]: +def combine_masks_and( + mask1: Optional[NamedArray], mask2: Optional[NamedArray] +) -> Optional[NamedArray]: if mask1 is None: return mask2 if mask2 is None: @@ -124,7 +127,9 @@ def combine_masks_and(mask1: Optional[NamedArray], mask2: Optional[NamedArray]) return mask1 & mask2 -def combine_masks_or(mask1: Optional[NamedArray], mask2: Optional[NamedArray]) -> Optional[NamedArray]: +def combine_masks_or( + mask1: Optional[NamedArray], mask2: Optional[NamedArray] +) -> Optional[NamedArray]: if mask1 is None: return mask2 if mask2 is None: @@ -141,13 +146,17 @@ def causal_mask(QPos: Axis, KPos: Axis) -> NamedArray: :return: NamedArray of shape (QPos, KPos) """ # copilot wrote this and i'm just blown away - return haliax.arange(QPos).broadcast_axis(KPos) >= haliax.arange(KPos).broadcast_axis(QPos) + return haliax.arange(QPos).broadcast_axis(KPos) >= haliax.arange( + KPos + ).broadcast_axis(QPos) def prefix_lm_mask(QSeqLen: Axis, KSeqLen: Axis, prefix_len: int) -> NamedArray: """Mask for the PrefixLM objective: fully connected before prefix_len, then causal after.""" - assert prefix_len >= 0 - assert prefix_len <= KSeqLen.size + # sometimes prefix_len is a tracer so we can't assert + if isinstance(prefix_len, int): + assert prefix_len >= 0 + assert prefix_len <= KSeqLen.size causal = causal_mask(QSeqLen, KSeqLen) prefix = haliax.arange(KSeqLen) < prefix_len @@ -162,7 +171,9 @@ def dropout_mask(axes: AxisSpec, dropout_rate: float, *, key: PRNGKey) -> NamedA return hrandom.bernoulli(key, shape=axes, p=1 - dropout_rate) -def forgetful_causal_mask(KPos: Axis, mask_prob: float, sample_prob: bool = True, *, key: PRNGKey) -> NamedArray: +def forgetful_causal_mask( + KPos: Axis, mask_prob: float, sample_prob: bool = True, *, key: PRNGKey +) -> NamedArray: """ Forgetful Context Masking a la https://arxiv.org/abs/2210.13432. Randomly drops out positions from the key sequence. Reportedly better than normal attention dropout. Almost certainly faster. @@ -201,11 +212,15 @@ def _get_alibi_slopes(heads: int, bias_max: float) -> List[float]: closest_power_of_2 = 2 ** math.floor(math.log2(heads)) return ( get_slopes_power_of_2(closest_power_of_2) - + get_slopes_power_of_2(2 * closest_power_of_2)[0::2][: heads - closest_power_of_2] + + get_slopes_power_of_2(2 * closest_power_of_2)[0::2][ + : heads - closest_power_of_2 + ] ) -def alibi_attention_bias(Heads: Axis, KPos: Axis, bias_max: float = 8, dtype=jnp.float32) -> NamedArray: +def alibi_attention_bias( + Heads: Axis, KPos: Axis, bias_max: float = 8, dtype=jnp.float32 +) -> NamedArray: """ Creates an attention bias for alibi attention. commit bf66545f249f371079075214fe5c9a8bac2b2238 Date: 2023-07-03T10:02:54-07:00 Run pre commit in CI (#6) * run pre-commit in ci * wip * fix black config * sigh * sigh * fix flake repo diff --git a/.github/workflows/run_pre_commit.yaml b/.github/workflows/run_pre_commit.yaml new file mode 100644 index 0000000..039594d --- /dev/null +++ b/.github/workflows/run_pre_commit.yaml @@ -0,0 +1,34 @@ +name: Python package + +on: [push] + +jobs: + build: + + runs-on: ubuntu-latest + strategy: + matrix: + python-version: ["3.10"] + + steps: + - uses: actions/checkout@v3 + - name: Set up Python ${{ matrix.python-version }} + uses: actions/setup-python@v4 + with: + python-version: ${{ matrix.python-version }} + - name: Install dependencies + run: | + python -m pip install --upgrade pip + pip install flake8 pytest pre-commit + pip install --upgrade "jax[cpu]==0.4.10" + pip install . +# - name: Lint with flake8 +# run: | +# # stop the build if there are Python syntax errors or undefined names +# flake8 . --count --select=E9,F63,F7,F82 --show-source --statistics +# # exit-zero treats all errors as warnings. The GitHub editor is 127 chars wide +# flake8 . --count --exit-zero --max-complexity=50 --max-line-length=127 --statistics + - name: "Run Pre-commit" + run: | + pre-commit run --all-files --show-diff-on-failure + diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml index 67b877d..1a53e46 100644 --- a/.pre-commit-config.yaml +++ b/.pre-commit-config.yaml @@ -26,7 +26,7 @@ repos: hooks: - id: isort -- repo: https://gitlab.com/pycqa/flake8 +- repo: https://github.com/PyCQA/flake8 rev: 3.9.2 hooks: - id: flake8 diff --git a/pyproject.toml b/pyproject.toml index c522eb7..d854b10 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -42,8 +42,21 @@ packages = ["haliax", "haliax.*"] [options.package_data] haliax = ["src/haliax/*"] +[tool.black] +line-length = 119 +target-version = ["py310"] +preview = true + [tool.isort] profile = "black" +multi_line_output = 3 +lines_after_imports = 2 +include_trailing_comma = true +force_grid_wrap = 0 +use_parentheses = true +ensure_newline_before_comments = true +line_length = 119 +src_paths = ["src", "tests"] [project.urls] "Homepage" = "https://github.com/stanford-crfm/haliax" diff --git a/src/haliax/__init__.py b/src/haliax/__init__.py index d48736c..6462c78 100644 --- a/src/haliax/__init__.py +++ b/src/haliax/__init__.py @@ -59,14 +59,10 @@ def ones(shape: AxisSpec, dtype=None) -> NamedArray: def full(shape: AxisSpec, fill_value, dtype=None) -> NamedArray: """Creates a NamedArray with all elements set to `fill_value`""" if isinstance(shape, Axis): - return NamedArray( - jnp.full(shape=shape.size, fill_value=fill_value, dtype=dtype), (shape,) - ) + return NamedArray(jnp.full(shape=shape.size, fill_value=fill_value, dtype=dtype), (shape,)) else: x_shape = tuple(x.size for x in shape) - return NamedArray( - jnp.full(shape=x_shape, fill_value=fill_value, dtype=dtype), tuple(shape) - ) + return NamedArray(jnp.full(shape=x_shape, fill_value=fill_value, dtype=dtype), tuple(shape)) def zeros_like(a: NamedArray, dtype=None) -> NamedArray: @@ -97,9 +93,7 @@ def stack(axis: AxisSelector, arrays: Sequence[NamedArray]) -> NamedArray: if len(arrays) == 0: return zeros(axis) arrays = [a.rearrange(arrays[0].axes) for a in arrays] - return NamedArray( - jnp.stack([a.array for a in arrays], axis=0), (axis,) + arrays[0].axes - ) + return NamedArray(jnp.stack([a.array for a in arrays], axis=0), (axis,) + arrays[0].axes) def concatenate(axis: AxisSelector, arrays: Sequence[NamedArray]) -> NamedArray: @@ -122,9 +116,7 @@ def concatenate(axis: AxisSelector, arrays: Sequence[NamedArray]) -> NamedArray: raise ValueError(f"Axis {axis.name} not found in 0th array {arrays[0]}") new_axes = arrays[0].axes[:axis_index] + (axis,) + arrays[0].axes[axis_index + 1 :] - return NamedArray( - jnp.concatenate([a.array for a in arrays], axis=axis_index), new_axes - ) + return NamedArray(jnp.concatenate([a.array for a in arrays], axis=axis_index), new_axes) # elementwise unary operations @@ -195,12 +187,8 @@ trunc = wrap_elemwise_unary(jnp.trunc) all: ReductionFunction = wrap_reduction_call(jnp.all) amax: ReductionFunction = wrap_reduction_call(jnp.amax) any: ReductionFunction = wrap_reduction_call(jnp.any) -argmax: SimpleReductionFunction = wrap_reduction_call( - jnp.argmax, single_axis_only=True, supports_where=False -) -argmin: SimpleReductionFunction = wrap_reduction_call( - jnp.argmin, single_axis_only=True, supports_where=False -) +argmax: SimpleReductionFunction = wrap_reduction_call(jnp.argmax, single_axis_only=True, supports_where=False) +argmin: SimpleReductionFunction = wrap_reduction_call(jnp.argmin, single_axis_only=True, supports_where=False) max: ReductionFunction = wrap_reduction_call(jnp.max) mean: ReductionFunction = wrap_reduction_call(jnp.mean) min: ReductionFunction = wrap_reduction_call(jnp.min) diff --git a/src/haliax/nn/__init__.py b/src/haliax/nn/__init__.py index 476ac74..903ef49 100644 --- a/src/haliax/nn/__init__.py +++ b/src/haliax/nn/__init__.py @@ -11,19 +11,14 @@ import haliax.nn.attention as attention from ..core import NamedArray from ..types import Axis, AxisSelector, AxisSpec from ..util import UNSPECIFIED, Unspecified -from ..wrap import ( - ReductionFunction, - unwrap_namedarrays, - wrap_axiswise_call, - wrap_elemwise_unary, - wrap_reduction_call, -) +from ..wrap import ReductionFunction, unwrap_namedarrays, wrap_axiswise_call, wrap_elemwise_unary, wrap_reduction_call from .dropout import Dropout, dropout from .embedding import Embedding from .linear import Linear from .normalization import LayerNorm from .scan import Stacked + relu = wrap_elemwise_unary(jnn.relu) relu6 = wrap_elemwise_unary(jnn.relu6) sigmoid = wrap_elemwise_unary(jnn.sigmoid) @@ -69,16 +64,12 @@ def standardize( raw_x, mean, variance, where = unwrap_namedarrays(x, mean, variance, where) axis_indices = x._lookup_indices(axis) - plain = jnn.standardize( - raw_x, axis_indices, mean=mean, variance=variance, epsilon=epsilon, where=where - ) + plain = jnn.standardize(raw_x, axis_indices, mean=mean, variance=variance, epsilon=epsilon, where=where) return NamedArray(plain, x.axes) @functools.wraps(jnn.one_hot) -def one_hot( - x: Union[NamedArray, int], class_axis: Axis, *, dtype=jnp.float_ -) -> NamedArray: +def one_hot(x: Union[NamedArray, int], class_axis: Axis, *, dtype=jnp.float_) -> NamedArray: if isinstance(x, NamedArray): array = jnn.one_hot(x.array, num_classes=class_axis.size, dtype=dtype) return NamedArray(array, x.axes + (class_axis,)) diff --git a/src/haliax/nn/attention.py b/src/haliax/nn/attention.py index f2910cd..958afe0 100644 --- a/src/haliax/nn/attention.py +++ b/src/haliax/nn/attention.py @@ -11,6 +11,7 @@ import haliax.random as hrandom from haliax.core import NamedArray from haliax.types import Axis, AxisSelection, AxisSpec, PrecisionLike + # With attention we usually distinguish between the mask and the bias, though the former is just a special case of the # latter. In practice, the mask is a boolean array that is applied using `where` to the logits, while the bias is a # float array that is added to the logits. The mask is usually used to prevent attention to certain positions, while @@ -106,9 +107,7 @@ def dot_product_attention( key = key.rename({KPos: QPos}) value = value.rename({KPos: QPos}) - weights = dot_product_attention_weights( - KeySize, KPos, query, key, mask, bias, attention_dtype, precision - ) + weights = dot_product_attention_weights(KeySize, KPos, query, key, mask, bias, attention_dtype, precision) return haliax.dot(KPos, weights, value) @@ -117,9 +116,7 @@ def mask_to_bias(mask: NamedArray, mask_value: float = -1e9) -> NamedArray: return mask * mask_value -def combine_masks_and( - mask1: Optional[NamedArray], mask2: Optional[NamedArray] -) -> Optional[NamedArray]: +def combine_masks_and(mask1: Optional[NamedArray], mask2: Optional[NamedArray]) -> Optional[NamedArray]: if mask1 is None: return mask2 if mask2 is None: @@ -127,9 +124,7 @@ def combine_masks_and( return mask1 & mask2 -def combine_masks_or( - mask1: Optional[NamedArray], mask2: Optional[NamedArray] -) -> Optional[NamedArray]: +def combine_masks_or(mask1: Optional[NamedArray], mask2: Optional[NamedArray]) -> Optional[NamedArray]: if mask1 is None: return mask2 if mask2 is None: @@ -146,9 +141,7 @@ def causal_mask(QPos: Axis, KPos: Axis) -> NamedArray: :return: NamedArray of shape (QPos, KPos) """ # copilot wrote this and i'm just blown away - return haliax.arange(QPos).broadcast_axis(KPos) >= haliax.arange( - KPos - ).broadcast_axis(QPos) + return haliax.arange(QPos).broadcast_axis(KPos) >= haliax.arange(KPos).broadcast_axis(QPos) def prefix_lm_mask(QSeqLen: Axis, KSeqLen: Axis, prefix_len: int) -> NamedArray: @@ -171,9 +164,7 @@ def dropout_mask(axes: AxisSpec, dropout_rate: float, *, key: PRNGKey) -> NamedA return hrandom.bernoulli(key, shape=axes, p=1 - dropout_rate) -def forgetful_causal_mask( - KPos: Axis, mask_prob: float, sample_prob: bool = True, *, key: PRNGKey -) -> NamedArray: +def forgetful_causal_mask(KPos: Axis, mask_prob: float, sample_prob: bool = True, *, key: PRNGKey) -> NamedArray: """ Forgetful Context Masking a la https://arxiv.org/abs/2210.13432. Randomly drops out positions from the key sequence. Reportedly better than normal attention dropout. Almost certainly faster. @@ -212,15 +203,11 @@ def _get_alibi_slopes(heads: int, bias_max: float) -> List[float]: closest_power_of_2 = 2 ** math.floor(math.log2(heads)) return ( get_slopes_power_of_2(closest_power_of_2) - + get_slopes_power_of_2(2 * closest_power_of_2)[0::2][ - : heads - closest_power_of_2 - ] + + get_slopes_power_of_2(2 * closest_power_of_2)[0::2][: heads - closest_power_of_2] ) -def alibi_attention_bias( - Heads: Axis, KPos: Axis, bias_max: float = 8, dtype=jnp.float32 -) -> NamedArray: +def alibi_attention_bias(Heads: Axis, KPos: Axis, bias_max: float = 8, dtype=jnp.float32) -> NamedArray: """ Creates an attention bias for alibi attention. diff --git a/src/haliax/util.py b/src/haliax/util.py index f2eb5ca..7badc03 100644 --- a/src/haliax/util.py +++ b/src/haliax/util.py @@ -2,6 +2,7 @@ from typing import Callable, Sequence, Tuple, Type, TypeAlias, TypeVar, Union from haliax.jax_utils import is_jax_array_like + T = TypeVar("T") @@ -36,9 +37,7 @@ class StringHolderEnum(type): def __new__(cls, name, bases, members): # this just iterates through the class dict and removes # all the dunder methods - cls.members = [ - v for k, v in members.items() if not k.startswith("__") and not callable(v) - ] + cls.members = [v for k, v in members.items() if not k.startswith("__") and not callable(v)] return super().__new__(cls, name, bases, members) # giving your class an __iter__ method gives you membership checking diff --git a/src/haliax/wrap.py b/src/haliax/wrap.py index 0709107..6e09acf 100644 --- a/src/haliax/wrap.py +++ b/src/haliax/wrap.py @@ -23,13 +23,9 @@ def wrap_elemwise_unary(f): return wrapper -def wrap_reduction_call( - fn, single_axis_only: bool = False, supports_where: bool = True -): +def wrap_reduction_call(fn, single_axis_only: bool = False, supports_where: bool = True): @functools.wraps(fn) - def wrapper( - a, axis: Optional[AxisSelection] = None, where: NamedArray = None, **kwargs - ): + def wrapper(a, axis: Optional[AxisSelection] = None, where: NamedArray = None, **kwargs): kwargs = dict(kwargs) if where is not None and not supports_where: raise ValueError(f"where is not supported by {fn.__name__}") @@ -44,9 +40,7 @@ def wrap_reduction_call( if isinstance(a, NamedArray): if where is not None: if not isinstance(where, NamedArray): - raise TypeError( - "where must be a NamedArray if a is a NamedArray" - ) + raise TypeError("where must be a NamedArray if a is a NamedArray") where = broadcast_to(where, a.axes) kwargs["where"] = where.array @@ -76,9 +70,7 @@ def wrap_reduction_call( kwargs["where"] = where return fn(a, axis=axis, **kwargs) - return jax.tree_util.tree_map( - reduce_one_leaf, a, is_leaf=lambda x: isinstance(x, NamedArray) - ) + return jax.tree_util.tree_map(reduce_one_leaf, a, is_leaf=lambda x: isinstance(x, NamedArray)) wrapper.__doc__ = ( """ @@ -167,7 +159,5 @@ class ReductionFunction(Protocol): class SimpleReductionFunction(Protocol): - def __call__( - self, array: NamedArray, axis: Optional[AxisSelector] = None, **kwargs - ) -> NamedArray: + def __call__(self, array: NamedArray, axis: Optional[AxisSelector] = None, **kwargs) -> NamedArray: ... diff --git a/tests/test_attention.py b/tests/test_attention.py index 607c6d0..fb58623 100644 --- a/tests/test_attention.py +++ b/tests/test_attention.py @@ -1,9 +1,9 @@ import numpy as np from jax.random import PRNGKey -from test_utils import skip_if_no_torch import haliax as hax from haliax.nn.attention import alibi_attention_bias, dot_product_attention_weights, forgetful_causal_mask +from test_utils import skip_if_no_torch def test_alibi_attention_bias(): diff --git a/tests/test_partitioning.py b/tests/test_partitioning.py index dffbc4a..c372f3b 100644 --- a/tests/test_partitioning.py +++ b/tests/test_partitioning.py @@ -4,11 +4,11 @@ import jax.numpy as jnp import numpy as np from jax.sharding import Mesh, NamedSharding, PartitionSpec from jaxtyping import Array -from test_utils import skip_if_not_enough_devices import haliax as hax from haliax import Axis, NamedArray from haliax.partitioning import ResourceAxis, axis_mapping, infer_resource_partitions, named_jit +from test_utils import skip_if_not_enough_devices class MyModule(eqx.Module): commit e594c01a70d736e8604ced69755b0d404c62bf95 Date: 2023-07-07T03:14:18+01:00 Upgraded to latest Equinox; removed Chex dependency. (#7) diff --git a/pyproject.toml b/pyproject.toml index d854b10..ef632e4 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta" [project] name = "haliax" -version = "1.0.1" +version = "1.0.2" authors = [ { name="David Hall", email="dlwh@cs.stanford.edu" }, ] @@ -22,9 +22,9 @@ classifiers = [ dependencies = [ # we'll require that you install jax yourself, since the extras vary by system. # jax = {version = ">=0.4.10,<0.5.0"} - "equinox~=0.9.0", + "equinox>=0.10.6", + "jaxtyping>=0.2.20", "safetensors[numpy]", - "chex", ] [project.optional-dependencies] diff --git a/src/haliax/hof.py b/src/haliax/hof.py index 496618c..707532a 100644 --- a/src/haliax/hof.py +++ b/src/haliax/hof.py @@ -6,7 +6,6 @@ from typing import Any, Callable, Tuple, TypeVar, Union import equinox as eqx import jax import jax.lax as lax -from equinox.custom_types import BoolAxisSpec from jaxtyping import PyTree from .core import NamedArray, selects_axis @@ -16,6 +15,7 @@ from .types import Axis, AxisSelector from .util import index_where, is_jax_or_hax_array_like, is_named_array +BoolAxisSpec = Union[bool, Callable[[Any], bool]] Carry = TypeVar("Carry") X = TypeVar("X") Y = TypeVar("Y") diff --git a/src/haliax/jax_utils.py b/src/haliax/jax_utils.py index 0ed0ab8..b2b8f78 100644 --- a/src/haliax/jax_utils.py +++ b/src/haliax/jax_utils.py @@ -4,11 +4,13 @@ from typing import Any, Callable, List, Optional, Sequence, Union import equinox as eqx import jax import numpy as np -from chex import PRNGKey -from equinox.module import Static from jax import numpy as jnp from jax import random as jrandom -from jaxtyping import PyTree +from jaxtyping import PyTree, PRNGKeyArray + + +class Static(eqx.Module): + value: Any = eqx.field(static=True) def shaped_rng_split(key, split_shape: Union[int, Sequence[int]] = 2) -> jrandom.KeyArray: @@ -26,7 +28,7 @@ def shaped_rng_split(key, split_shape: Union[int, Sequence[int]] = 2) -> jrandom return jnp.reshape(unshaped, split_shape) -def maybe_rng_split(key: Optional[PRNGKey], num: int = 2): +def maybe_rng_split(key: Optional[PRNGKeyArray], num: int = 2): """Splits a random key into multiple random keys. If the key is None, then it replicates the None. Also handles num == 1 case""" if key is None: diff --git a/src/haliax/nn/attention.py b/src/haliax/nn/attention.py index 958afe0..ab78fb3 100644 --- a/src/haliax/nn/attention.py +++ b/src/haliax/nn/attention.py @@ -4,7 +4,7 @@ from typing import List, Optional import jax import jax.numpy as jnp import numpy as np -from jax.random import PRNGKey +from jaxtyping import PRNGKeyArray import haliax import haliax.random as hrandom @@ -157,14 +157,14 @@ def prefix_lm_mask(QSeqLen: Axis, KSeqLen: Axis, prefix_len: int) -> NamedArray: return prefix | causal -def dropout_mask(axes: AxisSpec, dropout_rate: float, *, key: PRNGKey) -> NamedArray: +def dropout_mask(axes: AxisSpec, dropout_rate: float, *, key: PRNGKeyArray) -> NamedArray: """ Really just an alias for haliax.random.bernoulli. You can pass in e.g. Head, QPos and KPos """ return hrandom.bernoulli(key, shape=axes, p=1 - dropout_rate) -def forgetful_causal_mask(KPos: Axis, mask_prob: float, sample_prob: bool = True, *, key: PRNGKey) -> NamedArray: +def forgetful_causal_mask(KPos: Axis, mask_prob: float, sample_prob: bool = True, *, key: PRNGKeyArray) -> NamedArray: """ Forgetful Context Masking a la https://arxiv.org/abs/2210.13432. Randomly drops out positions from the key sequence. Reportedly better than normal attention dropout. Almost certainly faster. diff --git a/src/haliax/nn/dropout.py b/src/haliax/nn/dropout.py index 935df53..0ff659d 100644 --- a/src/haliax/nn/dropout.py +++ b/src/haliax/nn/dropout.py @@ -2,6 +2,7 @@ from typing import Optional import equinox as eqx import jax +from jaxtyping import PRNGKeyArray import haliax from haliax.core import NamedArray @@ -76,7 +77,7 @@ class Dropout(eqx.Module): x: NamedArray, *, inference: bool, - key: Optional["jax.random.PRNGKey"] = None, + key: Optional[PRNGKeyArray] = None, ) -> NamedArray: """**Arguments:** diff --git a/src/haliax/nn/scan.py b/src/haliax/nn/scan.py index e93b2c2..92c39e6 100644 --- a/src/haliax/nn/scan.py +++ b/src/haliax/nn/scan.py @@ -90,5 +90,5 @@ class Stacked(eqx.Module, Generic[M]): return block(carry, *extra_args, **extra_kwargs) # TODO: this is for logic that's in levanter. We should move that logic to haliax I guess? - def _state_dict_key_map(self) -> Optional[Dict[str, Optional[str]]]: + def _state_dict_key_map(self) -> Dict[str, Optional[str]]: return {"stacked": None} diff --git a/src/haliax/partitioning.py b/src/haliax/partitioning.py index 7436c30..90bb1ac 100644 --- a/src/haliax/partitioning.py +++ b/src/haliax/partitioning.py @@ -7,7 +7,8 @@ from typing import Mapping, Optional, Sequence, TypeVar, Union import equinox as eqx import jax -from equinox.compile_utils import compile_cache, get_fun_names, hashable_combine, hashable_partition +# TODO: avoid depending on private Equinox internals. +from equinox._compile_utils import compile_cache, hashable_combine, hashable_partition from jax._src.sharding_impls import AUTO from jax.experimental.pjit import pjit from jax.lax import with_sharding_constraint @@ -292,7 +293,7 @@ def named_jit( cmanager = contextlib.nullcontext() with cmanager: - cached_pjitted_fun = _named_pjit_cache(get_fun_names(fn), **my_pjit_args) + cached_pjitted_fun = _named_pjit_cache(fn, **my_pjit_args) return cached_pjitted_fun(dynamic_donated, dynamic_reserved, static) return f diff --git a/src/haliax/tree_util.py b/src/haliax/tree_util.py index da204da..9340a7d 100644 --- a/src/haliax/tree_util.py +++ b/src/haliax/tree_util.py @@ -1,12 +1,11 @@ import jax -from jax.random import PRNGKey -from jaxtyping import PyTree +from jaxtyping import PyTree, PRNGKeyArray from .core import Axis, NamedArray from .util import is_named_array -def resize_axis(tree: PyTree[NamedArray], axis: Axis, key: PRNGKey): +def resize_axis(tree: PyTree[NamedArray], axis: Axis, key: PRNGKeyArray): """Resizes the NamedArrays of a PyTree along a given axis. If the array needs to grow, then the new elements are sampled from a truncated normal distribution with the same mean and standard deviation as the existing elements. If the array needs to shrink, then it's truncated.""" diff --git a/tests/test_random.py b/tests/test_random.py index c077461..fe41763 100644 --- a/tests/test_random.py +++ b/tests/test_random.py @@ -2,7 +2,7 @@ from typing import Callable import jax import jax.numpy as jnp -from chex import PRNGKey +from jaxtyping import PRNGKeyArray import haliax as hax from haliax.random import generate_sharded @@ -96,7 +96,7 @@ def test_randint(): def check_gen_is_equal( - jax_fn: Callable[[PRNGKey, tuple], jnp.ndarray], hax_fn: Callable[[PRNGKey, hax.AxisSpec], hax.NamedArray] + jax_fn: Callable[[PRNGKeyArray, tuple], jnp.ndarray], hax_fn: Callable[[PRNGKeyArray, hax.AxisSpec], hax.NamedArray] ): key = jax.random.PRNGKey(0) diff --git a/tests/test_utils.py b/tests/test_utils.py index bd9b779..0b4f7ec 100644 --- a/tests/test_utils.py +++ b/tests/test_utils.py @@ -3,9 +3,9 @@ from typing import Callable, List, Optional, TypeVar import equinox as eqx import jax import pytest -from chex import assert_trees_all_close from equinox import nn as nn from equinox import static_field +from jaxtyping import PRNGKeyArray T = TypeVar("T") @@ -35,7 +35,7 @@ class MLP(eqx.Module): activation: Callable = jax.nn.relu, final_activation: Callable = lambda x: x, *, - key: "jax.random.PRNGKey", + key: PRNGKeyArray, **kwargs, ): """**Arguments**: @@ -70,7 +70,7 @@ class MLP(eqx.Module): self.activation = activation # type: ignore self.final_activation = final_activation # type: ignore - def __call__(self, x, *, key: Optional["jax.random.PRNGKey"] = None): + def __call__(self, x, *, key: Optional[PRNGKeyArray] = None): """**Arguments:** - `x`: A JAX array with shape `(in_size,)`. @@ -89,23 +89,9 @@ class MLP(eqx.Module): return x -def assert_trees_not_close(a, b): - try: - assert_trees_all_close(jax.tree_util.tree_leaves(arrays_only(a)), jax.tree_util.tree_leaves(arrays_only(b))) - except AssertionError: - pass - else: - raise AssertionError("Trees are equal") - - -def arrays_only(x): - return eqx.filter(x, eqx.is_inexact_array_like) - - def has_torch(): try: import torch # noqa F401 - return True except ImportError: return False commit de430e2e3e4b09eeabea1d3811c776bb8a75e1a7 Date: 2023-07-07T00:01:39-07:00 fix pre-commit, and maybe the build? diff --git a/.github/workflows/run_pre_commit.yaml b/.github/workflows/run_pre_commit.yaml index 039594d..1fe17c5 100644 --- a/.github/workflows/run_pre_commit.yaml +++ b/.github/workflows/run_pre_commit.yaml @@ -20,7 +20,6 @@ jobs: run: | python -m pip install --upgrade pip pip install flake8 pytest pre-commit - pip install --upgrade "jax[cpu]==0.4.10" pip install . # - name: Lint with flake8 # run: | diff --git a/.github/workflows/run_tests.yaml b/.github/workflows/run_tests.yaml index 624bfa7..78b4f81 100644 --- a/.github/workflows/run_tests.yaml +++ b/.github/workflows/run_tests.yaml @@ -20,7 +20,7 @@ jobs: run: | python -m pip install --upgrade pip pip install flake8 pytest - pip install --upgrade "jax[cpu]==0.4.10" + pip install --upgrade "jax[cpu]==0.4.11 jaxlib==0.4.11" pip install . # - name: Lint with flake8 # run: | diff --git a/src/haliax/jax_utils.py b/src/haliax/jax_utils.py index b2b8f78..1721f4e 100644 --- a/src/haliax/jax_utils.py +++ b/src/haliax/jax_utils.py @@ -6,7 +6,7 @@ import jax import numpy as np from jax import numpy as jnp from jax import random as jrandom -from jaxtyping import PyTree, PRNGKeyArray +from jaxtyping import PRNGKeyArray, PyTree class Static(eqx.Module): diff --git a/src/haliax/partitioning.py b/src/haliax/partitioning.py index 90bb1ac..8ba3dd5 100644 --- a/src/haliax/partitioning.py +++ b/src/haliax/partitioning.py @@ -7,6 +7,7 @@ from typing import Mapping, Optional, Sequence, TypeVar, Union import equinox as eqx import jax + # TODO: avoid depending on private Equinox internals. from equinox._compile_utils import compile_cache, hashable_combine, hashable_partition from jax._src.sharding_impls import AUTO diff --git a/src/haliax/tree_util.py b/src/haliax/tree_util.py index 9340a7d..cba5143 100644 --- a/src/haliax/tree_util.py +++ b/src/haliax/tree_util.py @@ -1,5 +1,5 @@ import jax -from jaxtyping import PyTree, PRNGKeyArray +from jaxtyping import PRNGKeyArray, PyTree from .core import Axis, NamedArray from .util import is_named_array diff --git a/tests/test_random.py b/tests/test_random.py index fe41763..db73e21 100644 --- a/tests/test_random.py +++ b/tests/test_random.py @@ -96,7 +96,8 @@ def test_randint(): def check_gen_is_equal( - jax_fn: Callable[[PRNGKeyArray, tuple], jnp.ndarray], hax_fn: Callable[[PRNGKeyArray, hax.AxisSpec], hax.NamedArray] + jax_fn: Callable[[PRNGKeyArray, tuple], jnp.ndarray], + hax_fn: Callable[[PRNGKeyArray, hax.AxisSpec], hax.NamedArray], ): key = jax.random.PRNGKey(0) diff --git a/tests/test_utils.py b/tests/test_utils.py index 0b4f7ec..f82c7f1 100644 --- a/tests/test_utils.py +++ b/tests/test_utils.py @@ -92,6 +92,7 @@ class MLP(eqx.Module): def has_torch(): try: import torch # noqa F401 + return True except ImportError: return False commit 96f42f2b4185e2fc673057de955c9faaddc11705 Date: 2023-07-07T00:02:19-07:00 update names of ci diff --git a/.github/workflows/run_pre_commit.yaml b/.github/workflows/run_pre_commit.yaml index 1fe17c5..153feb4 100644 --- a/.github/workflows/run_pre_commit.yaml +++ b/.github/workflows/run_pre_commit.yaml @@ -1,4 +1,4 @@ -name: Python package +name: Pre-Commit on: [push] diff --git a/.github/workflows/run_tests.yaml b/.github/workflows/run_tests.yaml index 78b4f81..75a6b29 100644 --- a/.github/workflows/run_tests.yaml +++ b/.github/workflows/run_tests.yaml @@ -1,4 +1,4 @@ -name: Python package +name: Run Tests on: [push] commit 7ceaf94692fc47803f530027f15bfe061ac6d412 Date: 2023-07-07T00:06:49-07:00 sigh diff --git a/.github/workflows/run_tests.yaml b/.github/workflows/run_tests.yaml index 75a6b29..ab1b9f8 100644 --- a/.github/workflows/run_tests.yaml +++ b/.github/workflows/run_tests.yaml @@ -20,7 +20,7 @@ jobs: run: | python -m pip install --upgrade pip pip install flake8 pytest - pip install --upgrade "jax[cpu]==0.4.11 jaxlib==0.4.11" + pip install --upgrade "jax[cpu]==0.4.11" "jaxlib[cpu]==0.4.11" pip install . # - name: Lint with flake8 # run: | commit 7577177ffd4a3aaaa35654905972a68555c26904 Date: 2023-07-08T14:41:44-07:00 explicitly export ReductionFunction from wrap diff --git a/src/haliax/wrap.py b/src/haliax/wrap.py index 6e09acf..7933bf8 100644 --- a/src/haliax/wrap.py +++ b/src/haliax/wrap.py @@ -144,6 +144,8 @@ __all__ = [ "wrap_axiswise_call", "wrap_elemwise_binary", "unwrap_namedarrays", + "ReductionFunction", + "SimpleReductionFunction", ] commit f75dea801ea43b40c4b4285b367fac38c62f8d4c Date: 2023-07-08T15:45:45-07:00 fix partitioning changes from equinox diff --git a/src/haliax/partitioning.py b/src/haliax/partitioning.py index 8ba3dd5..b4f29a2 100644 --- a/src/haliax/partitioning.py +++ b/src/haliax/partitioning.py @@ -9,7 +9,7 @@ import equinox as eqx import jax # TODO: avoid depending on private Equinox internals. -from equinox._compile_utils import compile_cache, hashable_combine, hashable_partition +from equinox._compile_utils import compile_cache from jax._src.sharding_impls import AUTO from jax.experimental.pjit import pjit from jax.lax import with_sharding_constraint @@ -18,6 +18,7 @@ from jaxtyping import PyTree from .core import NamedArray from .jax_utils import filter_eval_shape, is_jax_array_like +from .tree_util import hashable_combine, hashable_partition from .types import Axis, AxisSelection, AxisSelector from .util import StringHolderEnum, ensure_tuple, is_named_array @@ -241,7 +242,6 @@ def named_jit( out_axis_resources = axis_resources dynamic_fun, static_fun = hashable_partition(fn, is_jax_array_like) - dynamic_argspec, static_argspec = hashable_partition((args, kwargs), is_jax_array_like) dynamic = (dynamic_fun, dynamic_argspec) diff --git a/src/haliax/tree_util.py b/src/haliax/tree_util.py index cba5143..2ab9c91 100644 --- a/src/haliax/tree_util.py +++ b/src/haliax/tree_util.py @@ -1,4 +1,6 @@ +import equinox as eqx import jax +import jax.tree_util as jtu from jaxtyping import PRNGKeyArray, PyTree from .core import Axis, NamedArray @@ -46,3 +48,17 @@ def resize_axis(tree: PyTree[NamedArray], axis: Axis, key: PRNGKeyArray): new_leaves = [_resize_one(x, key) for x, key in zip(leaves, keys)] return jax.tree_util.tree_unflatten(structure, new_leaves) + + +# old version of eqx's partition functions +def hashable_partition(pytree, filter_spec): + dynamic, static = eqx.partition(pytree, filter_spec) + static_leaves, static_treedef = jtu.tree_flatten(static) + static_leaves = tuple(static_leaves) + return dynamic, (static_leaves, static_treedef) + + +def hashable_combine(dynamic, static): + static_leaves, static_treedef = static + static = jtu.tree_unflatten(static_treedef, static_leaves) + return eqx.combine(dynamic, static) diff --git a/tests/test_partitioning.py b/tests/test_partitioning.py index c372f3b..da9b470 100644 --- a/tests/test_partitioning.py +++ b/tests/test_partitioning.py @@ -224,3 +224,36 @@ def test_shard_plain_array_in_module(): with Mesh(np.array(devices).reshape(-1, 1), (ResourceAxis.DATA, ResourceAxis.MODEL)): mod = named_jit(MyModule)() assert mod.array.sharding.is_fully_replicated + + +def test_named_jit_with_donation(): + with axis_mapping(resource_map): + + class MyModule(eqx.Module): + array: jnp.ndarray + array2: jnp.ndarray + + devices = jax.devices() + with Mesh(np.array(devices).reshape(-1, 1), (ResourceAxis.DATA, ResourceAxis.MODEL)): + mod = named_jit(MyModule, donate_args=(True, False))(jnp.zeros((8, 8)), jnp.zeros((8, 16))) + assert mod.array.sharding.is_fully_replicated + + +def test_named_jit_with_donation_nested_pytrees(): + with axis_mapping(resource_map): + + class MyModule(eqx.Module): + array: jnp.ndarray + array2: jnp.ndarray + + class MyModule2(eqx.Module): + mod: MyModule + mod2: MyModule + + def init(a1, a2): + return MyModule2(MyModule(a1, a2), MyModule(a1, a2)) + + devices = jax.devices() + with Mesh(np.array(devices).reshape(-1, 1), (ResourceAxis.DATA, ResourceAxis.MODEL)): + mod = named_jit(init, donate_args=(True, False))(jnp.zeros((8, 8)), jnp.zeros((8, 16))) + assert mod.mod.array.sharding.is_fully_replicated commit 0aababbda76d97890f42cb921149b889256a97a5 Date: 2023-07-09T23:57:23-07:00 Update README.md with new tutorials (#9) diff --git a/README.md b/README.md index 1fd6711..9fd26bb 100644 --- a/README.md +++ b/README.md @@ -86,10 +86,12 @@ You can find us in the #levanter channel on the unofficial [Jax LLM Discord](htt ## Documentation -Currently, we have two tutorials for Haliax: +Currently, we have four tutorials for Haliax : * [Introduction to Haliax with Transformers](https://colab.research.google.com/drive/1TiTcQQ4V5mopbgCu1SVl-oqJtXn7rFnC) * [Distributed Training in Haliax](https://colab.research.google.com/drive/1QX4yH3zRFF3Xiibf1aahETcSQ5nbcUMz) (including FSDP) +* [Tensor Parallelism in Haliax](https://colab.research.google.com/drive/18_BrtDpe1lu89M4T6fKzda8DdSLtFJhi) +* [Mixed Precision with `jmp`](https://colab.research.google.com/drive/1_4cikwt-UhSH7yRzNRK8ze9msM9r2mEl?usp=sharing) (This one is really a tutorial for [jmp](https://github.com/deepmind/jmp) but it's how to use it with Haliax...) ## Contributing commit a424714cac6b64ccd355b2af1bd27026185ebc88 Date: 2023-07-13T16:03:32-07:00 sharding_for_axis diff --git a/src/haliax/partitioning.py b/src/haliax/partitioning.py index b4f29a2..f77be88 100644 --- a/src/haliax/partitioning.py +++ b/src/haliax/partitioning.py @@ -381,6 +381,11 @@ def physical_axis_size(axis: AxisSelector, mapping: Optional[ResourceMapping] = return prod([mesh_shape[n] for n in name]) +def sharding_for_axis(axis: AxisSelection, mapping: Optional[ResourceMapping] = None) -> NamedSharding: + """Get the sharding for a single axis""" + return NamedSharding(_get_mesh(), pspec_for_axis(axis, mapping)) + + def pspec_for_axis(axis: AxisSelection, mapping: Optional[ResourceMapping] = None) -> PartitionSpec: """Get the PartitionSpec for a single axis""" axis = ensure_tuple(axis) commit 53aadd1aaf68eb3379fd27ab1ef6aad1886db15f Date: 2023-07-13T16:33:37-07:00 update random for sophia diff --git a/src/haliax/random.py b/src/haliax/random.py index 7decb7a..0b1ffac 100644 --- a/src/haliax/random.py +++ b/src/haliax/random.py @@ -234,20 +234,24 @@ def choice( @named_call -def categorical(key, shape: AxisSpec, logits: NamedArray, axis: AxisSelector): +def categorical(key, logits: NamedArray, axis: AxisSelector, shape: Optional[AxisSpec] = None): """Sample random values from categorical distributions. Args: key: a PRNG key used as the random key. - shape: A tuple of nonnegative integers representing the result shape. - Must be broadcast-compatible with logits without the axis logits: Unnormalized log probabilities of the categorical distribution(s) to sample from, so that `softmax(logits, axis)` gives the corresponding probabilities. axis: Axis along which logits belong to the same categorical distribution. + shape: A tuple of axes representing the result shape, or None. if None, the shape is + logits.axes \ {axis}. If not None, logits.axes \ {axis} must be a subset of shape. Returns: A random array with int dtype and shape given by ``shape`` """ - shape = ensure_tuple(shape) + axis = logits.resolve_axis(axis) + if shape is None: + shape = tuple(a for a in logits.axes if a != axis) + else: + shape = ensure_tuple(shape) # TODO: could alias the axis and rename at end if selects_axis(shape, axis): diff --git a/tests/test_random.py b/tests/test_random.py index db73e21..effc0fd 100644 --- a/tests/test_random.py +++ b/tests/test_random.py @@ -256,13 +256,13 @@ def test_categorical(): ) check_gen_is_equal( lambda k, s: jax.random.categorical(k, logits.array, shape=s, axis=-1), - lambda k, s: hax.random.categorical(k, s, logits, Digit), + lambda k, s: hax.random.categorical(k, logits, Digit, shape=s), ) logits = logits.rearrange((Digit, Height, Width)) check_gen_is_equal( lambda k, s: jax.random.categorical(k, logits.array, shape=s, axis=0), - lambda k, s: hax.random.categorical(k, s, logits, Digit), + lambda k, s: hax.random.categorical(k, logits, Digit, shape=s), ) # check broadcasting @@ -277,13 +277,13 @@ def test_categorical(): raw_logits = jnp.broadcast_to(logits.array.reshape(-1, 1, Digit.size), (Height.size, Width.size, Digit.size)) check_gen_is_equal( lambda k, s: jax.random.categorical(k, raw_logits, shape=s, axis=-1), - lambda k, s: hax.random.categorical(k, s, logits, Digit), + lambda k, s: hax.random.categorical(k, logits, Digit, shape=s), ) # check str arg for selector check_gen_is_equal( lambda k, s: jax.random.categorical(k, raw_logits, shape=s, axis=-1), - lambda k, s: hax.random.categorical(k, s, logits, "Digit"), + lambda k, s: hax.random.categorical(k, logits, "Digit", shape=s), ) commit c7d8dcd38438df904fcebf291eb6199024dd3a82 Date: 2023-07-14T22:52:58-07:00 pass in mesh for axis mapping diff --git a/src/haliax/partitioning.py b/src/haliax/partitioning.py index f77be88..598126f 100644 --- a/src/haliax/partitioning.py +++ b/src/haliax/partitioning.py @@ -352,7 +352,8 @@ def _cached_filter_eval_shape(fun, *args, **kwargs): def physical_axis_name(axis: AxisSelector, mapping: Optional[ResourceMapping] = None) -> Optional[PhysicalAxisSpec]: """Get the physical axis name for a logical axis from the mapping. Returns none if the axis is not mapped.""" - mapping = mapping or _mapping_holder.thread_data.resource_mapping + if mapping is None: + mapping = _mapping_holder.thread_data.resource_mapping if mapping is None: return None elif isinstance(axis, str): @@ -381,9 +382,11 @@ def physical_axis_size(axis: AxisSelector, mapping: Optional[ResourceMapping] = return prod([mesh_shape[n] for n in name]) -def sharding_for_axis(axis: AxisSelection, mapping: Optional[ResourceMapping] = None) -> NamedSharding: +def sharding_for_axis( + axis: AxisSelection, mapping: Optional[ResourceMapping] = None, mesh: Optional[Mesh] = None +) -> NamedSharding: """Get the sharding for a single axis""" - return NamedSharding(_get_mesh(), pspec_for_axis(axis, mapping)) + return NamedSharding(mesh or _get_mesh(), pspec_for_axis(axis, mapping)) def pspec_for_axis(axis: AxisSelection, mapping: Optional[ResourceMapping] = None) -> PartitionSpec: commit 4a28de3d5423add300d299d6d77dc80475eb5fa4 Date: 2023-07-23T00:12:16-07:00 add hax.map similar to jax.lax.map diff --git a/src/haliax/__init__.py b/src/haliax/__init__.py index 6462c78..6aff97a 100644 --- a/src/haliax/__init__.py +++ b/src/haliax/__init__.py @@ -27,7 +27,7 @@ from .core import ( unbind, unflatten_axis, ) -from .hof import fold, scan, vmap +from .hof import fold, map, scan, vmap from .ops import clip, isclose, pad_left, trace, tril, triu, where from .partitioning import auto_sharded, axis_mapping, named_jit, shard_with_axis_mapping from .types import Axis, AxisSelection, AxisSelector, AxisSpec @@ -357,6 +357,7 @@ __all__ = [ "sort", "scan", "fold", + "map", "vmap", "trace", "where", diff --git a/src/haliax/hof.py b/src/haliax/hof.py index 707532a..ba6267a 100644 --- a/src/haliax/hof.py +++ b/src/haliax/hof.py @@ -127,6 +127,33 @@ def fold( return scanned_f +def map( + fn: Callable[[X], Y], + axis: Axis, + reverse: bool = False, + unroll: int = 1, + is_mapped: BoolAxisSpec = is_jax_or_hax_array_like, +) -> Callable[[PyTree[X]], PyTree[Y]]: + """ + NamedArray aware version of jax.lax.map. Normal arrays are mapped according to the specs as in equinox.filter_map, + except that the output axis is always 0 b/c it's annoying to make anything else work. + + You'll typically want to use map (instead of a vmap or just vectorized code) when you want to encourage XLA to + loop over the axis to control memory. + """ + + def scan_compatible_fn(_, x): + del _ + return None, fn(x) + + scan_preconfig = scan(scan_compatible_fn, axis, reverse=reverse, unroll=unroll, is_scanned=is_mapped) + + def scanned_f(*args, **kwargs): + return scan_preconfig(None, *args, **kwargs)[1] + + return scanned_f + + ResolvedUnnamedAxisSpec = Union[int, None] UnnamedAxisSpec = Union[ResolvedUnnamedAxisSpec, Callable[[Any], ResolvedUnnamedAxisSpec]] @@ -374,4 +401,4 @@ def _ensure_first(axis): return ensure_first -__all__ = ["scan", "fold", "vmap"] +__all__ = ["scan", "fold", "vmap", "map"] commit 32cfd94749ba7f2055bae11f1736b941a410606b Date: 2023-07-24T11:19:36-07:00 remove AUTO for now since it's still flakey diff --git a/src/haliax/partitioning.py b/src/haliax/partitioning.py index 598126f..9d6382b 100644 --- a/src/haliax/partitioning.py +++ b/src/haliax/partitioning.py @@ -10,7 +10,8 @@ import jax # TODO: avoid depending on private Equinox internals. from equinox._compile_utils import compile_cache -from jax._src.sharding_impls import AUTO + +# from jax._src.sharding_impls import AUTO from jax.experimental.pjit import pjit from jax.lax import with_sharding_constraint from jax.sharding import Mesh, NamedSharding, PartitionSpec, SingleDeviceSharding @@ -153,16 +154,10 @@ def infer_resource_partitions( mesh = mesh or _get_mesh() - def _auto_array_sharding(node): - if hasattr(node, "sharding"): - return node.sharding - else: - return None - def partition_spec(node: typing.Any): if isinstance(node, NamedArray): if preserve_existing_shardings: - current_sharding = _auto_array_sharding(node) + current_sharding = getattr(node, "sharding", None) else: current_sharding = None @@ -172,7 +167,7 @@ def infer_resource_partitions( sharding = NamedSharding(mesh, pspec_for_axis(node.axes, resource_mapping)) return NamedArray(sharding, node.axes) # type: ignore else: - sharding = _auto_array_sharding(node) + sharding = getattr(node, "sharding", None) # TODO: these are usually replicated. Is there a better way to tell? if isinstance(sharding, SingleDeviceSharding): return NamedSharding(mesh, PartitionSpec(None)) @@ -180,13 +175,13 @@ def infer_resource_partitions( return sharding elif node.shape == (): return NamedSharding(mesh, PartitionSpec()) - elif use_auto_sharding: - # TODO: auto doesn't seem to really work reliably yet - # compat between 0.4.10 and 0.4.11 - if isinstance(AUTO, typing.Callable): # type: ignore - return AUTO(mesh) - else: - return AUTO + # elif use_auto_sharding: + # TODO: auto doesn't seem to really work reliably yet + # compat between 0.4.10 and 0.4.11 + # if isinstance(AUTO, typing.Callable): # type: ignore + # return AUTO(mesh) + # else: + # return AUTO return NamedSharding(mesh, PartitionSpec(None)) return jax.tree_util.tree_map(partition_spec, tree, is_leaf=is_named_array) commit 747519764854007a0322be7bba72284811306006 Date: 2023-07-25T12:09:09-07:00 warn if the dtype is wrong in ce loss diff --git a/src/haliax/nn/__init__.py b/src/haliax/nn/__init__.py index 903ef49..159d1c7 100644 --- a/src/haliax/nn/__init__.py +++ b/src/haliax/nn/__init__.py @@ -1,4 +1,5 @@ import functools +import warnings from typing import Optional, Tuple, Union import jax.nn as jnn @@ -91,6 +92,12 @@ def cross_entropy_loss( ) -> NamedArray: loss, _ = cross_entropy_loss_and_log_normalizers(pred_y, Label, target_y) + # if target_y isn't some kind of floating point, something is wrong, so warn + if not jnp.issubdtype(target_y.dtype, jnp.floating): + warnings.warn( + f"target_y has dtype {target_y.dtype}, which is not a floating point type. This is probably a mistake." + ) + if reduction is UNSPECIFIED: reduction = haliax.mean commit 34dc37eb385e6e5cc781f5fb9fd936028954da2b Date: 2023-07-26T16:07:57-07:00 expose the thread_local resource mapping so we can pass it around diff --git a/src/haliax/partitioning.py b/src/haliax/partitioning.py index 9d6382b..2745c35 100644 --- a/src/haliax/partitioning.py +++ b/src/haliax/partitioning.py @@ -147,7 +147,7 @@ def infer_resource_partitions( don't have a sharding. """ if resource_mapping is None: - resource_mapping = _mapping_holder.thread_data.resource_mapping + resource_mapping = current_thread_local_mapping() if resource_mapping is None: raise ValueError("No resource mapping found") @@ -187,6 +187,10 @@ def infer_resource_partitions( return jax.tree_util.tree_map(partition_spec, tree, is_leaf=is_named_array) +def current_thread_local_mapping(): + return _mapping_holder.thread_data.resource_mapping + + def named_jit( fn=None, axis_resources: Optional[ResourceMapping] = None, @@ -348,7 +352,8 @@ def _cached_filter_eval_shape(fun, *args, **kwargs): def physical_axis_name(axis: AxisSelector, mapping: Optional[ResourceMapping] = None) -> Optional[PhysicalAxisSpec]: """Get the physical axis name for a logical axis from the mapping. Returns none if the axis is not mapped.""" if mapping is None: - mapping = _mapping_holder.thread_data.resource_mapping + if hasattr(_mapping_holder.thread_data, "resource_mapping"): + mapping = _mapping_holder.thread_data.resource_mapping if mapping is None: return None elif isinstance(axis, str): @@ -425,4 +430,5 @@ __all__ = [ "physical_axis_name", "pspec_for_axis", "round_axis_for_partitioning", + "current_thread_local_mapping", ] commit f77bdc5b1acde6f8eb206473cdfe308d5e32c73a Date: 2023-07-26T16:46:16-07:00 use current_thread_local_mapping more diff --git a/src/haliax/partitioning.py b/src/haliax/partitioning.py index 2745c35..67a98e0 100644 --- a/src/haliax/partitioning.py +++ b/src/haliax/partitioning.py @@ -54,7 +54,7 @@ def axis_mapping(mapping: ResourceMapping, *, merge: bool = False, **kwargs): """Context manager for setting the global resource mapping""" mapping = dict(mapping) - old_mapping = _mapping_holder.thread_data.resource_mapping + old_mapping = current_thread_local_mapping() if merge: mapping.update(old_mapping or {}) @@ -68,6 +68,19 @@ def axis_mapping(mapping: ResourceMapping, *, merge: bool = False, **kwargs): _mapping_holder.thread_data.resource_mapping = old_mapping +def current_thread_local_mapping(): + """ + Get the current thread-local resource mapping, or None if there is no resource mapping set. + :return: + """ + if _mapping_holder.thread_data is None: + return None + if not hasattr(_mapping_holder.thread_data, "resource_mapping"): + return None + + return _mapping_holder.thread_data.resource_mapping + + T = TypeVar("T", bound=PyTree) @@ -78,7 +91,7 @@ def auto_sharded(x: T, mesh: Optional[Mesh] = None) -> T: If there is no axis mapping, the global axis mapping, this function is a no-op. """ - mapping = _mapping_holder.thread_data.resource_mapping + mapping = current_thread_local_mapping() if mapping is None: return x @@ -187,10 +200,6 @@ def infer_resource_partitions( return jax.tree_util.tree_map(partition_spec, tree, is_leaf=is_named_array) -def current_thread_local_mapping(): - return _mapping_holder.thread_data.resource_mapping - - def named_jit( fn=None, axis_resources: Optional[ResourceMapping] = None, @@ -235,7 +244,7 @@ def named_jit( nonlocal axis_resources, in_axis_resources, out_axis_resources, donate_args, donate_kwargs if axis_resources is None: - axis_resources = _mapping_holder.thread_data.resource_mapping + axis_resources = current_thread_local_mapping() if out_axis_resources is None: out_axis_resources = axis_resources @@ -352,8 +361,7 @@ def _cached_filter_eval_shape(fun, *args, **kwargs): def physical_axis_name(axis: AxisSelector, mapping: Optional[ResourceMapping] = None) -> Optional[PhysicalAxisSpec]: """Get the physical axis name for a logical axis from the mapping. Returns none if the axis is not mapped.""" if mapping is None: - if hasattr(_mapping_holder.thread_data, "resource_mapping"): - mapping = _mapping_holder.thread_data.resource_mapping + mapping = current_thread_local_mapping() if mapping is None: return None elif isinstance(axis, str): commit 0ab27d5e18acf16d3a3981566a0aac23ad4bcffe Date: 2023-07-29T00:13:08-07:00 add an option for Linear to be output-major diff --git a/src/haliax/nn/linear.py b/src/haliax/nn/linear.py index ec95106..1cc128b 100644 --- a/src/haliax/nn/linear.py +++ b/src/haliax/nn/linear.py @@ -1,11 +1,11 @@ from typing import Optional import equinox as eqx -import jax import haliax as hax from ..core import NamedArray +from ..jax_utils import named_call from ..types import AxisSpec @@ -20,13 +20,22 @@ class Linear(eqx.Module): Out: AxisSpec = eqx.static_field() @staticmethod - def init(In: AxisSpec, Out: AxisSpec, *, key, use_bias=True) -> "Linear": - joint_spec = hax.concat_axis_specs(In, Out) + def init(In: AxisSpec, Out: AxisSpec, *, key, use_bias=True, out_first: bool = False) -> "Linear": + """ + + :param In: Input axes + :param Out: Output axes + :param key: rng key for initialization + :param use_bias: whether to include bias term + :param out_first: whether to put output axes first in the weight matrix. out_first is how PyTorch does it. + :return: + """ + joint_spec = hax.concat_axis_specs(Out, In) if out_first else hax.concat_axis_specs(In, Out) weight = hax.random.normal(key, joint_spec) * 0.02 bias = hax.zeros(Out) if use_bias else None return Linear(weight, bias, In, Out) - @jax.named_scope(name="linear") + @named_call def __call__(self, inputs): q = inputs.dot(self.In, self.weight) q = hax.auto_sharded(q) @@ -36,3 +45,10 @@ class Linear(eqx.Module): q = hax.auto_sharded(q) return q + + @property + def out_first(self): + if isinstance(self.Out, hax.Axis): + return self.weight.axes[0] == self.Out + else: + return self.weight.axes[: len(self.Out)] == self.Out commit e1080e848412a587817bdfdaee76f9482b31abde Date: 2023-07-29T00:13:34-07:00 always auto-shard dot diff --git a/src/haliax/core.py b/src/haliax/core.py index 89efa16..a0d340a 100644 --- a/src/haliax/core.py +++ b/src/haliax/core.py @@ -727,7 +727,8 @@ def dot(axis: AxisSelection, *arrays: NamedArray, precision: PrecisionLike = Non precision=precision, ) - return NamedArray(output, output_axes) + out = NamedArray(output, output_axes) + return haliax.auto_sharded(out) def split(a: NamedArray, axis: AxisSelector, new_axes: Sequence[Axis]) -> Sequence[NamedArray]: commit dd0fb970c3c869b866b56f99b1bc07ef43256748 Date: 2023-07-29T22:11:08-07:00 better check for whether or not something is out_first diff --git a/src/haliax/nn/linear.py b/src/haliax/nn/linear.py index 1cc128b..f8d8bec 100644 --- a/src/haliax/nn/linear.py +++ b/src/haliax/nn/linear.py @@ -48,7 +48,8 @@ class Linear(eqx.Module): @property def out_first(self): + # We do it this way because of scan layers if isinstance(self.Out, hax.Axis): - return self.weight.axes[0] == self.Out + return self.weight.axes[-1] != self.Out else: - return self.weight.axes[: len(self.Out)] == self.Out + return self.weight.axes[-len(self.Out) :] != self.Out commit 8c9e6b95a1dbe3e81c63198b5822d7358fa81a7d Date: 2023-08-01T12:45:19-07:00 don't get mad about empty arrays in shard_with_axis_mapping diff --git a/src/haliax/partitioning.py b/src/haliax/partitioning.py index 67a98e0..c418268 100644 --- a/src/haliax/partitioning.py +++ b/src/haliax/partitioning.py @@ -116,6 +116,9 @@ def shard_with_axis_mapping(x: T, mapping: ResourceMapping, mesh: Optional[Mesh] if _is_jit_tracer(x.array): pspec = pspec_for_axis(x.axes, mapping) return with_sharding_constraint(x, pspec) + elif not is_jax_array_like(x.array): + # this happens when we filter out params for things like lora + return x else: raw_x = x.array current_sharding = raw_x.sharding commit c7d59c4dcf0cb07519e8477729d9f6f072c84800 Date: 2023-08-01T14:33:53-07:00 eqx's filter_eval_shape is actually all we need diff --git a/src/haliax/jax_utils.py b/src/haliax/jax_utils.py index 1721f4e..7476220 100644 --- a/src/haliax/jax_utils.py +++ b/src/haliax/jax_utils.py @@ -39,20 +39,13 @@ def maybe_rng_split(key: Optional[PRNGKeyArray], num: int = 2): return jrandom.split(key, num) -def filter_eval_shape(fun: Callable, *args, **kwargs): - """As `jax.eval_shape`, but allows any Python object as inputs and outputs""" +# use alias eqx.filter_eval_shape but mark as deprecated +@ft.wraps(eqx.filter_eval_shape) +def filter_eval_shape(*args, **kwargs): + import warnings - # TODO: file a bug - - def _fn(_static, _dynamic): - _args, _kwargs = eqx.combine(_static, _dynamic) - _out = fun(*_args, **_kwargs) - _dynamic_out, _static_out = eqx.partition(_out, is_jax_array_like) - return _dynamic_out, Static(_static_out) - - dynamic, static = eqx.partition((args, kwargs), is_jax_array_like) - dynamic_out, static_out = jax.eval_shape(ft.partial(_fn, static), dynamic) - return eqx.combine(dynamic_out, static_out.value) + warnings.warn("filter_eval_shape is deprecated, use eqx.filter_eval_shape instead", DeprecationWarning) + return eqx.filter_eval_shape(*args, **kwargs) def filter_checkpoint(fun: Callable, *, prevent_cse: bool = True, policy: Optional[Callable[..., bool]] = None): diff --git a/src/haliax/partitioning.py b/src/haliax/partitioning.py index c418268..c7cf1c5 100644 --- a/src/haliax/partitioning.py +++ b/src/haliax/partitioning.py @@ -18,7 +18,7 @@ from jax.sharding import Mesh, NamedSharding, PartitionSpec, SingleDeviceShardin from jaxtyping import PyTree from .core import NamedArray -from .jax_utils import filter_eval_shape, is_jax_array_like +from .jax_utils import is_jax_array_like from .tree_util import hashable_combine, hashable_partition from .types import Axis, AxisSelection, AxisSelector from .util import StringHolderEnum, ensure_tuple, is_named_array @@ -356,7 +356,7 @@ def _cached_filter_eval_shape(fun, *args, **kwargs): """ dynamic, static = hashable_partition((fun, args, kwargs), is_jax_array_like) if static not in _eval_shape_cache: - _eval_shape_cache[static] = filter_eval_shape(fun, *args, **kwargs) + _eval_shape_cache[static] = eqx.filter_eval_shape(fun, *args, **kwargs) return _eval_shape_cache[static] commit d6471e82670dffbdfd58efa854c1e74a269cf735 Date: 2023-08-01T15:40:29-07:00 mark and replace combine as deprecated diff --git a/src/haliax/hof.py b/src/haliax/hof.py index ba6267a..287038d 100644 --- a/src/haliax/hof.py +++ b/src/haliax/hof.py @@ -9,7 +9,7 @@ import jax.lax as lax from jaxtyping import PyTree from .core import NamedArray, selects_axis -from .jax_utils import broadcast_prefix, combine, is_jax_array_like +from .jax_utils import broadcast_prefix, is_jax_array_like from .partitioning import physical_axis_name from .types import Axis, AxisSelector from .util import index_where, is_jax_or_hax_array_like, is_named_array @@ -77,7 +77,7 @@ def scan( def wrapped_fn(carry, scanned_x_leaves): scanned_x = jax.tree_util.tree_unflatten(x_elem_structure, scanned_x_leaves) # this part is the most delicate: combining the scanned x with the unscanned x - scanned_x = combine(scanned_x, unscanned_xs, is_leaf=is_named_array) + scanned_x = eqx.combine(scanned_x, unscanned_xs, is_leaf=is_named_array) args, kwargs = scanned_x carry, y = f(carry, *args, **kwargs) y = jax.tree_util.tree_map(_pacify_named_arrays, y, is_leaf=is_named_array) diff --git a/src/haliax/jax_utils.py b/src/haliax/jax_utils.py index 7476220..cb6fdee 100644 --- a/src/haliax/jax_utils.py +++ b/src/haliax/jax_utils.py @@ -6,7 +6,7 @@ import jax import numpy as np from jax import numpy as jnp from jax import random as jrandom -from jaxtyping import PRNGKeyArray, PyTree +from jaxtyping import PRNGKeyArray class Static(eqx.Module): @@ -39,7 +39,6 @@ def maybe_rng_split(key: Optional[PRNGKeyArray], num: int = 2): return jrandom.split(key, num) -# use alias eqx.filter_eval_shape but mark as deprecated @ft.wraps(eqx.filter_eval_shape) def filter_eval_shape(*args, **kwargs): import warnings @@ -86,34 +85,12 @@ def broadcast_prefix(prefix_tree: Any, full_tree: Any, is_leaf: Optional[Callabl return jax.tree_util.tree_unflatten(full_structure, result) -def _is_none(x): - return x is None - - -def _combine(*args): - for arg in args: - if arg is not None: - return arg - return None - - -def combine(*pytrees: PyTree, is_leaf=None) -> PyTree: - """Generalization of eqx.combine to support custom is_leaf functions - - **Returns:** - - A PyTree with the same structure as its inputs. Each leaf will be the first - non-`None` leaf found in the corresponding leaves of `pytrees` as they are - iterated over. - """ - - if is_leaf is None: - is_leaf = _is_none - else: - _orig_is_leaf = is_leaf - is_leaf = lambda x: _is_none(x) or _orig_is_leaf(x) # noqa: E731 +@ft.wraps(eqx.combine) +def combine(*args, **kwargs): + import warnings - return jax.tree_util.tree_map(_combine, *pytrees, is_leaf=is_leaf) + warnings.warn("combine is deprecated, use eqx.combine instead", DeprecationWarning) + return eqx.combine(*args, **kwargs) def _UNSPECIFIED(): commit d77100ff7361ad08cf00542dd6c0bad96475b119 Date: 2023-08-04T23:28:16-07:00 Various changes in support of flash attention (#11) * updated_slice, eliminate_axes diff --git a/README.md b/README.md index 9fd26bb..2270008 100644 --- a/README.md +++ b/README.md @@ -10,7 +10,6 @@ as in NumPy, PyTorch, etc. Here's a minimal attention module implementation in H please see the [Haliax tutorial](https://colab.research.google.com/drive/1TiTcQQ4V5mopbgCu1SVl-oqJtXn7rFnC). ```python - import equinox as eqx import jax import jax.numpy as jnp @@ -23,52 +22,55 @@ Head = hax.Axis("head", 8) # number of attention heads Key = hax.Axis("key", 64) # key size Embed = hax.Axis("embed", 512) # embedding size + def attention_scores(Key, KPos, query, key, mask): - # how similar is each query to each key - scores = hax.dot(Key, query, key) / jnp.sqrt(Key.size) + # how similar is each query to each key + scores = hax.dot(Key, query, key) / jnp.sqrt(Key.size) - if mask is not None: - scores -= 1E9 * (1.0 - mask) + if mask is not None: + scores -= 1E9 * (1.0 - mask) - # convert to probabilities - scores = hax.nn.softmax(scores, KPos) - return scores + # convert to probabilities + scores = hax.nn.softmax(scores, KPos) + return scores def attention(Key, KPos, query, key, value, mask): - scores = attention_scores(Key, KPos, query, key, mask) - answers = hax.dot(KPos, scores, value) + scores = attention_scores(Key, KPos, query, key, mask) + answers = hax.dot(KPos, scores, value) + + return answers - return answers # Causal Mask means that if pos >= key_pos, then pos can attend to key_pos causal_mask = hax.arange(Pos).broadcast_axis(KPos) >= hax.arange(KPos) + class Attention(eqx.Module): - proj_qkv: hnn.Linear # input projection from [Embed] -> [(q, k, v), Head, Key] - proj_answer: hnn.Linear # output projection from [Head, Key] -> [Embed] + proj_qkv: hnn.Linear # input projection from [Embed] -> [(q, k, v), Head, Key] + proj_answer: hnn.Linear # output projection from [Head, Key] -> [Embed] - @staticmethod - def init(Embed, Head, Key, *, key): - Qkv = hax.Axis("qkv", 3) # create all three at once + @staticmethod + def init(Embed, Head, Key, *, key): + Qkv = hax.Axis("qkv", 3) # create all three at once - k_qkv, k_ans = jax.random.split(key, 2) - proj_qkv = hnn.Linear.init(In=Embed, Out=(Qkv, Head, Key), key=k_qkv) - proj_answer = hnn.Linear.init(In=(Head, Key), Out=Embed, key=k_ans) - return Attention(proj_qkv, proj_answer) + k_qkv, k_ans = jax.random.split(key, 2) + proj_qkv = hnn.Linear.init(In=Embed, Out=(Qkv, Head, Key), key=k_qkv) + proj_answer = hnn.Linear.init(In=(Head, Key), Out=Embed, key=k_ans) + return Attention(proj_qkv, proj_answer) - def __call__(self, x, mask=None): - qkv_out = self.proj_qkv(x) - q, k, v = qkv_out.unbind("qkv") + def __call__(self, x, mask=None): + qkv_out = self.proj_qkv(x) + q, k, v = qkv_out.unbind("qkv") - # Rename k and v's Pos as haliax doesn't support unnamed axes or duplicate axes - k = k.rename({"position": "key_position"}) - v = v.rename({"position": "key_position"}) + # Rename k and v's Pos as haliax doesn't support unnamed axes or duplicate axes + k = k.rename({"position": "key_position"}) + v = v.rename({"position": "key_position"}) - answers = attention(Key, KPos, q, k, v, causal_mask) + answers = attention(Key, KPos, q, k, v, causal_mask) - x = self.proj_answer(answers) - return x + x = self.proj_answer(answers) + return x ``` (We use the excellent [Equinox](https://github.com/patrick-kidger/equinox) library for its module system and tree transformations.) diff --git a/docs/indexing.md b/docs/indexing.md index 8bee511..eab9df9 100644 --- a/docs/indexing.md +++ b/docs/indexing.md @@ -10,7 +10,6 @@ Basic indexing works basically like you would expect: you can use integers or sl Haliax supports two syntaxes for indexing: one accepts a dict of axis names and indices, and the other accepts an alternating sequence of axis names and indices. The latter is useful for indexing with a small number of indices. - ```python import haliax as hax import jax diff --git a/src/haliax/__init__.py b/src/haliax/__init__.py index 6aff97a..5ff64f9 100644 --- a/src/haliax/__init__.py +++ b/src/haliax/__init__.py @@ -6,31 +6,31 @@ import jax.numpy as jnp import haliax.random as random from haliax import tree_util as tree_util +from .axis import Axis, AxisSelection, AxisSelector, AxisSpec, concat_axes, eliminate_axes, selects_axis from .core import ( NamedArray, are_shape_checks_enabled, broadcast_arrays, broadcast_axis, broadcast_to, - concat_axis_specs, dot, enable_shape_checks, flatten_axes, + index, named, rearrange, rename, roll, slice, - slice_nd, split, take, unbind, unflatten_axis, + updated_slice, ) from .hof import fold, map, scan, vmap from .ops import clip, isclose, pad_left, trace, tril, triu, where from .partitioning import auto_sharded, axis_mapping, named_jit, shard_with_axis_mapping -from .types import Axis, AxisSelection, AxisSelector, AxisSpec from .wrap import ( ReductionFunction, SimpleReductionFunction, @@ -246,13 +246,12 @@ right_shift = wrap_elemwise_binary(jnp.right_shift) subtract = wrap_elemwise_binary(jnp.subtract) true_divide = wrap_elemwise_binary(jnp.true_divide) +# deprecated name +concat_axis_specs = concat_axes + __all__ = [ - "Axis", "NamedArray", - "AxisSpec", - "AxisSelection", - "AxisSelector", "broadcast_to", "broadcast_axis", "named", @@ -261,12 +260,12 @@ __all__ = [ "split", "flatten_axes", "slice", - "slice_nd", + "updated_slice", + "index", "take", "unbind", "rename", "rearrange", - "concat_axis_specs", "zeros", "ones", "full", @@ -410,4 +409,8 @@ __all__ = [ "pad_left", "stack", "concatenate", + "eliminate_axes", + "selects_axis", + "concat_axes", + "concat_axis_specs", ] diff --git a/src/haliax/axis.py b/src/haliax/axis.py new file mode 100644 index 0000000..53f6e72 --- /dev/null +++ b/src/haliax/axis.py @@ -0,0 +1,166 @@ +from dataclasses import dataclass +from typing import Dict, Mapping, Optional, Sequence, Union, overload + +from haliax.util import ensure_tuple, index_where + + +@dataclass(frozen=True) +class Axis: + """Axis is a dataclass that represents an axis of an NamedArray. It has a name and a size.""" + + name: str + size: int + + def alias(self, new_name: str): + return Axis(new_name, self.size) + + def resize(self, size) -> "Axis": + return Axis(self.name, size) + + +AxisSelector = Union[Axis, str] +"""AxisSelector is a type that can be used to select a single axis from an array. str or Axis""" +AxisSelection = Union[AxisSelector, Sequence[AxisSelector]] +"""AxisSelection is a type that can be used to select multiple axes from an array. str, Axis, or sequence of mixed +str and Axis""" +AxisSpec = Union[Axis, Sequence[Axis]] +"""AxisSpec is a type that can be used to specify the axes of an array, usually for creation or adding a new axis + whose size can't be determined another way. Axis or sequence of Axis""" + + +def selects_axis(selector: AxisSelection, selected: AxisSelection) -> bool: + """Returns true if the selector has every axis in selected and, if dims are given, that they match""" + if isinstance(selector, Axis) or isinstance(selector, str): + selected = ensure_tuple(selected) + try: + index = index_where(lambda ax: is_axis_compatible(ax, selector), selected) # type: ignore + return index >= 0 + except ValueError: + return False + + selector_dict = _spec_to_dict(selector) + + selected_tuple = ensure_tuple(selected) # type: ignore + for ax in selected_tuple: + if isinstance(ax, Axis): + selector_size = selector_dict.get(ax.name, _Sentinel) + if selector_size is not None and selector_size != ax.size: + return False + elif isinstance(ax, str): + if ax not in selector_dict: + return False + else: + raise ValueError(f"Invalid axis spec: {ax}") + + return True + + +class _Sentinel: + ... + + +def is_axis_compatible(ax1: AxisSelector, ax2: AxisSelector): + """ + Returns true if the two axes are compatible, meaning they have the same name and, if both are Axis, the same size + """ + if isinstance(ax1, str): + if isinstance(ax2, str): + return ax1 == ax2 + return ax1 == ax2.name + if isinstance(ax2, str): + return ax1.name == ax2 + return ax1.name == ax2.name + + +@overload +def _spec_to_dict(axis_spec: AxisSpec) -> Dict[str, int]: # type: ignore + ... + + +@overload +def _spec_to_dict(axis_spec: AxisSelection) -> Dict[str, Optional[int]]: # type: ignore + ... + + +def _spec_to_dict(axis_spec: AxisSelection) -> Dict[str, Optional[int]]: # type: ignore + spec = ensure_tuple(axis_spec) # type: ignore + shape_dict: Dict[str, Optional[int]] = {} + for ax in spec: + if isinstance(ax, Axis): + shape_dict[ax.name] = ax.size + elif isinstance(ax, str): + shape_dict[ax] = None + else: + raise ValueError(f"Invalid axis spec: {ax}") + + return shape_dict + + +def _dict_to_spec(axis_spec: Mapping[str, Optional[int]]) -> AxisSelection: + return tuple(Axis(name, size) if size is not None else name for name, size in axis_spec.items()) + + +@overload +def concat_axes(a1: AxisSpec, a2: AxisSpec) -> AxisSpec: + pass + + +@overload +def concat_axes(a1: AxisSelection, a2: AxisSelection) -> AxisSelection: + pass + + +def concat_axes(a1: AxisSelection, a2: AxisSelection) -> AxisSelection: + """Concatenates two AxisSpec. Raises ValueError if any axis is present in both specs""" + + def _ax_name(ax: AxisSelector) -> str: + if isinstance(ax, Axis): + return ax.name + else: + return ax + + if isinstance(a1, Axis) and isinstance(a2, Axis): + if _ax_name(a1) == _ax_name(a2): + raise ValueError(f"Axis {a1} specified twice") + return (a1, a2) + else: + a1 = ensure_tuple(a1) + a2 = ensure_tuple(a2) + + a1_names = [_ax_name(ax) for ax in a1] + a2_names = [_ax_name(ax) for ax in a2] + + if len(set(a1_names) & set(a2_names)) > 0: + overlap = [ax for ax in a1_names if ax in a2_names] + raise ValueError(f"AxisSpecs overlap! {' '.join(str(x) for x in overlap)}") + return a1 + a2 + + +@overload +def eliminate_axes(axis_spec: AxisSpec, axes: AxisSelection) -> AxisSpec: # type: ignore + ... + + +@overload +def eliminate_axes(axis_spec: AxisSelection, axes: AxisSelection) -> AxisSelection: # type: ignore + ... + + +def eliminate_axes(axis_spec: AxisSelection, to_remove: AxisSelection) -> AxisSelection: # type: ignore + """Returns a new axis spec that is the same as the original, but without any axes in axes. Raises if any axis in to_remove is + not present in axis_spec""" + to_remove = ensure_tuple(to_remove) + axis_spec_dict = _spec_to_dict(axis_spec) + for ax in to_remove: + if isinstance(ax, Axis): + if ax.name not in axis_spec_dict: + raise ValueError(f"Axis {ax.name} not present in axis spec {axis_spec}") + del axis_spec_dict[ax.name] + elif isinstance(ax, str): + if ax not in axis_spec_dict: + raise ValueError(f"Axis {ax} not present in axis spec {axis_spec}") + del axis_spec_dict[ax] + else: + raise ValueError(f"Invalid axis spec: {ax}") + + return _dict_to_spec(axis_spec_dict) diff --git a/src/haliax/core.py b/src/haliax/core.py index a0d340a..79b006b 100644 --- a/src/haliax/core.py +++ b/src/haliax/core.py @@ -12,10 +12,12 @@ import jax.numpy as jnp import numpy as np import haliax +import haliax.axis from haliax.jax_utils import is_jax_array_like from haliax.util import ensure_tuple, index_where, py_slice, slice_t -from .types import Axis, AxisSelection, AxisSelector, AxisSpec, PrecisionLike, Scalar +from .axis import Axis, AxisSelection, AxisSelector, AxisSpec, selects_axis +from .types import PrecisionLike, Scalar NamedOrNumeric = Union[Scalar, "NamedArray"] @@ -225,10 +227,23 @@ class NamedArray: return haliax.rename(self, renames=renames) # slicing + @typing.overload + def slice( + self, axis: AxisSelector, new_axis: Optional[AxisSelector] = None, start: int = 0, length: Optional[int] = None + ) -> "NamedArray": + pass + + @typing.overload + def slice( + self, start: Mapping[AxisSelector, int], length: Mapping[AxisSelector, Union[int, Axis]] + ) -> "NamedArray": + pass + + def slice(self, *args, **kwargs) -> "NamedArray": + return haliax.slice(self, *args, **kwargs) - # TOOD: AxisSelector-ify new_axis - def slice(self, axis: AxisSelector, new_axis: Axis, start: int = 0) -> "NamedArray": - return haliax.slice(self, axis=axis, new_axis=new_axis, start=start) + def updated_slice(self, start: Mapping[AxisSelector, int], update: "NamedArray") -> "NamedArray": + return haliax.updated_slice(self, start=start, update=update) def take(self, axis: AxisSelector, index: Union[int, "NamedArray"]) -> "NamedArray": return haliax.take(self, axis=axis, index=index) @@ -256,15 +271,15 @@ class NamedArray: >>> Y = Axis("y", 20) >>> arr = haliax.random.randint(jax.random.PRNGKey(0), (X, Y), 0, X.size) # slice with ints or slices - >>> arr[{"x": 1, "y": slice(0, 10, 2)}] + >>> arr[{"x": 1, "y": slice(0,10,new_axis=2)}] >>> Z = Axis("z", 3) # so-called "advanced indexing" with NamedArrays. >>> index_arr = NamedArray(np.array([1, 2, 3]), Z) >>> arr[{"x": 1, "y": index_arr}] A shorthand is provided that works with Python's slicing syntax: - >>> arr["x", :] == arr[{"x": slice(None, None, None)}] - >>> arr["y", slice(0, 10, 2)] == arr[{"y": slice(0, 10, 2)}] + >>> arr["x", :] == arr[{"x": slice(None,None,new_axis=None)}] + >>> arr["y", slice(0,10,new_axis=2)] == arr[{"y": slice(0,10,new_axis=2)}] Advanced indexing is implemented by broadcasting all index arrays to the same shape (using Haliax's usual broadcasting rules). @@ -281,7 +296,7 @@ class NamedArray: ) idx = {idx[i]: idx[i + 1] for i in range(0, len(idx), 2)} - return slice_nd(self, idx) + return index(self, idx) # np.ndarray methods: def all(self, axis: Optional[AxisSelection] = None) -> "NamedArray": @@ -450,6 +465,13 @@ class NamedArray: return haliax.less_equal(self, other) def __eq__(self, other): + # special case because Jax sometimes call == on + # types when they're in PyTrees + if self.array is None: + return other.array is None + if other.array is None: + return False + return haliax.equal(self, other) def __ne__(self, other): @@ -594,22 +616,180 @@ def take(array: NamedArray, axis: AxisSelector, index: Union[int, NamedArray]) - return NamedArray(new_array, new_axes) -def slice(array: NamedArray, axis: AxisSelector, new_axis: Axis, start: int = 0) -> NamedArray: +@typing.overload +def slice( + array: NamedArray, + axis: AxisSelector, + new_axis: Optional[AxisSelector] = None, + start: int = 0, + length: Optional[int] = None, +) -> NamedArray: + pass + + +@typing.overload +def slice( + array: NamedArray, + start: Mapping[AxisSelector, Union[int, jnp.ndarray]], + length: Optional[Mapping[AxisSelector, int]], +) -> NamedArray: + """ + Slices the array along the specified axes, replacing them with new axes (or a shortened version of the old one) + + :arg start: the starting index of each axis to slice + :arg length: the length of each axis to slice. If not specified, the length of the new axis will be the same as the old one + """ + pass + + +def slice(array: NamedArray, *args, **kwargs) -> NamedArray: + """ + Slices the array along the specified axis or axes, replacing them with new axes (or a shortened version of the old one) + + This method has two signatures: + slice(array, axis, new_axis=None, start=0, length=None) + slice(array, start: Mapping[AxisSelector, Union[int, jnp.ndarray]], length: Mapping[AxisSelector, int]) + + They both do similar things. The former slices an array along a single axis, replacing it with a new axis. + The latter slices an array along multiple axes, replacing them with new axes. + """ + if len(args) >= 1: + if isinstance(args[0], Mapping): + return _slice_new(array, *args, **kwargs) + else: + return _slice_old(array, *args, **kwargs) + elif "axis" in kwargs: + return _slice_old(array, **kwargs) + else: + return _slice_new(array, **kwargs) + + +def _slice_old( + array: NamedArray, + axis: AxisSelector, + new_axis: Optional[AxisSelector] = None, + start: int = 0, + length: Optional[int] = None, +) -> NamedArray: """ Selects elements from an array along an axis, by an index or by another named array This is somewhat better than take if you want a contiguous slice of an array + + :arg axis: the axis to slice + :arg new_axis: the name of the new axis that replaces the old one. If none, the old name will be used + :arg start: the index to start the slice at + :arg length: the length of the slice. either new_axis must be an Axis or length must be specified + + Note: this method is basically a wrapper around jax.lax.dynamic_slice_in_dim """ axis_index = array._lookup_indices(axis) if axis_index is None: raise ValueError(f"axis {axis} not found in {array}") - sliced = jax.lax.dynamic_slice_in_dim(array.array, start, new_axis.size, axis=axis_index) + if length is None: + if not isinstance(new_axis, Axis): + raise ValueError("either new_axis must be an Axis or length must be specified") + length = new_axis.size + + if isinstance(new_axis, str): + new_axis = Axis(new_axis, length) + elif new_axis is None: + new_axis = array.axes[axis_index].resize(length) + + assert isinstance(new_axis, Axis) + + sliced = jax.lax.dynamic_slice_in_dim(array.array, start, length, axis=axis_index) new_axes = array.axes[:axis_index] + (new_axis,) + array.axes[axis_index + 1 :] # new axes come from splicing the old axis with return NamedArray(sliced, new_axes) -def slice_nd( +def _slice_new( + array: NamedArray, + start: Mapping[AxisSelector, Union[int, jnp.ndarray]], + length: Mapping[AxisSelector, Union[int, Axis]], +) -> NamedArray: + array_slice_indices = [0] * len(array.axes) + new_axes = list(array.axes) + new_lengths = [axis.size for axis in array.axes] + + for axis, s in start.items(): + axis_index = array._lookup_indices(axis.name if isinstance(axis, Axis) else axis) + if axis_index is None: + raise ValueError(f"axis {axis} not found in {array}") + + array_slice_indices[axis_index] = s + try: + length_or_axis = length[axis] + except KeyError: + raise ValueError(f"length of axis {axis} not specified") + + if isinstance(length_or_axis, Axis): + new_axis = length_or_axis + ax_len = length_or_axis.size + else: + ax_len = length_or_axis + new_axis = array.axes[axis_index].resize(ax_len) + + new_axes[axis_index] = new_axis + new_lengths[axis_index] = ax_len + + total_length = array.axes[axis_index].size + if isinstance(s, int) and isinstance(ax_len, int): + if s + ax_len > total_length: + raise ValueError(f"slice {s}:{s} + {ax_len} is out of bounds for axis {axis} of length {total_length}") + + sliced_array = jax.lax.dynamic_slice(array.array, array_slice_indices, new_lengths) + + return NamedArray(sliced_array, tuple(new_axes)) + + +def updated_slice( + array: NamedArray, start: Mapping[AxisSelector, Union[int, jnp.ndarray]], update: NamedArray +) -> NamedArray: + """ + Updates a slice of an array with another array + + :arg array: the array to update + :arg start: the starting index of each axis to update + :arg update: the array to update with + """ + + array_slice_indices = [0] * len(array.axes) + for axis, s in start.items(): + axis_index = array._lookup_indices(axis.name if isinstance(axis, Axis) else axis) + if axis_index is None: + raise ValueError(f"axis {axis} not found in {array}") + array_slice_indices[axis_index] = s + total_length = array.axes[axis_index].size + update_axis = update._lookup_indices(axis.name if isinstance(axis, Axis) else axis) + + if update_axis is None: + raise ValueError(f"axis {axis} not found in {update}") + # if s is a tracer we can't check the size + if isinstance(s, int) and update.axes[update_axis].size + s > total_length: + raise ValueError( + f"update axis {axis} is too large to start at {s}. Array size is {total_length}, update size is" + f" {update.axes[update_axis].size}" + ) + + # broadcasting here is a bit delicate because the sizes aren't necessarily the same + # we need to broadcast the update array to the same axis names as the array we're updating, adding them as necessary + broadcasted_axes = [] + for axis in array.axes: + update_axis = update._lookup_indices(axis.name) + if update_axis is None: + broadcasted_axes.append(axis) + else: + broadcasted_axes.append(update.axes[update_axis]) + + update = haliax.broadcast_to(update, broadcasted_axes, enforce_no_extra_axes=True) + + updated = jax.lax.dynamic_update_slice(array.array, update.array, array_slice_indices) + return NamedArray(updated, array.axes) + + +def index( array: NamedArray, slices: Mapping[AxisSelector, Union[int, slice_t, NamedArray]] ) -> Union[NamedArray, jnp.ndarray]: """ @@ -945,42 +1125,6 @@ def named(a: jnp.ndarray, axis: AxisSelection) -> NamedArray: return NamedArray(a, axes) -@overload -def concat_axis_specs(a1: AxisSpec, a2: AxisSpec) -> Sequence[Axis]: - pass - - -@overload -def concat_axis_specs(a1: AxisSelection, a2: AxisSelection) -> Sequence[Union[Axis, str]]: - pass - - -def concat_axis_specs(a1: AxisSelection, a2: AxisSelection) -> AxisSelection: - """Concatenates two AxisSpec. Raises ValueError if any axis is present in both specs""" - - def _ax_name(ax: AxisSelector) -> str: - if isinstance(ax, Axis): - return ax.name - else: - return ax - - if isinstance(a1, Axis) and isinstance(a2, Axis): - if _ax_name(a1) == _ax_name(a2): - raise ValueError(f"Axis {a1} specified twice") - return (a1, a2) - else: - a1 = ensure_tuple(a1) - a2 = ensure_tuple(a2) - - a1_names = [_ax_name(ax) for ax in a1] - a2_names = [_ax_name(ax) for ax in a2] - - if len(set(a1_names) & set(a2_names)) > 0: - overlap = [ax for ax in a1_names if ax in a2_names] - raise ValueError(f"AxisSpecs overlap! {' '.join(str(x) for x in overlap)}") - return a1 + a2 - - # Broadcasting Support def _broadcast_order(a: NamedArray, b: NamedArray, require_subset: bool = True) -> Tuple[Axis, ...]: """ @@ -1189,7 +1333,7 @@ def check_shape(jnp_shape: Sequence[int], hax_axes: AxisSelection) -> Tuple[Axis axes: Tuple[AxisSelector, ...] = ensure_tuple(hax_axes) if len(jnp_shape) != len(axes): raise ValueError(f"Shape mismatch: jnp_shape={jnp_shape} hax_axes={hax_axes}") - result_axes: List[haliax.Axis] = [] + result_axes: List[Axis] = [] for i in range(len(axes)): ax = axes[i] if isinstance(ax, Axis): @@ -1204,79 +1348,14 @@ def check_shape(jnp_shape: Sequence[int], hax_axes: AxisSelection) -> Tuple[Axis return tuple(result_axes) -class _Sentinel: - ... - - -def is_axis_compatible(ax1: AxisSelector, ax2: AxisSelector): - if isinstance(ax1, str): - if isinstance(ax2, str): - return ax1 == ax2 - return ax1 == ax2.name - if isinstance(ax2, str): - return ax1.name == ax2 - return ax1.name == ax2.name - - -def selects_axis(selector: AxisSelection, selected: AxisSelection) -> bool: - """Returns true if the selector has every axis in selected and, if dims are given, that they match""" - if isinstance(selector, Axis) or isinstance(selector, str): - selected = ensure_tuple(selected) - try: - index = index_where(lambda ax: is_axis_compatible(ax, selector), selected) # type: ignore - return index >= 0 - except ValueError: - return False - - selector_dict = _spec_to_dict(selector) - - selected_tuple = ensure_tuple(selected) # type: ignore - for ax in selected_tuple: - if isinstance(ax, Axis): - selector_size = selector_dict.get(ax.name, _Sentinel) - if selector_size is not None and selector_size != ax.size: - return False - elif isinstance(ax, str): - if ax not in selector_dict: - return False - else: - raise ValueError(f"Invalid axis spec: {ax}") - - return True - - -@overload -def _spec_to_dict(axis_spec: AxisSpec) -> Mapping[str, int]: - ... - - -@overload -def _spec_to_dict(axis_spec: AxisSelection) -> Mapping[str, Optional[int]]: - ... - - -def _spec_to_dict(axis_spec: AxisSelection) -> Mapping[str, Optional[int]]: - spec = ensure_tuple(axis_spec) # type: ignore - shape_dict: Dict[str, Optional[int]] = {} - for ax in spec: - if isinstance(ax, Axis): - shape_dict[ax.name] = ax.size - elif isinstance(ax, str): - shape_dict[ax] = None - else: - raise ValueError(f"Invalid axis spec: {ax}") - - return shape_dict - - __all__ = [ "NamedArray", - "concat_axis_specs", "dot", "named", "rearrange", "slice", - "slice_nd", + "updated_slice", + "index", "take", "split", "flatten_axes", diff --git a/src/haliax/hof.py b/src/haliax/hof.py index ba6267a..28e3f49 100644 --- a/src/haliax/hof.py +++ b/src/haliax/hof.py @@ -8,10 +8,10 @@ import jax import jax.lax as lax from jaxtyping import PyTree -from .core import NamedArray, selects_axis +from .axis import Axis, AxisSelector, selects_axis +from .core import NamedArray from .jax_utils import broadcast_prefix, combine, is_jax_array_like from .partitioning import physical_axis_name -from .types import Axis, AxisSelector from .util import index_where, is_jax_or_hax_array_like, is_named_array diff --git a/src/haliax/nn/__init__.py b/src/haliax/nn/__init__.py index 159d1c7..5908dda 100644 --- a/src/haliax/nn/__init__.py +++ b/src/haliax/nn/__init__.py @@ -9,8 +9,8 @@ import haliax import haliax as hax import haliax.nn.attention as attention +from .. import Axis, AxisSelector, AxisSpec from ..core import NamedArray -from ..types import Axis, AxisSelector, AxisSpec from ..util import UNSPECIFIED, Unspecified from ..wrap import ReductionFunction, unwrap_namedarrays, wrap_axiswise_call, wrap_elemwise_unary, wrap_reduction_call from .dropout import Dropout, dropout diff --git a/src/haliax/nn/attention.py b/src/haliax/nn/attention.py index ab78fb3..fadd1fb 100644 --- a/src/haliax/nn/attention.py +++ b/src/haliax/nn/attention.py @@ -8,8 +8,9 @@ from jaxtyping import PRNGKeyArray import haliax import haliax.random as hrandom +from haliax import Axis, AxisSelection, AxisSpec from haliax.core import NamedArray -from haliax.types import Axis, AxisSelection, AxisSpec, PrecisionLike +from haliax.types import PrecisionLike # With attention we usually distinguish between the mask and the bias, though the former is just a special case of the diff --git a/src/haliax/nn/dropout.py b/src/haliax/nn/dropout.py index 0ff659d..6a058ec 100644 --- a/src/haliax/nn/dropout.py +++ b/src/haliax/nn/dropout.py @@ -5,8 +5,8 @@ import jax from jaxtyping import PRNGKeyArray import haliax +from haliax.axis import AxisSpec from haliax.core import NamedArray -from haliax.types import AxisSpec from haliax.util import ensure_tuple diff --git a/src/haliax/nn/embedding.py b/src/haliax/nn/embedding.py index 9215bda..c150b05 100644 --- a/src/haliax/nn/embedding.py +++ b/src/haliax/nn/embedding.py @@ -2,7 +2,8 @@ import equinox as eqx import haliax as hax -from ..core import Axis, NamedArray +from ..axis import Axis +from ..core import NamedArray from ..jax_utils import named_call diff --git a/src/haliax/nn/linear.py b/src/haliax/nn/linear.py index f8d8bec..01bf134 100644 --- a/src/haliax/nn/linear.py +++ b/src/haliax/nn/linear.py @@ -4,9 +4,9 @@ import equinox as eqx import haliax as hax +from ..axis import AxisSpec from ..core import NamedArray from ..jax_utils import named_call -from ..types import AxisSpec class Linear(eqx.Module): diff --git a/src/haliax/nn/normalization.py b/src/haliax/nn/normalization.py index 000d8c2..4214b22 100644 --- a/src/haliax/nn/normalization.py +++ b/src/haliax/nn/normalization.py @@ -4,8 +4,8 @@ import equinox as eqx import haliax as hax +from ..axis import AxisSpec from ..core import NamedArray -from ..types import AxisSpec class LayerNorm(eqx.Module): diff --git a/src/haliax/nn/scan.py b/src/haliax/nn/scan.py index 92c39e6..1da3f95 100644 --- a/src/haliax/nn/scan.py +++ b/src/haliax/nn/scan.py @@ -4,7 +4,7 @@ from typing import Dict, Generic, Optional, Protocol, Type, TypeVar import equinox as eqx import haliax -from haliax.core import Axis +import haliax as hax from haliax.jax_utils import filter_checkpoint @@ -43,7 +43,7 @@ class Stacked(eqx.Module, Generic[M]): >>> import haliax.nn as hnn >>> class MyModule(eqx.Module): ... def __init__(self, num_layers: int, hidden: hax.Axis, *, key): - ... self.axis = Axis("layer", num_layers) + ... self.axis = hax.Axis("layer", num_layers) ... self.layers = Stacked.init(self.axis, hnn.Linear)(In=hidden, Out=hidden, key=key) ... ... def __call__(self, x): @@ -57,12 +57,12 @@ class Stacked(eqx.Module, Generic[M]): # TODO: we can probably make this module support pipeline parallelism, but that's a whole project in itself stacked: M - Block: Axis = eqx.static_field() + Block: hax.Axis = eqx.static_field() # TODO: support fancier gradient checkpointing gradient_checkpointing: bool = eqx.static_field() @staticmethod - def init(Block: Axis, module: Type[M], *, gradient_checkpointing: bool = False) -> ModuleInit["Stacked[M]"]: + def init(Block: hax.Axis, module: Type[M], *, gradient_checkpointing: bool = False) -> ModuleInit["Stacked[M]"]: @functools.wraps(module) def fn(*args, **kwargs): stacked = haliax.vmap(module.init, Block)(*args, **kwargs) diff --git a/src/haliax/ops.py b/src/haliax/ops.py index 7b8e160..66b3d89 100644 --- a/src/haliax/ops.py +++ b/src/haliax/ops.py @@ -3,8 +3,8 @@ from typing import Union import jax import jax.numpy as jnp +from .axis import Axis, AxisSelector from .core import NamedArray, NamedOrNumeric, broadcast_arrays, broadcast_arrays_and_return_axes -from .types import Axis, AxisSelector def trace(array: NamedArray, axis1: AxisSelector, axis2: AxisSelector, offset=0, dtype=None) -> NamedArray: diff --git a/src/haliax/partitioning.py b/src/haliax/partitioning.py index c7cf1c5..8817133 100644 --- a/src/haliax/partitioning.py +++ b/src/haliax/partitioning.py @@ -17,10 +17,10 @@ from jax.lax import with_sharding_constraint from jax.sharding import Mesh, NamedSharding, PartitionSpec, SingleDeviceSharding from jaxtyping import PyTree +from .axis import Axis, AxisSelection, AxisSelector from .core import NamedArray from .jax_utils import is_jax_array_like from .tree_util import hashable_combine, hashable_partition -from .types import Axis, AxisSelection, AxisSelector from .util import StringHolderEnum, ensure_tuple, is_named_array diff --git a/src/haliax/random.py b/src/haliax/random.py index 0b1ffac..0f8c26e 100644 --- a/src/haliax/random.py +++ b/src/haliax/random.py @@ -8,12 +8,12 @@ import jax.numpy as jnp import jax.random as jrandom import haliax -from haliax.core import NamedArray, NamedOrNumeric, broadcast_to, selects_axis +from haliax.core import NamedArray, NamedOrNumeric, broadcast_to from haliax.util import ensure_tuple +from .axis import Axis, AxisSelector, AxisSpec, selects_axis from .jax_utils import named_call from .partitioning import auto_sharded, physical_axis_name, physical_axis_size, pspec_for_axis -from .types import Axis, AxisSelector, AxisSpec @named_call diff --git a/src/haliax/tree_util.py b/src/haliax/tree_util.py index 2ab9c91..60cff83 100644 --- a/src/haliax/tree_util.py +++ b/src/haliax/tree_util.py @@ -3,7 +3,8 @@ import jax import jax.tree_util as jtu from jaxtyping import PRNGKeyArray, PyTree -from .core import Axis, NamedArray +from .axis import Axis +from .core import NamedArray from .util import is_named_array @@ -27,7 +28,7 @@ def resize_axis(tree: PyTree[NamedArray], axis: Axis, key: PRNGKeyArray): if axis.size == current_axis.size: return x elif current_axis.size > axis.size: - return x.slice(current_axis, axis) + return x.slice(current_axis, start=0, new_axis=axis) else: num_padding = axis.size - current_axis.size diff --git a/src/haliax/types.py b/src/haliax/types.py index 72a4d43..b674b69 100644 --- a/src/haliax/types.py +++ b/src/haliax/types.py @@ -1,31 +1,8 @@ -from dataclasses import dataclass -from typing import Sequence, Tuple, Union +from typing import Tuple, Union from jax.lax import Precision -@dataclass(frozen=True) -class Axis: - """Axis is a dataclass that represents an axis of an NamedArray. It has a name and a size.""" - - name: str - size: int - - def alias(self, new_name: str): - return Axis(new_name, self.size) - - def resize(self, size): - return Axis(self.name, size) - - -AxisSelector = Union[Axis, str] -"""AxisSelector is a type that can be used to select a single axis from an array. str or Axis""" -AxisSelection = Union[AxisSelector, Sequence[AxisSelector]] -"""AxisSelection is a type that can be used to select multiple axes from an array. str, Axis, or sequence of mixed -str and Axis""" -AxisSpec = Union[Axis, Sequence[Axis]] -"""AxisSpec is a type that can be used to specify the axes of an array, usually for creation or adding a new axis - whose size can't be determined another way. Axis or sequence of Axis""" Scalar = Union[float, int] PrecisionLike = Union[None, str, Precision, Tuple[str, str], Tuple[Precision, Precision]] diff --git a/src/haliax/wrap.py b/src/haliax/wrap.py index 7933bf8..f7fb956 100644 --- a/src/haliax/wrap.py +++ b/src/haliax/wrap.py @@ -4,10 +4,10 @@ from typing import Optional, Protocol import jax import jax.numpy as jnp -from haliax.core import NamedArray, _broadcast_order, broadcast_to, selects_axis +from haliax.core import NamedArray, _broadcast_order, broadcast_to from haliax.util import ensure_tuple -from .types import AxisSelection, AxisSelector +from .axis import AxisSelection, AxisSelector, selects_axis def wrap_elemwise_unary(f): diff --git a/tests/__init__.py b/tests/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/tests/core_test.py b/tests/core_test.py index 4f7ae40..4b304b0 100644 --- a/tests/core_test.py +++ b/tests/core_test.py @@ -416,15 +416,15 @@ def test_rename(): assert hax.rename(named1, {H: H2, "W": "W2"}).axes == (H2, W2, D) -def test_slice_nd(): +def test_index(): H = Axis("H", 20) W = Axis("W", 30) D = Axis("D", 40) named1 = hax.random.uniform(PRNGKey(0), (H, W, D)) - assert jnp.all(jnp.equal(hax.slice_nd(named1, {"H": slice(0, 10, 2)}).array, named1.array[0:10:2, :, :])) - assert hax.slice_nd(named1, {"H": slice(0, 10, 2)}).axes == (Axis("H", 5), W, D) + assert jnp.all(jnp.equal(hax.index(named1, {"H": slice(0, 10, 2)}).array, named1.array[0:10:2, :, :])) + assert hax.index(named1, {"H": slice(0, 10, 2)}).axes == (Axis("H", 5), W, D) # try indexing syntax assert jnp.all(jnp.equal(named1[{"H": slice(0, 10, 2)}].array, named1.array[0:10:2, :, :])) @@ -443,7 +443,7 @@ def test_slice_nd(): assert jnp.all(jnp.equal(named1[{"H": 0, "W": 0, "D": 0}], named1.array[0, 0, 0])) -def test_slice_nd_array_slices(): +def test_index_array_slices(): # fancier tests with array slices with named array args H = Axis("H", 10) W = Axis("W", 20) @@ -581,3 +581,95 @@ def test_duplicate_axis_names_in_slicing(): a[{"Y": ind1}] # error, "X" is not eliminated by the indexing operation a[{"X": ind2, "Y": ind1}] # ok, because X and Y are eliminated by the indexing operation + + +def test_slice_old_style(): + H = Axis("H", 10) + W = Axis("W", 20) + D = Axis("D", 30) + + named1 = hax.random.randint(PRNGKey(0), (H, W, D), minval=0, maxval=10) + + assert jnp.alltrue(named1.slice("H", start=4, length=2).array == named1.array[4:6, :, :]) + assert jnp.alltrue(named1.slice("W", start=4, length=2).array == named1.array[:, 4:6, :]) + assert jnp.alltrue(named1.slice("D", start=4, length=2).array == named1.array[:, :, 4:6]) + + H2 = Axis("H2", 5) + W2 = Axis("W2", 10) + D2 = Axis("D2", 15) + + assert jnp.alltrue(named1.slice("H", H2, start=4).array == named1.array[4 : 4 + H2.size, :, :]) + assert jnp.alltrue(named1.slice("W", W2, start=4).array == named1.array[:, 4 : 4 + W2.size, :]) + assert jnp.alltrue(named1.slice("D", D2, start=4).array == named1.array[:, :, 4 : 4 + D2.size]) + + +def test_slice_new_style(): + H = Axis("H", 10) + W = Axis("W", 20) + D = Axis("D", 30) + + named1 = hax.random.randint(PRNGKey(0), (H, W, D), minval=0, maxval=10) + + x1 = named1.slice({"H": 4, "W": 5, "D": 7}, length={"H": 2, "W": 3, "D": 4}) + assert jnp.alltrue(x1.array == named1.array[4:6, 5:8, 7:11]) + + with pytest.raises(TypeError): + named1.slice({"H": 4, "W": 5, "D": 7}, length={"H": 2, "W": 3, "D": 4}, start={"H": 1, "W": 2, "D": 3}) + + with pytest.raises(ValueError): + named1.slice({"H": 4, "W": 5, "D": 7}, length={"H": 2, "W": 3}) + + H2 = Axis("H2", 5) + W2 = Axis("W2", 10) + D2 = Axis("D2", 15) + + x2 = named1.slice({"H": 4, "W": 5, "D": 7}, length={"H": H2, "W": W2, "D": D2}) + assert jnp.alltrue(x2.array == named1.array[4 : 4 + H2.size, 5 : 5 + W2.size, 7 : 7 + D2.size]) + + +def test_updated_slice(): + H = Axis("H", 10) + W = Axis("W", 20) + D = Axis("D", 30) + + H2 = H.resize(5) + W2 = W.resize(10) + D2 = D.resize(15) + + named1 = hax.random.randint(PRNGKey(0), (H, W, D), minval=0, maxval=10) + named2 = hax.random.randint(PRNGKey(0), (H2, W2, D2), minval=10, maxval=30) + + named1_updated = named1.updated_slice({"H": 0, "W": 0, "D": 0}, named2) + + assert named1_updated.axes == named1.axes + assert jnp.alltrue(named1_updated["H", 0 : H2.size, "W", 0 : W2.size, "D", 0 : D2.size].array == named2.array) + + # test broadcasting + for pair in [(H2, D2), (H2, W2), (W2, D2), (D2, H2), (D2, W2), (W2, H2)]: + n3 = hax.random.randint(PRNGKey(0), pair, minval=10, maxval=30) + named1_updated = named1.updated_slice({ax.name: 0 for ax in pair}, n3) + assert named1_updated.axes == named1.axes + assert jnp.alltrue((named1_updated[{ax.name: slice(0, ax.size) for ax in pair}] == n3).array) + # check that the array outside the slice is unchanged + assert jnp.alltrue( + ( + named1_updated[{ax.name: slice(ax.size, None) for ax in pair}] + == named1[{ax.name: slice(ax.size, None) for ax in pair}] + ).array + ) + + +def test_updated_slice_extra_update_axis_errors(): + H = Axis("H", 10) + W = Axis("W", 20) + D = Axis("D", 30) + + named1 = hax.random.randint(PRNGKey(0), (H, W, D), minval=0, maxval=10) + named2 = hax.random.randint(PRNGKey(0), (H, W, D), minval=10, maxval=30) + + with pytest.raises(ValueError): + named1.updated_slice({"H": 0, "W": 0, "D": 0, "extra": 0}, named2) + + with pytest.raises(ValueError): + named3 = hax.random.randint(PRNGKey(0), (H, W), minval=10, maxval=30) + named3.updated_slice({"H": 0, "W": 0}, named2) diff --git a/tests/test_axis.py b/tests/test_axis.py new file mode 100644 index 0000000..56432d7 --- /dev/null +++ b/tests/test_axis.py @@ -0,0 +1,25 @@ +import pytest + +from haliax.axis import Axis, eliminate_axes + + +def test_eliminate_axes(): + H = Axis("H", 3) + W = Axis("W", 4) + C = Axis("C", 5) + + assert eliminate_axes((H, W), (H,)) == (W,) + assert eliminate_axes((H, W), (W,)) == (H,) + assert eliminate_axes((H, W), (H, W)) == () + + with pytest.raises(ValueError): + eliminate_axes((H, W), (C,)) + + with pytest.raises(ValueError): + eliminate_axes((H, W), (H, C)) + + # test string references + assert eliminate_axes((H, W), ("H",)) == (W,) + assert eliminate_axes(("H", W), (H,)) == (W,) + assert eliminate_axes(("H", W), ("H",)) == (W,) + assert eliminate_axes(("H", W), ("H", "W")) == () commit 5840ccd34aa991c49a69cc226e63ce89b12ef5b7 Date: 2023-08-08T12:45:26-07:00 FSDP function for less boilerplate (#12) diff --git a/pyproject.toml b/pyproject.toml index ef632e4..9340073 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -25,6 +25,7 @@ dependencies = [ "equinox>=0.10.6", "jaxtyping>=0.2.20", "safetensors[numpy]", + "jmp" ] [project.optional-dependencies] diff --git a/src/haliax/__init__.py b/src/haliax/__init__.py index 5ff64f9..3351094 100644 --- a/src/haliax/__init__.py +++ b/src/haliax/__init__.py @@ -30,7 +30,7 @@ from .core import ( ) from .hof import fold, map, scan, vmap from .ops import clip, isclose, pad_left, trace, tril, triu, where -from .partitioning import auto_sharded, axis_mapping, named_jit, shard_with_axis_mapping +from .partitioning import auto_sharded, axis_mapping, fsdp, named_jit, shard_with_axis_mapping from .wrap import ( ReductionFunction, SimpleReductionFunction, @@ -251,6 +251,10 @@ concat_axis_specs = concat_axes __all__ = [ + "Axis", + "AxisSpec", + "AxisSelection", + "AxisSelector", "NamedArray", "broadcast_to", "broadcast_axis", @@ -401,8 +405,8 @@ __all__ = [ "auto_sharded", "axis_mapping", "named_jit", + "fsdp", "shard_with_axis_mapping", - "named_jit", "enable_shape_checks", "are_shape_checks_enabled", "isclose", diff --git a/src/haliax/nn/scan.py b/src/haliax/nn/scan.py index 1da3f95..8af65ee 100644 --- a/src/haliax/nn/scan.py +++ b/src/haliax/nn/scan.py @@ -72,7 +72,7 @@ class Stacked(eqx.Module, Generic[M]): def scan(self, init, *extra_args, **extra_kwargs): if self.gradient_checkpointing: - do_block = filter_checkpoint(self._do_block) + do_block = filter_checkpoint(self._do_block, prevent_cse=False) else: do_block = self._do_block return haliax.scan(do_block, self.Block)(init, self.stacked, *extra_args, **extra_kwargs) diff --git a/src/haliax/partitioning.py b/src/haliax/partitioning.py index 8817133..1ca6553 100644 --- a/src/haliax/partitioning.py +++ b/src/haliax/partitioning.py @@ -7,6 +7,7 @@ from typing import Mapping, Optional, Sequence, TypeVar, Union import equinox as eqx import jax +import jmp # TODO: avoid depending on private Equinox internals. from equinox._compile_utils import compile_cache @@ -30,6 +31,8 @@ PhysicalAxisSpec = Union[PhysicalAxis, Sequence[PhysicalAxis]] ResourceMapping = Mapping[LogicalAxisName, PhysicalAxisSpec] """Mapping from logical axis names to physical axis names""" +F = typing.TypeVar("F", bound=typing.Callable) + class ResourceAxis(StringHolderEnum): """Standard names for physical axes""" @@ -311,6 +314,53 @@ def named_jit( return f +@typing.overload +def fsdp( + fn: F, parameter_mapping: ResourceMapping, compute_mapping: ResourceMapping, mp: Optional[jmp.Policy] = None +) -> F: + ... + + +@typing.overload +def fsdp( + parameter_mapping: ResourceMapping, compute_mapping: ResourceMapping, mp: Optional[jmp.Policy] = None +) -> typing.Callable[[F], F]: + ... + + +def fsdp(*args, **kwargs): + """ + A convenience wrapper around named_jit / pjit and jmp's Policy to encode the FSDP pattern. It's basically equivalent to this: + + ```python + @named_jit(in_axis_resources=parameter_mapping, out_axis_resources=parameter_mapping) + def f(*args, **kwargs): + with axis_mapping(compute_mapping): + return fn(*args, **kwargs) + ``` + + This function can be used as a decorator or as a function. + """ + if "fn" in kwargs: + return _fsdp_impl(*args, **kwargs) + elif len(args) > 1 and callable(args[0]): + return _fsdp_impl(*args[1:], fn=args[0]) + else: + return functools.partial(_fsdp_impl, *args, **kwargs) + + +def _fsdp_impl(fn: F, parameter_mapping, compute_mapping, mp: Optional[jmp.Policy] = None): + @functools.wraps(fn) + def f(*args, **kwargs): + with axis_mapping(compute_mapping): + if mp is not None: + args, kwargs = mp.cast_to_compute((args, kwargs)) + + return fn(*args, **kwargs) + + return named_jit(f, axis_resources=parameter_mapping) + + # This is more or less copy-pasted from Equinox's similar functions (pmap, vmap, etc), but # it's not really explained there so we'll explain it here. # Many jax functions work by compiling functions to XLA. The compilation process is expensive, @@ -438,6 +488,7 @@ __all__ = [ "auto_sharded", "infer_resource_partitions", "named_jit", + "fsdp", "physical_axis_name", "pspec_for_axis", "round_axis_for_partitioning", commit c1bf258be6f6fbd3cafc32de909db0805ec1669d Date: 2023-08-08T13:22:20-07:00 Merge remote-tracking branch 'origin/main' commit a7ba3ca0691878b322e384f45d39321f9c04edaa Date: 2023-08-08T13:23:40-07:00 messed up arg order for fsdp diff --git a/src/haliax/partitioning.py b/src/haliax/partitioning.py index 1ca6553..037b227 100644 --- a/src/haliax/partitioning.py +++ b/src/haliax/partitioning.py @@ -346,7 +346,7 @@ def fsdp(*args, **kwargs): elif len(args) > 1 and callable(args[0]): return _fsdp_impl(*args[1:], fn=args[0]) else: - return functools.partial(_fsdp_impl, *args, **kwargs) + return lambda fn: _fsdp_impl(fn, *args, **kwargs) def _fsdp_impl(fn: F, parameter_mapping, compute_mapping, mp: Optional[jmp.Policy] = None): commit 6d612213f462131c912a40adaec4a5b948420f47 Date: 2023-08-08T13:25:20-07:00 be more explicit about fsdp axis mapping diff --git a/src/haliax/partitioning.py b/src/haliax/partitioning.py index 037b227..009ad55 100644 --- a/src/haliax/partitioning.py +++ b/src/haliax/partitioning.py @@ -358,7 +358,7 @@ def _fsdp_impl(fn: F, parameter_mapping, compute_mapping, mp: Optional[jmp.Polic return fn(*args, **kwargs) - return named_jit(f, axis_resources=parameter_mapping) + return named_jit(f, in_axis_resources=parameter_mapping, out_axis_resources=parameter_mapping) # This is more or less copy-pasted from Equinox's similar functions (pmap, vmap, etc), but commit cfcf0ac7683f15269fd6911900699f51f8db898b Date: 2023-08-09T15:46:09-07:00 remove jmp from mp. was a bad choice diff --git a/src/haliax/partitioning.py b/src/haliax/partitioning.py index 009ad55..5de6bc3 100644 --- a/src/haliax/partitioning.py +++ b/src/haliax/partitioning.py @@ -7,7 +7,6 @@ from typing import Mapping, Optional, Sequence, TypeVar, Union import equinox as eqx import jax -import jmp # TODO: avoid depending on private Equinox internals. from equinox._compile_utils import compile_cache @@ -224,8 +223,19 @@ def named_jit( provided, the arguments' own (pre-existing) shardings will be used as the in_axis_resources. If out_axis_resources is not provided, axis_resources will be used as the out_axis_resources. + functionally this is very similar to something like: + + ```python + arg = hax.shard_with_axis_mapping(arg, in_axis_resources) + with hax.use_resource_mapping(axis_resources): + result = jit(fn, **pjit_args)(arg) + result = hax.shard_with_axis_mapping(result, out_axis_resources) + return result + ``` + but it uses the jit decorator directly + :param fn: The function to be jit'd - :param axis_resources: A mapping from logical axis names to physical axis names + :param axis_resources: A mapping from logical axis names to physical axis names use for the contextual resource mapping :param in_axis_resources: A mapping from logical axis names to physical axis names for arguments. If not passed, it uses the arguments' own shardings :param out_axis_resources: A mapping from logical axis names to physical axis names for the result, defaults to axis_resources :param donate_args: A PyTree of booleans or function leaf->bool, indicating whether to donate arguments to the @@ -315,28 +325,23 @@ def named_jit( @typing.overload -def fsdp( - fn: F, parameter_mapping: ResourceMapping, compute_mapping: ResourceMapping, mp: Optional[jmp.Policy] = None -) -> F: +def fsdp(fn: F, parameter_mapping: ResourceMapping, compute_mapping: ResourceMapping) -> F: ... @typing.overload -def fsdp( - parameter_mapping: ResourceMapping, compute_mapping: ResourceMapping, mp: Optional[jmp.Policy] = None -) -> typing.Callable[[F], F]: +def fsdp(parameter_mapping: ResourceMapping, compute_mapping: ResourceMapping) -> typing.Callable[[F], F]: ... def fsdp(*args, **kwargs): """ - A convenience wrapper around named_jit / pjit and jmp's Policy to encode the FSDP pattern. It's basically equivalent to this: + A convenience wrapper around named_jit / pjit to encode the FSDP pattern. It's basically equivalent to this: ```python - @named_jit(in_axis_resources=parameter_mapping, out_axis_resources=parameter_mapping) + @named_jit(in_axis_resources=parameter_mapping, out_axis_resources=parameter_mapping, axis_resources=compute_mapping) def f(*args, **kwargs): - with axis_mapping(compute_mapping): - return fn(*args, **kwargs) + return fn(*args, **kwargs) ``` This function can be used as a decorator or as a function. @@ -349,16 +354,10 @@ def fsdp(*args, **kwargs): return lambda fn: _fsdp_impl(fn, *args, **kwargs) -def _fsdp_impl(fn: F, parameter_mapping, compute_mapping, mp: Optional[jmp.Policy] = None): - @functools.wraps(fn) - def f(*args, **kwargs): - with axis_mapping(compute_mapping): - if mp is not None: - args, kwargs = mp.cast_to_compute((args, kwargs)) - - return fn(*args, **kwargs) - - return named_jit(f, in_axis_resources=parameter_mapping, out_axis_resources=parameter_mapping) +def _fsdp_impl(fn: F, parameter_mapping, compute_mapping): + return named_jit( + fn, in_axis_resources=parameter_mapping, out_axis_resources=parameter_mapping, axis_resources=compute_mapping + ) # This is more or less copy-pasted from Equinox's similar functions (pmap, vmap, etc), but commit 7aa24c04aac276921178f81723b0508bfa159bc2 Date: 2023-08-09T23:08:13-07:00 put the eval_shape in the context manager to fix weird behavior diff --git a/src/haliax/partitioning.py b/src/haliax/partitioning.py index 5de6bc3..21df8d1 100644 --- a/src/haliax/partitioning.py +++ b/src/haliax/partitioning.py @@ -291,33 +291,33 @@ def named_jit( static = (static_fun, static_argspec) - output_shape = _cached_filter_eval_shape(fn, *args, **kwargs) - # TODO: with new jax.Array I shouldn't have to specify shardings, but I do for now - # https://github.com/google/jax/issues/15600 - # we don't really need in_shardings though - my_pjit_args = dict(**pjit_args) - - if in_axis_resources is not None or axis_resources is not None: - if in_axis_resources is None: - in_axis_resources = axis_resources - in_resources = infer_resource_partitions( - (dynamic_donated, dynamic_reserved), - in_axis_resources, - preserve_existing_shardings=in_axis_resources is None, - ) - my_pjit_args["in_shardings"] = in_resources - - if out_axis_resources is not None: - # TODO: when AUTO is fixed (or eval_shape can give shardings), use it here - out_resources = infer_resource_partitions(output_shape, out_axis_resources, use_auto_sharding=False) - my_pjit_args["out_shardings"] = out_resources - if axis_resources is not None: cmanager = axis_mapping(axis_resources) else: cmanager = contextlib.nullcontext() with cmanager: + output_shape = _cached_filter_eval_shape(fn, *args, **kwargs) + # TODO: with new jax.Array I shouldn't have to specify shardings, but I do for now + # https://github.com/google/jax/issues/15600 + # we don't really need in_shardings though + my_pjit_args = dict(**pjit_args) + + if in_axis_resources is not None or axis_resources is not None: + if in_axis_resources is None: + in_axis_resources = axis_resources + in_resources = infer_resource_partitions( + (dynamic_donated, dynamic_reserved), + in_axis_resources, + preserve_existing_shardings=in_axis_resources is None, + ) + my_pjit_args["in_shardings"] = in_resources + + if out_axis_resources is not None: + # TODO: when AUTO is fixed (or eval_shape can give shardings), use it here + out_resources = infer_resource_partitions(output_shape, out_axis_resources, use_auto_sharding=False) + my_pjit_args["out_shardings"] = out_resources + cached_pjitted_fun = _named_pjit_cache(fn, **my_pjit_args) return cached_pjitted_fun(dynamic_donated, dynamic_reserved, static) @@ -349,7 +349,7 @@ def fsdp(*args, **kwargs): if "fn" in kwargs: return _fsdp_impl(*args, **kwargs) elif len(args) > 1 and callable(args[0]): - return _fsdp_impl(*args[1:], fn=args[0]) + return _fsdp_impl(*args, **kwargs) else: return lambda fn: _fsdp_impl(fn, *args, **kwargs) commit 64224c43e6f41c0aa24c8d7885b833136074ea09 Date: 2023-08-10T14:36:15-07:00 Batched Take (#14) * hilariously complex version of broadcasted take * much less complicated version of broadcasted take * missed a thing diff --git a/src/haliax/__init__.py b/src/haliax/__init__.py index 3351094..e056360 100644 --- a/src/haliax/__init__.py +++ b/src/haliax/__init__.py @@ -3,8 +3,9 @@ from typing import Optional, Sequence import jax import jax.numpy as jnp +import haliax.nn as nn import haliax.random as random -from haliax import tree_util as tree_util +import haliax.tree_util as tree_util from .axis import Axis, AxisSelection, AxisSelector, AxisSpec, concat_axes, eliminate_axes, selects_axis from .core import ( @@ -251,6 +252,9 @@ concat_axis_specs = concat_axes __all__ = [ + "random", + "tree_util", + "nn", "Axis", "AxisSpec", "AxisSelection", diff --git a/src/haliax/axis.py b/src/haliax/axis.py index 53f6e72..6486ba3 100644 --- a/src/haliax/axis.py +++ b/src/haliax/axis.py @@ -1,5 +1,5 @@ from dataclasses import dataclass -from typing import Dict, Mapping, Optional, Sequence, Union, overload +from typing import Dict, List, Mapping, Optional, Sequence, Tuple, Union, overload from haliax.util import ensure_tuple, index_where @@ -137,7 +137,7 @@ def concat_axes(a1: AxisSelection, a2: AxisSelection) -> AxisSelection: @overload -def eliminate_axes(axis_spec: AxisSpec, axes: AxisSelection) -> AxisSpec: # type: ignore +def eliminate_axes(axis_spec: AxisSpec, axes: AxisSelection) -> Tuple[Axis, ...]: # type: ignore ... @@ -164,3 +164,44 @@ def eliminate_axes(axis_spec: AxisSelection, to_remove: AxisSelection) -> AxisSe raise ValueError(f"Invalid axis spec: {ax}") return _dict_to_spec(axis_spec_dict) + + +@overload +def overlapping_axes(ax1: AxisSpec, ax2: AxisSelection) -> Tuple[Axis, ...]: + ... + + +@overload +def overlapping_axes(ax1: AxisSelection, ax2: AxisSpec) -> Tuple[Axis, ...]: + ... + + +@overload +def overlapping_axes(ax1: AxisSelection, ax2: AxisSelection) -> Tuple[AxisSelector, ...]: + ... + + +def overlapping_axes(ax1: AxisSelection, ax2: AxisSelection) -> Tuple[AxisSelector, ...]: + """Returns a tuple of axes that are present in both ax1 and ax2""" + ax2_dict = _spec_to_dict(ax2) + out: List[AxisSelector] = [] + ax1 = ensure_tuple(ax1) + + for ax in ax1: + if isinstance(ax, Axis): + if ax.name in ax2_dict: + sz = ax2_dict[ax.name] + if sz is not None and sz != ax.size: + raise ValueError(f"Axis {ax.name} has different sizes in {ax1} and {ax2}") + out.append(ax) + elif isinstance(ax, str): + if ax in ax2_dict: + ax_sz = ax2_dict[ax] + if ax_sz is not None: + out.append(Axis(ax, ax_sz)) + else: + out.append(ax) + else: + raise ValueError(f"Invalid axis spec: {ax}") + + return tuple(out) diff --git a/src/haliax/core.py b/src/haliax/core.py index 79b006b..30c0272 100644 --- a/src/haliax/core.py +++ b/src/haliax/core.py @@ -16,7 +16,7 @@ import haliax.axis from haliax.jax_utils import is_jax_array_like from haliax.util import ensure_tuple, index_where, py_slice, slice_t -from .axis import Axis, AxisSelection, AxisSelector, AxisSpec, selects_axis +from .axis import Axis, AxisSelection, AxisSelector, AxisSpec, eliminate_axes, selects_axis from .types import PrecisionLike, Scalar @@ -278,8 +278,8 @@ class NamedArray: >>> arr[{"x": 1, "y": index_arr}] A shorthand is provided that works with Python's slicing syntax: - >>> arr["x", :] == arr[{"x": slice(None,None,new_axis=None)}] - >>> arr["y", slice(0,10,new_axis=2)] == arr[{"y": slice(0,10,new_axis=2)}] + >>> arr["x", :] == arr[{"x": slice(None)}] + >>> arr["y", 1, "x", 2] == arr[{"y": 1, "x": 2}] Advanced indexing is implemented by broadcasting all index arrays to the same shape (using Haliax's usual broadcasting rules). @@ -605,15 +605,44 @@ def take(array: NamedArray, axis: AxisSelector, index: Union[int, NamedArray]) - axis_index = array._lookup_indices(axis) if axis_index is None: raise ValueError(f"axis {axis} not found in {array}") + + axis = array.axes[axis_index] if isinstance(index, int): # just drop the axis new_array = jnp.take(array.array, index, axis=axis_index) new_axes = array.axes[:axis_index] + array.axes[axis_index + 1 :] + return NamedArray(new_array, new_axes) else: - new_array = jnp.take(array.array, index.array, axis=axis_index) - new_axes = array.axes[:axis_index] + index.axes + array.axes[axis_index + 1 :] - # new axes come from splicing the old axis with - return NamedArray(new_array, new_axes) + # #13: should broadcast/autobatch take + remaining_axes = eliminate_axes(array.axes, axis) + # axis order is generally [array.axes[:axis_index], index.axes, array.axes[axis_index + 1 :]] + # except that index.axes may overlap with array.axes + overlapping_axes: AxisSpec = haliax.axis.overlapping_axes(remaining_axes, index.axes) + + if overlapping_axes: + # if the eliminated axis is also in the index, we rename it to a dummy axis that we can broadcast over it + need_to_use_dummy_axis = index._lookup_indices(axis.name) is not None + if need_to_use_dummy_axis: + index = index.rename({axis.name: "__DUMMY_" + axis.name}) + array = haliax.broadcast_to(array, index.axes, ensure_order=False, enforce_no_extra_axes=False) + new_axes = eliminate_axes(array.axes, axis) + index = haliax.broadcast_to(index, new_axes, ensure_order=True, enforce_no_extra_axes=True) + + axis_index = array._lookup_indices(axis) # if it moved + index_array = jnp.expand_dims(index.array, axis=axis_index) + new_array = jnp.take_along_axis(array.array, index_array, axis=axis_index) + new_array = jnp.squeeze(new_array, axis=axis_index) + + out = NamedArray(new_array, new_axes) + if need_to_use_dummy_axis: + out = out.rename({"__DUMMY_" + axis.name: axis.name}) + return out + else: + new_axes = array.axes[:axis_index] + index.axes + array.axes[axis_index + 1 :] + new_array = jnp.take(array.array, index.array, axis=axis_index) + + # new axes come from splicing the old axis with + return NamedArray(new_array, new_axes) @typing.overload diff --git a/src/haliax/nn/__init__.py b/src/haliax/nn/__init__.py index 5908dda..7a663b2 100644 --- a/src/haliax/nn/__init__.py +++ b/src/haliax/nn/__init__.py @@ -9,7 +9,7 @@ import haliax import haliax as hax import haliax.nn.attention as attention -from .. import Axis, AxisSelector, AxisSpec +from ..axis import Axis, AxisSelector, AxisSpec from ..core import NamedArray from ..util import UNSPECIFIED, Unspecified from ..wrap import ReductionFunction, unwrap_namedarrays, wrap_axiswise_call, wrap_elemwise_unary, wrap_reduction_call diff --git a/src/haliax/nn/attention.py b/src/haliax/nn/attention.py index fadd1fb..8455908 100644 --- a/src/haliax/nn/attention.py +++ b/src/haliax/nn/attention.py @@ -8,7 +8,7 @@ from jaxtyping import PRNGKeyArray import haliax import haliax.random as hrandom -from haliax import Axis, AxisSelection, AxisSpec +from haliax.axis import Axis, AxisSelection, AxisSpec from haliax.core import NamedArray from haliax.types import PrecisionLike diff --git a/src/haliax/nn/scan.py b/src/haliax/nn/scan.py index 8af65ee..fad38ac 100644 --- a/src/haliax/nn/scan.py +++ b/src/haliax/nn/scan.py @@ -4,9 +4,10 @@ from typing import Dict, Generic, Optional, Protocol, Type, TypeVar import equinox as eqx import haliax -import haliax as hax from haliax.jax_utils import filter_checkpoint +from ..axis import Axis + M = TypeVar("M", bound=eqx.Module, covariant=True) @@ -57,12 +58,12 @@ class Stacked(eqx.Module, Generic[M]): # TODO: we can probably make this module support pipeline parallelism, but that's a whole project in itself stacked: M - Block: hax.Axis = eqx.static_field() + Block: Axis = eqx.static_field() # TODO: support fancier gradient checkpointing gradient_checkpointing: bool = eqx.static_field() @staticmethod - def init(Block: hax.Axis, module: Type[M], *, gradient_checkpointing: bool = False) -> ModuleInit["Stacked[M]"]: + def init(Block: Axis, module: Type[M], *, gradient_checkpointing: bool = False) -> ModuleInit["Stacked[M]"]: @functools.wraps(module) def fn(*args, **kwargs): stacked = haliax.vmap(module.init, Block)(*args, **kwargs) diff --git a/tests/__init__.py b/tests/__init__.py deleted file mode 100644 index e69de29..0000000 diff --git a/tests/core_test.py b/tests/core_test.py index 4b304b0..3a24d58 100644 --- a/tests/core_test.py +++ b/tests/core_test.py @@ -222,6 +222,51 @@ def test_take(): assert named2.axes == (Height, Width, Index, Index2) +def test_take_overlapping_names(): + Height = Axis("Height", 20) + Width = Axis("Width", 30) + Depth = Axis("Depth", 40) + named1 = hax.random.uniform(PRNGKey(0), (Height, Width, Depth)) + + Height2 = Axis("Height", 10) + indices_to_take = hax.arange(Height2, dtype=jnp.int32) + named2 = hax.take(named1, Height, indices_to_take) + + assert named2.axes == (Height2, Width, Depth) + assert named2.array.shape == (10, 30, 40) + + assert jnp.all(jnp.equal(named2.array, named1.array[:10])) + + +def test_take_overlapping_2(): + # https://github.com/stanford-crfm/haliax/issues/13 + def cross_entropy(logits: hax.NamedArray, labels: hax.NamedArray) -> hax.NamedArray: + return hax.take(logits, Embed, labels) # extract log probability of the correct token + + Embed = Axis("Embed", 10) + Block = Axis("Block", 20) + Batch = Axis("Batch", 30) + logits = hax.random.uniform(PRNGKey(0), (Batch, Block, Embed)) + labels = hax.random.randint(PRNGKey(0), (Batch, Block), 0, Embed.size) + + loss = cross_entropy(logits, labels) + assert loss.axes == (Batch, Block) + assert jnp.alltrue(loss.array == jnp.take_along_axis(logits.array, labels.array[..., None], axis=-1)[..., 0]) + + logits = hax.random.uniform(PRNGKey(0), (Batch, Embed, Block)) + + loss = cross_entropy(logits, labels) + assert loss.axes == (Batch, Block) + assert jnp.alltrue(loss.array == jnp.take_along_axis(logits.array, labels.array[..., None, :], axis=-2)[..., 0, :]) + + index = hax.random.randint(PRNGKey(0), (Block, Batch), 0, Embed.size) + loss = cross_entropy(logits, index) + assert loss.axes == (Batch, Block) + assert jnp.alltrue( + loss.array == jnp.take_along_axis(logits.array, index.array.transpose()[..., None, :], axis=-2)[..., 0, :] + ) + + def test_cumsum_etc(): Height = Axis("Height", 2) Width = Axis("Width", 3) commit a6f29e206c949a4814dfed474acd4da9fdd13708 Date: 2023-08-11T11:29:11-07:00 Raise in dot if axes with different sizes are provided. Also adds union_axes for specifying result. diff --git a/src/haliax/axis.py b/src/haliax/axis.py index 6486ba3..5fcd8ad 100644 --- a/src/haliax/axis.py +++ b/src/haliax/axis.py @@ -1,3 +1,4 @@ +import typing from dataclasses import dataclass from typing import Dict, List, Mapping, Optional, Sequence, Tuple, Union, overload @@ -113,12 +114,6 @@ def concat_axes(a1: AxisSelection, a2: AxisSelection) -> AxisSelection: def concat_axes(a1: AxisSelection, a2: AxisSelection) -> AxisSelection: """Concatenates two AxisSpec. Raises ValueError if any axis is present in both specs""" - def _ax_name(ax: AxisSelector) -> str: - if isinstance(ax, Axis): - return ax.name - else: - return ax - if isinstance(a1, Axis) and isinstance(a2, Axis): if _ax_name(a1) == _ax_name(a2): raise ValueError(f"Axis {a1} specified twice") @@ -136,6 +131,39 @@ def concat_axes(a1: AxisSelection, a2: AxisSelection) -> AxisSelection: return a1 + a2 +@typing.overload +def union_axes(a1: AxisSpec, a2: AxisSpec) -> AxisSpec: + ... + + +@typing.overload +def union_axes(a1: AxisSelection, a2: AxisSelection) -> AxisSelection: + ... + + +def union_axes(a1: AxisSelection, a2: AxisSelection) -> AxisSelection: + """ + Similar to concat_axes, but allows axes to be specified multiple times. The resulting AxisSpec will have the + order of just concatenating each axis spec, but with any duplicate axes removed. + + Raises if any axis is present in both specs with different sizes + """ + a1 = ensure_tuple(a1) + a2 = ensure_tuple(a2) + + a1_dict = _spec_to_dict(a1) + a2_dict = _spec_to_dict(a2) + + for ax, sz in a2_dict.items(): + if ax in a1_dict: + if sz is not None and a1_dict[ax] is not None and sz != a1_dict[ax]: + raise ValueError(f"Axis {ax} present in both specs with different sizes") + else: + a1_dict[ax] = sz + + return _dict_to_spec(a1_dict) + + @overload def eliminate_axes(axis_spec: AxisSpec, axes: AxisSelection) -> Tuple[Axis, ...]: # type: ignore ... @@ -152,16 +180,10 @@ def eliminate_axes(axis_spec: AxisSelection, to_remove: AxisSelection) -> AxisSe to_remove = ensure_tuple(to_remove) axis_spec_dict = _spec_to_dict(axis_spec) for ax in to_remove: - if isinstance(ax, Axis): - if ax.name not in axis_spec_dict: - raise ValueError(f"Axis {ax.name} not present in axis spec {axis_spec}") - del axis_spec_dict[ax.name] - elif isinstance(ax, str): - if ax not in axis_spec_dict: - raise ValueError(f"Axis {ax} not present in axis spec {axis_spec}") - del axis_spec_dict[ax] - else: - raise ValueError(f"Invalid axis spec: {ax}") + name = _ax_name(ax) + if name not in axis_spec_dict: + raise ValueError(f"Axis {name} not present in axis spec {axis_spec}") + del axis_spec_dict[name] return _dict_to_spec(axis_spec_dict) @@ -205,3 +227,10 @@ def overlapping_axes(ax1: AxisSelection, ax2: AxisSelection) -> Tuple[AxisSelect raise ValueError(f"Invalid axis spec: {ax}") return tuple(out) + + +def _ax_name(ax: AxisSelector) -> str: + if isinstance(ax, Axis): + return ax.name + else: + return ax diff --git a/src/haliax/core.py b/src/haliax/core.py index 30c0272..58c470d 100644 --- a/src/haliax/core.py +++ b/src/haliax/core.py @@ -16,7 +16,7 @@ import haliax.axis from haliax.jax_utils import is_jax_array_like from haliax.util import ensure_tuple, index_where, py_slice, slice_t -from .axis import Axis, AxisSelection, AxisSelector, AxisSpec, eliminate_axes, selects_axis +from .axis import Axis, AxisSelection, AxisSelector, AxisSpec, eliminate_axes, selects_axis, union_axes from .types import PrecisionLike, Scalar @@ -907,28 +907,31 @@ def dot(axis: AxisSelection, *arrays: NamedArray, precision: PrecisionLike = Non and any other axes that are shared between the arrays are batched over. Non-contracted Axes in one that are not in the other are preserved. """ + _ensure_no_mismatched_axes(*arrays) + output_axes: Tuple[Axis, ...] = ft.reduce(union_axes, (a.axes for a in arrays), ()) # type: ignore + output_axes = eliminate_axes(output_axes, axis) + axis = ensure_tuple(axis) array_specs = [] next_index = 0 - axis_mappings: Dict[Axis, int] = {} + axis_mappings: Dict[str, int] = {} for a in arrays: spec = "" for ax in a.axes: - if ax in axis_mappings: - spec += f"{axis_mappings[ax]} " + if ax.name in axis_mappings: + spec += f"{axis_mappings[ax.name]} " else: - axis_mappings[ax] = next_index + axis_mappings[ax.name] = next_index spec += f"{next_index} " next_index += 1 array_specs.append(spec) # now compute the output axes: - output_axes = tuple(ax for ax in axis_mappings.keys() if not selects_axis(ax, axis)) - output_spec = " ".join(str(axis_mappings[ax]) for ax in output_axes) + output_spec = " ".join(str(axis_mappings[ax.name]) for ax in output_axes) output = jnp.einsum( ", ".join(array_specs) + "-> " + output_spec, @@ -1377,6 +1380,21 @@ def check_shape(jnp_shape: Sequence[int], hax_axes: AxisSelection) -> Tuple[Axis return tuple(result_axes) +def _ensure_no_mismatched_axes(*arrays: NamedArray): + """Ensure that all the arrays have no axes with the same name but different sizes""" + if len(arrays) <= 1: + return + + known_sizes: dict[str, int] = {} + for a in arrays: + for ax in a.axes: + if ax.name in known_sizes: + if known_sizes[ax.name] != ax.size: + raise ValueError(f"Axis {ax.name} has multiple sizes: {known_sizes[ax.name]} and {ax.size}") + else: + known_sizes[ax.name] = ax.size + + __all__ = [ "NamedArray", "dot", diff --git a/tests/core_test.py b/tests/core_test.py index 3a24d58..fd1147d 100644 --- a/tests/core_test.py +++ b/tests/core_test.py @@ -53,6 +53,20 @@ def test_dot_string_selection(): ) +def test_dot_errors_if_different_sized_axes(): + Height = Axis("Height", 2) + Width = Axis("Width", 3) + Depth = Axis("Depth", 4) + + H2 = Axis("Height", 4) + + m1 = NamedArray(jnp.ones((Height.size, Width.size, Depth.size)), (Height, Width, Depth)) + m2 = NamedArray(jnp.ones((Depth.size, Width.size, H2.size)), (Depth, Width, H2)) + + with pytest.raises(ValueError): + hax.dot("Height", m1, m2) + + def test_unary_np_functions(): Height = Axis("Height", 2) Width = Axis("Width", 3) commit d4943a03030e7837723c87c6354f496fd827fe40 Date: 2023-08-11T16:24:40-07:00 add a resize_embeddings function diff --git a/src/haliax/nn/embedding.py b/src/haliax/nn/embedding.py index c150b05..649a91a 100644 --- a/src/haliax/nn/embedding.py +++ b/src/haliax/nn/embedding.py @@ -1,10 +1,15 @@ +import dataclasses +from typing import Optional + import equinox as eqx +from jaxtyping import PRNGKeyArray import haliax as hax from ..axis import Axis from ..core import NamedArray from ..jax_utils import named_call +from ..tree_util import resize_axis class Embedding(eqx.Module): @@ -30,3 +35,7 @@ class Embedding(eqx.Module): def unembed(self, input_embeds): return input_embeds.dot(self.Embed, self.weight) + + def resize_embeddings(self, new_size: int, key: Optional[PRNGKeyArray] = None): + new_weights = resize_axis(self.weight, self.Vocab, new_size, key=key) + return dataclasses.replace(self, Vocab=self.Vocab.resize(new_size), weight=new_weights) diff --git a/src/haliax/tree_util.py b/src/haliax/tree_util.py index 60cff83..8f210fa 100644 --- a/src/haliax/tree_util.py +++ b/src/haliax/tree_util.py @@ -1,17 +1,26 @@ +from typing import Optional + import equinox as eqx import jax import jax.tree_util as jtu from jaxtyping import PRNGKeyArray, PyTree -from .axis import Axis +from .axis import AxisSelector from .core import NamedArray +from .jax_utils import maybe_rng_split from .util import is_named_array -def resize_axis(tree: PyTree[NamedArray], axis: Axis, key: PRNGKeyArray): - """Resizes the NamedArrays of a PyTree along a given axis. If the array needs to grow, then the new elements are - sampled from a truncated normal distribution with the same mean and standard deviation as the existing elements. - If the array needs to shrink, then it's truncated.""" +def resize_axis(tree: PyTree[NamedArray], old_axis: AxisSelector, new_size: int, key: Optional[PRNGKeyArray] = None): + """Resizes the NamedArrays of a PyTree along a given axis. If the array needs to grow and key is not none, then the + new elements are sampled from a truncated normal distribution with the same mean and standard deviation as the + existing elements. If the key is none, they're just initialized to the mean. If the array needs to shrink, then it's + truncated. + + Note: if you have a module that stores a reference to the old axis, then you'll need to update that reference + manually. + + """ import haliax.random def _resize_one(x, key): @@ -21,30 +30,33 @@ def resize_axis(tree: PyTree[NamedArray], axis: Axis, key: PRNGKeyArray): assert isinstance(x, NamedArray) try: - current_axis = x.resolve_axis(axis.name) + current_axis = x.resolve_axis(old_axis) except ValueError: return x - if axis.size == current_axis.size: + if new_size == current_axis.size: return x - elif current_axis.size > axis.size: - return x.slice(current_axis, start=0, new_axis=axis) + elif current_axis.size > new_size: + return x.slice(current_axis, start=0, length=new_size) else: - num_padding = axis.size - current_axis.size + num_padding = new_size - current_axis.size mean = x.mean(current_axis) std = x.std(current_axis) # the shape of the padding is the same as the original array, except with the axis size changed padding_axes = list(x.axes) - padding_axes[padding_axes.index(current_axis)] = axis.resize(num_padding) + padding_axes[padding_axes.index(current_axis)] = current_axis.resize(num_padding) - padding = haliax.random.truncated_normal(key, padding_axes, lower=-2, upper=2) * std + mean + if key is None: + padding = mean.broadcast_axis(padding_axes) + else: + padding = haliax.random.truncated_normal(key, padding_axes, lower=-2, upper=2) * std + mean - return haliax.concatenate(axis, [x, padding]) + return haliax.concatenate(current_axis.name, [x, padding]) leaves, structure = jax.tree_util.tree_flatten(tree, is_leaf=is_named_array) - keys = jax.random.split(key, len(leaves)) + keys = maybe_rng_split(key, len(leaves)) new_leaves = [_resize_one(x, key) for x, key in zip(leaves, keys)] commit 728d8d0863df044a978d4dd80e75cf18a43f2a39 Date: 2023-08-13T23:07:05-07:00 support fancier masks in levanter fa branch (#15) diff --git a/src/haliax/__init__.py b/src/haliax/__init__.py index e056360..a4e3ef7 100644 --- a/src/haliax/__init__.py +++ b/src/haliax/__init__.py @@ -83,8 +83,11 @@ def full_like(a: NamedArray, fill_value, dtype=None) -> NamedArray: def arange(axis: Axis, *, start=0, step=1, dtype=None) -> NamedArray: """Version of jnp.arange that returns a NamedArray""" - stop = start + axis.size * step - return NamedArray(jnp.arange(start, stop, step, dtype=dtype), (axis,)) + # if start is a tracer, we need to be a bit cleverer since arange doesn't support tracers + # return NamedArray(jnp.arange(start, stop, step, dtype=dtype), (axis,)) + + arr = jax.lax.iota(dtype=dtype or jnp.result_type(start), size=axis.size) * step + start + return NamedArray(arr, (axis,)) def stack(axis: AxisSelector, arrays: Sequence[NamedArray]) -> NamedArray: diff --git a/src/haliax/nn/attention.py b/src/haliax/nn/attention.py index 8455908..45f08b8 100644 --- a/src/haliax/nn/attention.py +++ b/src/haliax/nn/attention.py @@ -133,27 +133,26 @@ def combine_masks_or(mask1: Optional[NamedArray], mask2: Optional[NamedArray]) - return mask1 | mask2 -def causal_mask(QPos: Axis, KPos: Axis) -> NamedArray: +def causal_mask(QPos: Axis, KPos: Axis, q_start: int = 0, k_start: int = 0) -> NamedArray: """ - Creates a causal mask for attention. + Creates a materialized causal mask for attention. :param QPos: Axis of query sequence length :param KPos: Axis of key sequence length :return: NamedArray of shape (QPos, KPos) """ - # copilot wrote this and i'm just blown away - return haliax.arange(QPos).broadcast_axis(KPos) >= haliax.arange(KPos).broadcast_axis(QPos) + return haliax.arange(QPos, start=q_start) >= haliax.arange(KPos, start=k_start).broadcast_axis(QPos) -def prefix_lm_mask(QSeqLen: Axis, KSeqLen: Axis, prefix_len: int) -> NamedArray: +def prefix_lm_mask(QSeqLen: Axis, KSeqLen: Axis, prefix_len: int, q_start: int = 0, k_start: int = 0) -> NamedArray: """Mask for the PrefixLM objective: fully connected before prefix_len, then causal after.""" # sometimes prefix_len is a tracer so we can't assert if isinstance(prefix_len, int): assert prefix_len >= 0 - assert prefix_len <= KSeqLen.size + # assert prefix_len <= KSeqLen.size - causal = causal_mask(QSeqLen, KSeqLen) - prefix = haliax.arange(KSeqLen) < prefix_len + causal = causal_mask(QSeqLen, KSeqLen, q_start=q_start, k_start=k_start) + prefix = haliax.arange(KSeqLen, start=k_start) < (prefix_len + k_start) return prefix | causal @@ -178,7 +177,7 @@ def forgetful_causal_mask(KPos: Axis, mask_prob: float, sample_prob: bool = True """ zeroth_on = haliax.nn.one_hot(0, KPos, dtype=jnp.bool_) # always allow 0th position if mask_prob == 0: - return jnp.ones((KPos.size,), dtype=jnp.bool_) + return haliax.ones((KPos,), dtype=jnp.bool_) elif mask_prob == 1: return zeroth_on else: diff --git a/tests/test_tree_util.py b/tests/test_tree_util.py index 0eb6ade..c1bb89d 100644 --- a/tests/test_tree_util.py +++ b/tests/test_tree_util.py @@ -26,7 +26,7 @@ def test_resize_axis(): NewA = A.resize(15) - module2 = htu.resize_axis(module, NewA, jax.random.PRNGKey(1)) + module2 = htu.resize_axis(module, "A", 15, key=jax.random.PRNGKey(1)) assert module2.name1.axes == (B, NewA, C) assert module2.name2.axes == (B, C) commit ec0b406291e1429063eb355f4e3b7468b6149ee9 Date: 2023-08-15T13:54:06-07:00 Stacked: default to prevent_cse=True, but expose a flag diff --git a/src/haliax/nn/scan.py b/src/haliax/nn/scan.py index fad38ac..7a5e66b 100644 --- a/src/haliax/nn/scan.py +++ b/src/haliax/nn/scan.py @@ -45,7 +45,8 @@ class Stacked(eqx.Module, Generic[M]): >>> class MyModule(eqx.Module): ... def __init__(self, num_layers: int, hidden: hax.Axis, *, key): ... self.axis = hax.Axis("layer", num_layers) - ... self.layers = Stacked.init(self.axis, hnn.Linear)(In=hidden, Out=hidden, key=key) + ... split_key = jax.random.split(key, num_layers) + ... self.layers = Stacked.init(self.axis, hnn.Linear)(In=hidden, Out=hidden, key=split_key) ... ... def __call__(self, x): ... return self.layers.fold(x) # applies each layer in sequence @@ -61,19 +62,32 @@ class Stacked(eqx.Module, Generic[M]): Block: Axis = eqx.static_field() # TODO: support fancier gradient checkpointing gradient_checkpointing: bool = eqx.static_field() + prevent_cse: bool = eqx.static_field() @staticmethod - def init(Block: Axis, module: Type[M], *, gradient_checkpointing: bool = False) -> ModuleInit["Stacked[M]"]: + def init( + Block: Axis, module: Type[M], *, gradient_checkpointing: bool = False, prevent_cse: bool = True + ) -> ModuleInit["Stacked[M]"]: + """ + Initialize a Stacked module. This method is curried: you can pass in the Block and module, and it will return + a function that takes (batched) arguments to the vmapped module's init method. + :param Block: + :param module: + :param gradient_checkpointing: + :param prevent_cse: + :return: + """ + @functools.wraps(module) def fn(*args, **kwargs): stacked = haliax.vmap(module.init, Block)(*args, **kwargs) - return Stacked(stacked, Block, gradient_checkpointing) + return Stacked(stacked, Block, gradient_checkpointing, prevent_cse) return fn def scan(self, init, *extra_args, **extra_kwargs): if self.gradient_checkpointing: - do_block = filter_checkpoint(self._do_block, prevent_cse=False) + do_block = filter_checkpoint(self._do_block, prevent_cse=self.prevent_cse) else: do_block = self._do_block return haliax.scan(do_block, self.Block)(init, self.stacked, *extra_args, **extra_kwargs) commit 2ab7cdb6953071bc966468663399aa289d3bc2df Date: 2023-08-16T00:47:45-07:00 support non-static fields in hax.vmap diff --git a/src/haliax/hof.py b/src/haliax/hof.py index c2324e4..796f04d 100644 --- a/src/haliax/hof.py +++ b/src/haliax/hof.py @@ -10,7 +10,7 @@ from jaxtyping import PyTree from .axis import Axis, AxisSelector, selects_axis from .core import NamedArray -from .jax_utils import broadcast_prefix, is_jax_array_like +from .jax_utils import Static, broadcast_prefix, is_jax_array_like from .partitioning import physical_axis_name from .util import index_where, is_jax_or_hax_array_like, is_named_array @@ -263,11 +263,12 @@ def vmap( # now we need to pacify the output, which may include NamedArrays, and add the batch axis back at the end chilled = jax.tree_util.tree_map(_pacify_named_arrays, out, is_leaf=is_named_array) - return chilled + arrays, nonarrays = eqx.partition(chilled, eqx.is_array_like) + return arrays, Static(nonarrays) spmd_axis_name = physical_axis_name(axis) - result = jax.vmap( + result_dynamic, result_static = jax.vmap( wrapped_fn, in_axes=(arg_axis_specs, kwarg_axis_specs), out_axes=0, @@ -275,6 +276,8 @@ def vmap( spmd_axis_name=spmd_axis_name, )(args, kwargs) + result = eqx.combine(result_dynamic, result_static.value) + # if we were passed in a string arg, we need to get its axis size out from some result true_axis = _infer_axis_size_from_result(result, axis) if true_axis is None: diff --git a/tests/test_hof.py b/tests/test_hof.py index 9d11a1d..6577eb1 100644 --- a/tests/test_hof.py +++ b/tests/test_hof.py @@ -1,3 +1,4 @@ +import equinox as eqx import jax.numpy as jnp from jax.random import PRNGKey @@ -212,3 +213,17 @@ def test_vmap_static_args(): assert jnp.all(jnp.equal(selected.array, expected.array)) assert selected.axes == expected.axes + + +def test_vmap_error_for_incorrectly_specified_args(): + class Module(eqx.Module): + # this should usually be declared static, but we're simulating a user error + field: Axis + + def __call__(self, x): + return x.sum(self.field) + + Batch = Axis("Batch", 10) + Width = Axis("Width", 3) + + hax.vmap(lambda a: Module(a), Batch)(Width) commit 6ebec3acf8d461ebf8c39caec5737a7fe3755e4c Date: 2023-08-23T09:13:23-07:00 Add lots of docs for Haliax, support for readthedocs (#16) diff --git a/.readthedocs.yaml b/.readthedocs.yaml new file mode 100644 index 0000000..eb8f36c --- /dev/null +++ b/.readthedocs.yaml @@ -0,0 +1,17 @@ +# Read the Docs configuration file for MkDocs projects +# See https://docs.readthedocs.io/en/stable/config-file/v2.html for details +# Required +version: 2 +# Set the version of Python and other tools you might need +build: + os: ubuntu-22.04 + tools: + python: "3.11" + +mkdocs: + configuration: mkdocs.yml + +# Optionally declare the Python requirements required to build your docs +python: + install: + - requirements: docs/requirements.txt diff --git a/README.md b/README.md index 2270008..3d0a926 100644 --- a/README.md +++ b/README.md @@ -81,7 +81,7 @@ our companion library for training large language models and other foundation mo and up to a TPU v3-256 pod slice. -Haliax was created by [Stanford's Center for Research on Foundation Models (CRFM)](https://crfm.stanford.edu/)'s research engineering team. ([We're hiring!](https://crfm.stanford.edu/apply.html)) +Haliax was created by [Stanford's Center for Research on Foundation Models (CRFM)](https://crfm.stanford.edu/)'s research engineering team. You can find us in the #levanter channel on the unofficial [Jax LLM Discord](https://discord.gg/FkRGNX3ND). <!--haliax-intro-end--> @@ -90,11 +90,15 @@ You can find us in the #levanter channel on the unofficial [Jax LLM Discord](htt Currently, we have four tutorials for Haliax : +<!--haliax-tutorials-start--> + * [Introduction to Haliax with Transformers](https://colab.research.google.com/drive/1TiTcQQ4V5mopbgCu1SVl-oqJtXn7rFnC) * [Distributed Training in Haliax](https://colab.research.google.com/drive/1QX4yH3zRFF3Xiibf1aahETcSQ5nbcUMz) (including FSDP) * [Tensor Parallelism in Haliax](https://colab.research.google.com/drive/18_BrtDpe1lu89M4T6fKzda8DdSLtFJhi) * [Mixed Precision with `jmp`](https://colab.research.google.com/drive/1_4cikwt-UhSH7yRzNRK8ze9msM9r2mEl?usp=sharing) (This one is really a tutorial for [jmp](https://github.com/deepmind/jmp) but it's how to use it with Haliax...) +<!--haliax-tutorials-end--> + ## Contributing We welcome contributions! Please see [CONTRIBUTING.md](CONTRIBUTING.md) for more information. diff --git a/docs/api.md b/docs/api.md new file mode 100644 index 0000000..2136bde --- /dev/null +++ b/docs/api.md @@ -0,0 +1,271 @@ +# Main API Reference +In general, the API is designed to be similar to JAX's version of NumPy's API, with the main difference being +that we use names (either strings or [haliax.Axis][] objects) to specify axes instead of integers. This shows up for creating +arrays (see [haliax.zeros][] and [haliax.ones][]) as well as things like reductions (see [haliax.sum][] and +[haliax.mean][]). + +## Axis Types + +There are four types related to [haliax.Axis][] you will see in the API reference: + +* [haliax.Axis][]: This is the main type for representing axes. It is a dataclass with a name and a size. +* [haliax.AxisSelector][]: This is a type alias for either [haliax.Axis][] or a `str`. This type is used when we want + one axis and the size can be inferred from the inputs. +* [haliax.AxisSpec][]: This is a type alias for either [haliax.Axis][] or a tuple/list of [haliax.Axis][]. This type is + used when we want one or more axes and the sizes cannot be inferred from the inputs, for instance when creating arrays. +* [haliax.AxisSelection][]: This is a type alias for either [haliax.AxisSelector][] or a tuple/list of [haliax.AxisSelector][]. + This type is used when we want one or more axes and the sizes can be inferred from the inputs, for instance when + reducing an array. + +Occasionally, an axis size can be inferred in some circumstances but not others. When this happens, we still use +`AxisSelector` but document the behavior in the docstring. A RuntimeError will be raised if the size cannot be inferred. + +::: haliax.Axis +::: haliax.AxisSelector +::: haliax.AxisSpec +::: haliax.AxisSelection + +### Axis Manipulation + +::: haliax.axis.concat_axes +::: haliax.axis.union_axes +::: haliax.axis.eliminate_axes +::: haliax.axis.overlapping_axes +::: haliax.axis.selects_axis +::: haliax.axis.is_axis_compatible + + +## Array Creation +::: haliax.named +::: haliax.zeros +::: haliax.ones +::: haliax.full +::: haliax.zeros_like +::: haliax.ones_like +::: haliax.full_like +::: haliax.arange +::: haliax.linspace +::: haliax.logspace +::: haliax.geomspace + + +### Combining Arrays + +We don't include `hstack` or `vstack` because we prefer semantic axes. + +::: haliax.concatenate +::: haliax.stack + + +## Array Manipulation + +### Broadcasting + +See also the section on [Broadcasting](broadcasting.md). + +::: haliax.broadcast_axis +::: haliax.broadcast_to + +### Slicing + +See also the section on [Indexing and Slicing](indexing.md). + +::: haliax.index +::: haliax.slice +::: haliax.take +::: haliax.updated_slice + +### Shape Manipulation + +::: haliax.flatten_axes +::: haliax.rearrange +::: haliax.unbind +::: haliax.unflatten_axis +::: haliax.split + + +## Operations + +[Binary](#binary-operations) and [unary](#unary-operations) operations are all more or less directly from JAX's NumPy API. +The only difference is they operate on named arrays instead. + +## Matrix Multiplication + +::: haliax.dot + +### Reductions + +Reduction operations are things like [haliax.sum][] and [haliax.mean][] that reduce an array along one or more axes. +Except for [haliax.argmin][] and [haliax.argmax][], they all have the form: + +```python +def sum(x, axis: Optional[AxisSelection] = None, where: Optional[NamedArray] = None) -> haliax.NamedArray: + ... +``` + +with the behavior closely mirroring that of JAX's NumPy API. The `axis` argument can +be a single axis (or axis name), a tuple of axes, or `None` to reduce all axes. The `where` argument is a boolean array +that specifies which elements to include in the reduction. It must be broadcastable to the input array, using +Haliax's [broadcasting rules](broadcasting.md). + +::: haliax.all +::: haliax.amax +::: haliax.any +::: haliax.argmax +::: haliax.argmin +::: haliax.max +::: haliax.mean +::: haliax.min +::: haliax.prod +::: haliax.ptp +::: haliax.std +::: haliax.sum +::: haliax.var + +### Axis-Wise Operations +Axis-wise operations are things like [haliax.cumsum][] and [haliax.sort][] that operate on a single axis of an array but +don't reduce it. + +::: haliax.cumsum +::: haliax.cumprod +::: haliax.sort +::: haliax.argsort + +### Unary Operations + +The `A` in these operations means [haliax.NamedArray][], a `Scalar`, or [jax.numpy.ndarray][]. +These are all more or less directly from JAX's NumPy API. + +::: haliax.abs +::: haliax.absolute +::: haliax.angle +::: haliax.arccos +::: haliax.arccosh +::: haliax.arcsin +::: haliax.arcsinh +::: haliax.arctan +::: haliax.arctanh +::: haliax.around +::: haliax.bitwise_not +::: haliax.cbrt +::: haliax.ceil +::: haliax.conj +::: haliax.conjugate +::: haliax.copy +::: haliax.cos +::: haliax.cosh +::: haliax.deg2rad +::: haliax.degrees +::: haliax.exp +::: haliax.exp2 +::: haliax.expm1 +::: haliax.fabs +::: haliax.fix +::: haliax.floor +::: haliax.frexp +::: haliax.i0 +::: haliax.imag +::: haliax.invert +::: haliax.iscomplex +::: haliax.isfinite +::: haliax.isinf +::: haliax.isnan +::: haliax.isneginf +::: haliax.isposinf +::: haliax.isreal +::: haliax.log +::: haliax.log10 +::: haliax.log1p +::: haliax.log2 +::: haliax.logical_not +::: haliax.ndim +::: haliax.negative +::: haliax.positive +::: haliax.rad2deg +::: haliax.radians +::: haliax.real +::: haliax.reciprocal +::: haliax.rint +::: haliax.round +::: haliax.rsqrt +::: haliax.sign +::: haliax.signbit +::: haliax.sin +::: haliax.sinc +::: haliax.sinh +::: haliax.square +::: haliax.sqrt +::: haliax.tan +::: haliax.tanh +::: haliax.trunc + +### Binary Operations +::: haliax.add +::: haliax.arctan2 +::: haliax.bitwise_and +::: haliax.bitwise_or +::: haliax.bitwise_xor +::: haliax.divide +::: haliax.divmod +::: haliax.equal +::: haliax.float_power +::: haliax.floor_divide +::: haliax.fmax +::: haliax.fmin +::: haliax.fmod +::: haliax.greater +::: haliax.greater_equal +::: haliax.hypot +::: haliax.left_shift +::: haliax.less +::: haliax.less_equal +::: haliax.logaddexp +::: haliax.logaddexp2 +::: haliax.logical_and +::: haliax.logical_or +::: haliax.logical_xor +::: haliax.maximum +::: haliax.minimum +::: haliax.mod +::: haliax.multiply +::: haliax.nextafter +::: haliax.not_equal +::: haliax.power +::: haliax.remainder +::: haliax.right_shift +::: haliax.subtract +::: haliax.true_divide + +### Other Operations + +::: haliax.clip +::: haliax.isclose +::: haliax.trace +::: haliax.tril +::: haliax.triu +::: haliax.where + + + +## Named Array Reference + +Most methods on [haliax.NamedArray][] just call the corresponding `haliax` function with the array as the first argument, +just as with Numpy. +The exceptions are documented here: + +::: haliax.NamedArray + + +## Partitioning API + +See also the section on [Partitioning](partitioning.md). + +::: haliax.partitioning.axis_mapping +::: haliax.shard_with_axis_mapping +::: haliax.auto_sharded +::: haliax.named_jit +::: haliax.fsdp +::: haliax.partitioning.round_axis_for_partitioning +::: haliax.partitioning.physical_axis_name +::: haliax.partitioning.physical_axis_size +::: haliax.partitioning.sharding_for_axis diff --git a/docs/broadcasting.md b/docs/broadcasting.md new file mode 100644 index 0000000..472ce48 --- /dev/null +++ b/docs/broadcasting.md @@ -0,0 +1,85 @@ +# Broadcasting + +One area where Haliax's treatment of named axes differs substantially from Numpy-esque positional code is in broadcasting. In traditional positional code, [broadcasting works like this](https://numpy.org/doc/stable/user/basics.broadcasting.html): + +```python +import numpy as np + +# compute the outer product of two arrays +a = np.arange(5) +b = np.arange(4) + +c = a.reshape((-1, 1)) * b.reshape((1, -1)) +print(c.shape) +print(c) + +# alternatively +c2 = a[:, np.newaxis] * b +``` + +This prints: +``` +(5, 4) +[[ 0 0 0 0] + [ 0 1 2 3] + [ 0 2 4 6] + [ 0 3 6 9] + [ 0 4 8 12]] +``` + +To quote the NumPy documentation, for positional arrays, "in order to broadcast, the size of the trailing axes for both arrays in an operation must either be the same size or one of them must be one." + +I have found this to be a source of bugs: it is easy to accidentally have an array of size [batch_size, 1] and combine it with an array of size [batch_size], yielding an array of [batch_size, batch_size]. + +In Haliax, broadcasting is done by matching names. The same operation in Haliax might look like this: + +```python +M = hax.Axis("M", 5) +N = hax.Axis("N", 4) + +a = hax.arange(M) +b = hax.arange(N) + +c = a.broadcast_axis(N) * b +print(c.axes) +print(c.array) +``` + +``` +(Axis(name='N', size=4), Axis(name='M', size=5)) +[[ 0 0 0 0 0] + [ 0 1 2 3 4] + [ 0 2 4 6 8] + [ 0 3 6 9 12]] +``` + +Haliax aims to be "order-independent" as much as possible (while still letting you choose the order for performance or compatibility with positional code). +Its semantics are: "in order to broadcast, identically named Axes of the arrays must have the same size. +In addition, they must share at least one named axis in common, unless one is a scalar." +The second condition is there to avoid bugs: we want to be sure that the arrays have something in common. +To satisfy the second condition, it is not uncommon to use [haliax.broadcast_axis][], like we did above. +This method takes one or more axes and adds them to the array. + +## Explicit Broadcasting Functions + +::: haliax.broadcast_axis +::: haliax.broadcast_to + + +<!-- +### Advanced Broadcasting Functions + +You probably won't need these, but they're here if you do. + +::: haliax.core.broadcast_arrays +::: haliax.core.broadcast_arrays_and_return_axes + +--> + +## A note on performance + +Under the hood, Haliax will automatically broadcast and permute axes so that the underlying positional code produces the correct result. +This is usually not a substantial performance hit because XLA is pretty good about picking optimal shapes, +but if you're doing repeated operations you may want to use [haliax.rearrange][] to change the order of axes. +As an example, in Levanter's GPT-2 implementation, we found using `rearrange` led to a 5% speedup for small models. This +isn't huge, but it's not nothing either. diff --git a/docs/cheatsheet.md b/docs/cheatsheet.md new file mode 100644 index 0000000..1b82e9b --- /dev/null +++ b/docs/cheatsheet.md @@ -0,0 +1,127 @@ +# Haliax Cheatsheet + +This is a cheatsheet for converting common functions and tasks from JAX/NumPy to Haliax. +Please open [an issue on Github](https://github.com/stanford-crfm/haliax/issues/) if you find any errors or omissions. +We're happy to add more examples if you have any that you think would be useful. + +## Preamble + +Throughout we assume the following: + +``` +import jax.numpy as jnp +import jax + +import haliax as hax + +Batch = hax.Axis("batch", 32) +Embed = hax.Axis("embed", 64) + +# for jax +x = jnp.zeros((32, 64)) +y = jnp.zeros((32, 64)) +z = jnp.zeros((32,)) +w = jnp.zeros((64,)) +ind = jnp.arange((8,), dtype=jnp.int32) + +# for haliax +x = hax.zeros((Batch, Embed)) +y = hax.zeros((Batch, Embed)) +z = hax.zeros((Batch,)) +w = hax.zeros((Embed,)) +ind = hax.arange(Axis("Index", 8), dtype=jnp.int32) +``` + + +## Array Creation + +| JAX | Haliax | +|------------------------------------------------|------------------------------------------------| +| [`jnp.zeros((32, 64))`][jax.numpy.zeros] | [`hax.zeros((Batch, Embed))`][haliax.zeros] | +| [`jnp.ones((32, 64))`][jax.numpy.ones] | [`hax.ones((Batch, Embed))`][haliax.ones] | +| [`jnp.zeros_like(x)`][jax.numpy.zeros_like] | [`hax.zeros_like(x)`][haliax.zeros_like] | +| [`jnp.ones_like(x)`][jax.numpy.ones_like] | [`hax.ones_like(x)`][haliax.ones_like] | +| [`jnp.eye(32)`][jax.numpy.eye] | ❌ | +| [`jnp.arange(32)`][jax.numpy.arange] | [`hax.arange(Batch)`][haliax.arange] | +| [`jnp.linspace(0, 1, 32)`][jax.numpy.linspace] | [`hax.linspace(Batch, 0, 1)`][haliax.linspace] | + +### Combining Arrays + +| JAX | Haliax | +|----------------------------------------------------|----------------------------------------------------------| +| [`jnp.concatenate([x, y])`][jax.numpy.concatenate] | [`hax.concatenate("batch", [x, y])`][haliax.concatenate] | +| [`jnp.stack([x, y])`][jax.numpy.stack] | [`hax.stack("foo", [x, y])`][haliax.stack] | +| [`jnp.hstack([x, y])`][jax.numpy.hstack] | [`hax.concatenate("embed", [x, y])`][haliax.concatenate] | +| [`jnp.vstack([x, y])`][jax.numpy.vstack] | [`hax.concatenate("batch", [x, y])`][haliax.concatenate] | + +## Array Manipulation + +### Broadcasting + +See also the section on [Broadcasting](broadcasting.md). + +| JAX | Haliax | +|--------------------------------------------------------------------------|-------------------------------------------------------| +| [`jnp.broadcast_to(z.reshape(-1, 1), (32, 64))`][jax.numpy.broadcast_to] | [`hax.broadcast_axis(z, Embed)`][haliax.broadcast_axis] | +| Outer product: `z.reshape(-1, 1) * w.reshape(1, -1)` | `z * w.broadcast_axis(Batch)` | + + +### Indexing and Slicing + +See also the section on [Indexing and Slicing](indexing.md). + +| JAX | Haliax | +|-------------------------------------------------------------------|-------------------------------------------------------------| +| `x[0]` | [`x["batch", 0]`][haliax.index] | +| `x[:, 0]` | [`x["embed", 0]`][haliax.index] | +| `x[0, 1]` | [`x["batch", 0, "embed", 1]`][haliax.index] | +| `x[0:10]` | [`x["batch", 0:10]`][haliax.index] | +| `x[0:10:2]` | [`x["batch", 0:10:2]`][haliax.index] | +| `x[0, 1:10:2]` | [`x["batch", 0, "embed", 1:10:2]`][haliax.index] | +| `x[0, [1, 2, 3]]` | [`x["batch", 0, "embed", [1, 2, 3]]`][haliax.index] | +| `x[0, ind]` | [`x["batch", 0, "embed", ind]`][haliax.index] | +| `jnp.take_along_axis(x, ind, axis=1)`][jax.numpy.take_along_axis] | [`hax.take(x, "embed", ind)`][haliax.take] | +| `jax.lax.dynamic_slice(x, [4], [10])`][jax.lax.dynamic_slice] | [`hax.slice(x, "batch", start=4, length=10)`][haliax.slice] | + +### Shape Manipulation + +| JAX | Haliax | +|-----------------------------------------------|-------------------------------------------------------------------------------------| +| [`x.transpose((1, 0))`][jax.numpy.transpose] | [`x.rearrange("embed", "batch")`][haliax.rearrange] | +| [`x.reshape((2, 16, 64))`][jax.numpy.reshape] | [`x.unflatten_axis("batch", (Axis("a", 2), Axis("b", 16)))`][haliax.unflatten_axis] | +| [`x.reshape((-1,))`][jax.numpy.reshape] | [`x.flatten_axes(("batch", "embed"), "foo")`][haliax.flatten_axes] | + + +## Operations + +### Elementwise Operations + +Almost all elementwise operations are the same as JAX, except that they work on either [haliax.NamedArray][] +or [jax.numpy.ndarray][] objects. + +Any elementwise operation in [jax.nn][] should be in [haliax.nn][]. + +### Binary Operations + +Similarly, binary operations are the same as JAX, except that they work on [haliax.NamedArray][] objects. + +### Reductions + +Reductions are similar to JAX, except that they use an axis name instead of an axis index. + +| JAX | Haliax | +|----------------------------------------------|---------------------------------------------------| +| [`jnp.sum(x, axis=0)`][jax.numpy.sum] | [`hax.sum(x, axis=Batch)`][haliax.sum] | +| [`jnp.mean(x, axis=(0, 1))`][jax.numpy.mean] | [`hax.mean(x, axis=(Batch, Embed))`][haliax.mean] | +| [`jnp.max(x)`][jax.numpy.max] | [`hax.max(x)`][haliax.max] | +| [`jnp.min(x, where=x > 0)`][jax.numpy.min] | [`hax.min(x, where=x > 0)`][haliax.min] | +| [`jnp.argmax(x, axis=0)`][jax.numpy.argmax] | [`hax.argmax(x, axis=Batch)`][haliax.argmax] | + +### Matrix Multiplication + +| JAX | Haliax | +|-----------------------------------------------------|----------------------------------------| +| [`jnp.dot(z, x)`][jax.numpy.dot] | [`hax.dot("batch", z, x)`][haliax.dot] | +| [`jnp.matmul(z, x)`][jax.numpy.matmul] | [`hax.dot("batch", z, x)`][haliax.dot] | +| [`jnp.dot(w, x.t)`][jax.numpy.dot] | [`hax.dot("embed", w, x)`][haliax.dot] | +| [`jnp.einsum("ij,j -> i", x, w)`][jax.numpy.einsum] | [`hax.dot("embed", x, w)`][haliax.dot] | diff --git a/docs/css/material.css b/docs/css/material.css new file mode 100644 index 0000000..b73faaf --- /dev/null +++ b/docs/css/material.css @@ -0,0 +1,25 @@ +.md-main__inner { + margin-bottom: 1.5rem; +} + +/* Custom admonition: preview */ +:root { + --md-admonition-icon--preview: url('data:image/svg+xml;charset=utf-8,<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24"><path d="M15.5 12a3.5 3.5 0 1 1-7 0 3.5 3.5 0 0 1 7 0Z"/><path d="M12 3.5c3.432 0 6.124 1.534 8.054 3.241 1.926 1.703 3.132 3.61 3.616 4.46a1.6 1.6 0 0 1 0 1.598c-.484.85-1.69 2.757-3.616 4.461-1.929 1.706-4.622 3.24-8.054 3.24-3.432 0-6.124-1.534-8.054-3.24C2.02 15.558.814 13.65.33 12.8a1.6 1.6 0 0 1 0-1.598c.484-.85 1.69-2.757 3.616-4.462C5.875 5.034 8.568 3.5 12 3.5ZM1.633 11.945a.115.115 0 0 0-.017.055c.001.02.006.039.017.056.441.774 1.551 2.527 3.307 4.08C6.691 17.685 9.045 19 12 19c2.955 0 5.31-1.315 7.06-2.864 1.756-1.553 2.866-3.306 3.307-4.08a.111.111 0 0 0 .017-.056.111.111 0 0 0-.017-.056c-.441-.773-1.551-2.527-3.307-4.08C17.309 6.315 14.955 5 12 5 9.045 5 6.69 6.314 4.94 7.865c-1.756 1.552-2.866 3.306-3.307 4.08Z"/></svg>'); +} + +.md-typeset .admonition.preview, +.md-typeset details.preview { + border-color: rgb(220, 139, 240); +} + +.md-typeset .preview>.admonition-title, +.md-typeset .preview>summary { + background-color: rgba(142, 43, 155, 0.1); +} + +.md-typeset .preview>.admonition-title::before, +.md-typeset .preview>summary::before { + background-color: rgb(220, 139, 240); + -webkit-mask-image: var(--md-admonition-icon--preview); + mask-image: var(--md-admonition-icon--preview); +} diff --git a/docs/css/mkdocstrings.css b/docs/css/mkdocstrings.css new file mode 100644 index 0000000..3c0b11e --- /dev/null +++ b/docs/css/mkdocstrings.css @@ -0,0 +1,26 @@ +/* Indentation. */ +div.doc-contents:not(.first) { + padding-left: 25px; + border-left: .05rem solid var(--md-typeset-table-color); +} + +/* Mark external links as such. */ +a.external::after, +a.autorefs-external::after { + /* https://primer.style/octicons/arrow-up-right-24 */ + mask-image: url('data:image/svg+xml,<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24"><path d="M18.25 15.5a.75.75 0 00.75-.75v-9a.75.75 0 00-.75-.75h-9a.75.75 0 000 1.5h7.19L6.22 16.72a.75.75 0 101.06 1.06L17.5 7.56v7.19c0 .414.336.75.75.75z"></path></svg>'); + content: ' '; + + display: inline-block; + vertical-align: middle; + position: relative; + + height: 1em; + width: 1em; + background-color: var(--md-typeset-a-color); +} + +a.external:hover::after, +a.autorefs-external:hover::after { + background-color: var(--md-accent-fg-color); +} diff --git a/docs/figures/data_parallel_mesh.png b/docs/figures/data_parallel_mesh.png new file mode 100644 index 0000000..720b147 Binary files /dev/null and b/docs/figures/data_parallel_mesh.png differ diff --git a/docs/figures/data_parallel_mesh_replicated.png b/docs/figures/data_parallel_mesh_replicated.png new file mode 100644 index 0000000..4302c9c Binary files /dev/null and b/docs/figures/data_parallel_mesh_replicated.png differ diff --git a/docs/figures/device_mesh_1d.png b/docs/figures/device_mesh_1d.png new file mode 100644 index 0000000..4b878d6 Binary files /dev/null and b/docs/figures/device_mesh_1d.png differ diff --git a/docs/figures/device_mesh_1d_zero.png b/docs/figures/device_mesh_1d_zero.png new file mode 100644 index 0000000..95789f9 Binary files /dev/null and b/docs/figures/device_mesh_1d_zero.png differ diff --git a/docs/figures/device_mesh_2d.png b/docs/figures/device_mesh_2d.png new file mode 100644 index 0000000..dbdfb7f Binary files /dev/null and b/docs/figures/device_mesh_2d.png differ diff --git a/docs/figures/device_mesh_2d_batch_partitioned.png b/docs/figures/device_mesh_2d_batch_partitioned.png new file mode 100644 index 0000000..657fd11 Binary files /dev/null and b/docs/figures/device_mesh_2d_batch_partitioned.png differ diff --git a/docs/figures/device_mesh_2d_data_replicated.png b/docs/figures/device_mesh_2d_data_replicated.png new file mode 100644 index 0000000..657fd11 Binary files /dev/null and b/docs/figures/device_mesh_2d_data_replicated.png differ diff --git a/docs/figures/device_mesh_2d_data_replicated_mlp_partitioned.png b/docs/figures/device_mesh_2d_data_replicated_mlp_partitioned.png new file mode 100644 index 0000000..3e636ef Binary files /dev/null and b/docs/figures/device_mesh_2d_data_replicated_mlp_partitioned.png differ diff --git a/docs/figures/device_mesh_2d_intermediate_fully_partitioned.png b/docs/figures/device_mesh_2d_intermediate_fully_partitioned.png new file mode 100644 index 0000000..d49cf51 Binary files /dev/null and b/docs/figures/device_mesh_2d_intermediate_fully_partitioned.png differ diff --git a/docs/figures/device_mesh_2d_zero.png b/docs/figures/device_mesh_2d_zero.png new file mode 100644 index 0000000..3b7912e Binary files /dev/null and b/docs/figures/device_mesh_2d_zero.png differ diff --git a/docs/hof.md b/docs/hof.md new file mode 100644 index 0000000..64b7656 --- /dev/null +++ b/docs/hof.md @@ -0,0 +1,16 @@ +# Higher-Order Functions + +JAX has a number of higher order functions (e.g. [jax.vmap][], [jax.lax.scan][]) that correspond to traditional +functional programming concepts. Haliax provides named versions of these functions that operate on named arrays/named +axes. + +## Vectorization + +::: haliax.vmap + + +## Looping and Scanning + +::: haliax.fold +::: haliax.scan +::: haliax.map diff --git a/docs/indexing.md b/docs/indexing.md index eab9df9..a32d620 100644 --- a/docs/indexing.md +++ b/docs/indexing.md @@ -1,7 +1,8 @@ -# Indexing in Haliax +# Indexing and Slicing -Haliax supports Numpy-style indexing, including advanced indexing, though the syntax is necessarily different. -Most forms of indexing are supporting, except we don't support indexing with booleans right now. (JAX doesn't support indexing with non-constant bool arrays anyway, +Haliax supports Numpy-style indexing, including so-called [Advanced Indexing](https://numpy.org/doc/stable/user/basics.indexing.html#advanced-indexing), +though the syntax is necessarily different. Most forms of indexing are supporting, except we don't support indexing with +booleans right now. (JAX doesn't support indexing with non-constant bool arrays anyway, so I don't think it's worth the effort to implement it in Haliax.) ## Basic Indexing @@ -36,6 +37,39 @@ Otherwise, the idea is pretty straightforward: any unspecified axes are treated slices are kept in reduced dimensions, and integers eliminate dimensions. If all dimensions are eliminated, a scalar JAX ndarray is returned. +## Dynamic Slices + +### Shapes in JAX + +Before we continue note on shapes in JAX. Most JAX code will be used inside `jit`, which means that the sizes of all arrays +must be determined at compile time (i.e. when JAX interprets your functions abstractly). This is a hard requirement in +XLA. + +A consequence of this restriction is that certain indexing patterns aren't allowed in `jit`-ed JAX code: + +```python +import jax.numpy as jnp +import jax + +@jax.jit +def f(x, slice_size: int): + num_blocks = x.shape[0] // slice_size + jax.lax.fori_loop(0, num_blocks, lambda i, x: x[i * slice_size : (i + 1) * slice_size], x) + + +f(jnp.arange(10), 2) +# IndexError: Array slice indices must have static start/stop/step to be used with NumPy indexing syntax. +# Found slice(Traced<ShapedArray(int32[], weak_type=True)>with<DynamicJaxprTrace(level=2/0)>, +# Traced<ShapedArray(int32[], weak_type=True)>with<DynamicJaxprTrace(level=2/0)>, None). To index a statically sized +# array at a dynamic position, try lax.dynamic_slice/dynamic_update_slice (JAX does not support dynamically sized +# arrays within JIT compiled functions). +``` + +This is a not-uncommon pattern in situations where you want to process a large array in chunks. In Haliax, we provide +two solutions: [haliax.slice][] + + + ## Advanced Indexing NumPy's [Advanced Indexing](https://numpy.org/doc/stable/user/basics.indexing.html#advanced-indexing) is supported, diff --git a/docs/nn.md b/docs/nn.md new file mode 100644 index 0000000..884536e --- /dev/null +++ b/docs/nn.md @@ -0,0 +1,73 @@ +# Neural Networks + +## Functions + +These functions wrap the equivalent in [jax.nn][]: + +::: haliax.nn.relu +::: haliax.nn.relu6 +::: haliax.nn.sigmoid +::: haliax.nn.softplus +::: haliax.nn.soft_sign +::: haliax.nn.silu +::: haliax.nn.swish +::: haliax.nn.log_sigmoid +::: haliax.nn.leaky_relu +::: haliax.nn.hard_sigmoid +::: haliax.nn.hard_silu +::: haliax.nn.hard_swish +::: haliax.nn.hard_tanh +::: haliax.nn.elu +::: haliax.nn.celu +::: haliax.nn.selu +::: haliax.nn.gelu +::: haliax.nn.quick_gelu +::: haliax.nn.glu +::: haliax.nn.logsumexp +::: haliax.nn.log_softmax +::: haliax.nn.softmax +::: haliax.nn.standardize +::: haliax.nn.one_hot + +### Loss Functions + +::: haliax.nn.cross_entropy_loss +::: haliax.nn.cross_entropy_loss_and_log_normalizers + + +## Modules + +Haliax provides a small number of neural network modules that are compatible with Equinox, though +they naturally all use [haliax.NamedArray][]. (We welcome PRs for more modules! Nothing too exotic though.) +The most interesting of these modules is [haliax.nn.Stacked][], which allows you to create homogenous "stacks" +of the same module (e.g. transformer blocks), which is a common pattern in deep learning. + +::: haliax.nn.Embedding +::: haliax.nn.Linear +::: haliax.nn.Dropout +::: haliax.nn.LayerNorm +::: haliax.nn.Stacked + +## Attention + +We don't provide an explicit attention module, but we do provide an attention function and several related functions: + +:::haliax.nn.attention.dot_product_attention +:::haliax.nn.attention.dot_product_attention_weights + +### Masks +::: haliax.nn.attention.causal_mask +::: haliax.nn.attention.prefix_lm_mask +::: haliax.nn.attention.combine_masks_and +::: haliax.nn.attention.combine_masks_or +::: haliax.nn.attention.forgetful_causal_mask + +### Biases + +::: haliax.nn.attention.mask_to_bias +::: haliax.nn.attention.alibi_attention_bias + + +## API Reference + +::: haliax.nn diff --git a/docs/partitioning.md b/docs/partitioning.md new file mode 100644 index 0000000..d0dae2f --- /dev/null +++ b/docs/partitioning.md @@ -0,0 +1,127 @@ +# Partitioning + +Partitioning refers to the process of splitting arrays and computation across multiple devices. Haliax provides a number +of functions for partitioning arrays and computation across multiple devices. + + +## Tutorial +An introduction to using Haliax's partitioning functions to scale a transformer can be found here: [Distributed Training in Haliax](https://colab.research.google.com/drive/1QX4yH3zRFF3Xiibf1aahETcSQ5nbcUMz). + +This page is designed to be more of a reference than a tutorial, and we assume you've read the tutorial before reading this page. + + +## Device Meshes in JAX + +See also JAX's tutorial [Distributed Arrays and Automatic Parallelization](https://jax.readthedocs.io/en/latest/notebooks/Distributed_arrays_and_automatic_parallelization.html) +for more details. + +One of the main ways JAX provides distributed parallelism is via the [jax.sharding.Mesh][]. +A mesh is a logical n-dimensional array of devices. Meshes in JAX are represented as a Numpy ndarray (note: not `jax.numpy`) +of devices and a tuple of axis names. For example, a 2D mesh of 16 devices might look like this: + +```python +import jax +import jax.numpy as jnp + +from jax.sharding import Mesh + +devices = jax.devices() +mesh = Mesh(jnp.array(devices).reshape((-1, 2)), ("data", "model")) +``` + +![2d Device Mesh showing 16 devices](figures/device_mesh_2d.png) + +The mesh above has two axes, `data` and `model`. In JAX's mesh parallelism, arrays are distributed by overlaying axes of +the array on top of the axes of the mesh. For example, if we have a batch of 32 sequences we might do something like this: + +```python +from jax.sharding import NamedSharding, PartitionSpec + +batch_size = 32 +seqlen = 512 + +batch = jnp.zeros((batch_size, seqlen), dtype=jnp.float32) +batch = jax.device_put(batch, NamedSharding(mesh, PartitionSpec("data", None))) +``` + +This specifies that the first axis of `batch` should be distributed across the `data` axis of the mesh. The `None` in the +`PartitionSpec` indicates that the second axis of `batch` is not distributed, which means that the data is replicated +so that one copy of the data is partitioned across each row of the mesh. + +![Device Mesh showing 16 devices with data partitioned across data axis](figures/device_mesh_2d_batch_partitioned.png) + +What's nice about this approach is that jax will automatically schedule computations so that operations are distributed +in the way you would expect: you don't have to explicitly manage communication between devices. + +However, JAX sometimes gets confused, and it's not sure how you want your arrays partitioned. In Jax, there's a function +called [jax.lax.with_sharding_constraint][] that lets you explicitly specify the sharding for the outputs of arrays. +You use this function only inside `jit`. + +## Haliax Partitioning in a nutshell + +As you might imagine, it gets tedious and error-prone to have to specify the partitioning of every array you create. Haliax provides +routines to handle mapping of [haliax.NamedArray][]s automatically. + +```python +import haliax as hax + +Batch = hax.Axis("batch", 32) +SeqLen = hax.Axis("seqlen", 512) + +axis_mapping = {"batch": "data", } + +batch = hax.zeros((Batch, SeqLen), dtype=jnp.float32) +batch = hax.shard_with_axis_mapping(batch, axis_mapping) + +# we also have "auto_sharded" and support context mappings for axis mappings: +with hax.axis_mapping({"batch": "data"}): + batch = hax.zeros((Batch, SeqLen), dtype=jnp.float32) + batch = hax.auto_sharded(batch) +``` + +Unlike in JAX, which has separate APIs for partitioning arrays inside and outside of `jit`, Haliax has a single API: +both `hax.shard_with_axis_mapping` and `hax.auto_sharded` work inside and outside of `jit`. Haliax automatically +chooses which JAX function to use based on context. + + +## Axis Mappings + +The core data structure we use to represent partitioning is the [haliax.partitioning.ResourceMapping][] which +is just an alias for a `Dict[str, str|Sequence[str]]`. The keys in this dictionary are the names of "logical" Axes in NamedArrays +and the values are the names of axes in the mesh. (In theory you can partition a single Axis across multiple axes in the mesh, +but we don't use this functionality.) + +::: haliax.partitioning.ResourceMapping + +A context manager can be used to specify an axis mapping for the current thread for the duration of the context: + +```python +with hax.axis_mapping({"batch": "data"}): + batch = hax.zeros((Batch, SeqLen), dtype=jnp.float32) + batch = hax.auto_sharded(batch) +``` + +::: haliax.partitioning.axis_mapping + +## Partitioning Functions + +### Sharding Arrays and PyTrees + +These functions are used to shard arrays and PyTrees of arrays, e.g. Modules. + +::: haliax.shard_with_axis_mapping +::: haliax.auto_sharded + +### `named_jit` and friends + +::: haliax.named_jit +::: haliax.fsdp + + +### Querying the Mesh and Axis Mapping + + +::: haliax.partitioning.round_axis_for_partitioning +::: haliax.partitioning.physical_axis_name +::: haliax.partitioning.physical_axis_size +::: haliax.partitioning.sharding_for_axis diff --git a/docs/requirements.txt b/docs/requirements.txt new file mode 100644 index 0000000..e8b195d --- /dev/null +++ b/docs/requirements.txt @@ -0,0 +1,9 @@ +mkdocs +mkdocstrings +mkdocstrings-python +mkdocs-material +mkdocs-material-extensions +mkdocs-autorefs +mkdocs-include-markdown-plugin +mkdocs-literate-nav +mkdocs-macros-plugin diff --git a/docs/tutorial.md b/docs/tutorial.md new file mode 100644 index 0000000..4ffe106 --- /dev/null +++ b/docs/tutorial.md @@ -0,0 +1,9 @@ +Haliax's tutorials are hosted on Google Colab. You can run the tutorials in your browser without installing anything. + +Here are our current tutorials: + +{% +include-markdown "../README.md" +start="<!--haliax-tutorials-start-->" +end="<!--haliax-tutorials-end-->" +%} diff --git a/mkdocs.yml b/mkdocs.yml index 175e269..b08e28f 100644 --- a/mkdocs.yml +++ b/mkdocs.yml @@ -6,48 +6,82 @@ theme: highlightjs: false features: - content.code.copy +markdown_extensions: +- attr_list +- admonition +#- callouts +- footnotes +- codehilite +- pymdownx.details # Allowing hidden expandable regions denoted by ??? +- pymdownx.magiclink +- pymdownx.superfences +- pymdownx.arithmatex: # Render LaTeX via MathJax + generic: true +- pymdownx.superfences # Seems to enable syntax highlighting when used with the Material theme. +- pymdownx.snippets: # Include one Markdown file into another + base_path: docs +- pymdownx.inlinehilite +- pymdownx.snippets: + check_paths: true +- pymdownx.superfences +- toc: + permalink: "¤" + toc_depth: "2-3" + plugins: - search + - autorefs - mkdocstrings: handlers: python: + setup_commands: + - import pytkdocs_tweaks + - pytkdocs_tweaks.main() + paths: [src] + import: + - https://docs.python.org/3/objects.inv + - https://jax.readthedocs.io/en/latest/objects.inv + - https://docs.kidger.site/equinox/objects.inv options: - show_root_heading: true - show_signature_annotations: true - show_bases: false - show_source: false - show_root_full_path: false - show_if_no_docstring: true - members_order: source - merge_init_into_class: true docstring_options: ignore_init_summary: true - + docstring_style: sphinx + show_source: false + docstring_section_style: list + heading_level: 5 + inherited_members: true + merge_init_into_class: true + load_external_modules: true + preload_modules: [haliax, haliax.core] +# separate_signature: true + show_root_heading: true + show_root_full_path: false +# show_signature_annotations: true + show_symbol_type_heading: false + show_symbol_type_toc: false + signature_crossrefs: true + line_length: 100 - include-markdown extra_css: - - docstrings.css -markdown_extensions: - - pymdownx.magiclink - - pymdownx.arithmatex: # Render LaTeX via MathJax - generic: true - - pymdownx.superfences # Seems to enable syntax highlighting when used with the Material theme. - - pymdownx.details # Allowing hidden expandable regions denoted by ??? - - pymdownx.snippets: # Include one Markdown file into another - base_path: docs - - pymdownx.highlight: - anchor_linenums: true - line_spans: __span - pygments_lang_class: true - - pymdownx.inlinehilite - - pymdownx.snippets - - pymdownx.superfences - - admonition - - toc: - permalink: "¤" # Adds a clickable permalink to each section heading - toc_depth: 4 + - css/material.css + - css/mkdocstrings.css + + watch: - src - docs nav: - - 'Home': 'index.md' - - Indexing and Slicing: 'indexing.md' + - Home: 'index.md' + - Tutorials: + - "Introduction to Haliax": https://colab.research.google.com/drive/1TiTcQQ4V5mopbgCu1SVl-oqJtXn7rFnC + - "Distributed Training and FSDP": https://colab.research.google.com/drive/1QX4yH3zRFF3Xiibf1aahETcSQ5nbcUMz + - "Tensor Parallelism": https://colab.research.google.com/drive/18_BrtDpe1lu89M4T6fKzda8DdSLtFJhi + - "Mixed Precision with `jmp`": https://colab.research.google.com/drive/1_4cikwt-UhSH7yRzNRK8ze9msM9r2mEl?usp=sharing + - Cheatsheet: 'cheatsheet.md' + - Named Arrays: + - Broadcasting: 'broadcasting.md' + - Indexing and Slicing: 'indexing.md' + - Neural Networks: 'nn.md' + - Partitioning: 'partitioning.md' + - Higher Order Functions: 'hof.md' + - API Reference: 'api.md' diff --git a/src/haliax/__init__.py b/src/haliax/__init__.py index a4e3ef7..76f5171 100644 --- a/src/haliax/__init__.py +++ b/src/haliax/__init__.py @@ -1,7 +1,9 @@ +import typing from typing import Optional, Sequence import jax import jax.numpy as jnp +from jax._src.typing import DTypeLike import haliax.nn as nn import haliax.random as random @@ -10,6 +12,7 @@ import haliax.tree_util as tree_util from .axis import Axis, AxisSelection, AxisSelector, AxisSpec, concat_axes, eliminate_axes, selects_axis from .core import ( NamedArray, + NamedOrNumeric, are_shape_checks_enabled, broadcast_arrays, broadcast_axis, @@ -32,6 +35,7 @@ from .core import ( from .hof import fold, map, scan, vmap from .ops import clip, isclose, pad_left, trace, tril, triu, where from .partitioning import auto_sharded, axis_mapping, fsdp, named_jit, shard_with_axis_mapping +from .types import Scalar from .wrap import ( ReductionFunction, SimpleReductionFunction, @@ -42,22 +46,26 @@ from .wrap import ( ) +T = typing.TypeVar("T") +A = typing.TypeVar("A", Scalar, NamedArray, jnp.ndarray) + + # creation routines -def zeros(shape: AxisSpec, dtype=None) -> NamedArray: +def zeros(shape: AxisSpec, dtype: Optional[DTypeLike] = None) -> NamedArray: """Creates a NamedArray with all elements set to 0""" if dtype is None: dtype = jnp.float32 return full(shape, 0, dtype) -def ones(shape: AxisSpec, dtype=None) -> NamedArray: +def ones(shape: AxisSpec, dtype: Optional[DTypeLike] = None) -> NamedArray: """Creates a NamedArray with all elements set to 1""" if dtype is None: dtype = jnp.float32 return full(shape, 1, dtype) -def full(shape: AxisSpec, fill_value, dtype=None) -> NamedArray: +def full(shape: AxisSpec, fill_value: T, dtype: Optional[DTypeLike] = None) -> NamedArray: """Creates a NamedArray with all elements set to `fill_value`""" if isinstance(shape, Axis): return NamedArray(jnp.full(shape=shape.size, fill_value=fill_value, dtype=dtype), (shape,)) @@ -76,12 +84,12 @@ def ones_like(a: NamedArray, dtype=None) -> NamedArray: return NamedArray(jnp.ones_like(a.array, dtype=dtype), a.axes) -def full_like(a: NamedArray, fill_value, dtype=None) -> NamedArray: +def full_like(a: NamedArray, fill_value: T, dtype: Optional[DTypeLike] = None) -> NamedArray: """Creates a NamedArray with all elements set to `fill_value`""" return NamedArray(jnp.full_like(a.array, fill_value, dtype=dtype), a.axes) -def arange(axis: Axis, *, start=0, step=1, dtype=None) -> NamedArray: +def arange(axis: Axis, *, start: int = 0, step: int = 1, dtype: Optional[DTypeLike] = None) -> NamedArray: """Version of jnp.arange that returns a NamedArray""" # if start is a tracer, we need to be a bit cleverer since arange doesn't support tracers # return NamedArray(jnp.arange(start, stop, step, dtype=dtype), (axis,)) @@ -90,8 +98,51 @@ def arange(axis: Axis, *, start=0, step=1, dtype=None) -> NamedArray: return NamedArray(arr, (axis,)) +# TODO: add overrides for arraylike start/stop to linspace, logspace, geomspace +def linspace( + axis: AxisSelector, *, start: float, stop: float, endpoint: bool = True, dtype: Optional[DTypeLike] = None +) -> NamedArray: + """ + Version of jnp.linspace that returns a NamedArray. + If `axis` is a string, the default number of samples (50, per numpy) will be used. + """ + if isinstance(axis, str): + axis = Axis(axis, 50) + return NamedArray(jnp.linspace(start, stop, axis.size, endpoint=endpoint, dtype=dtype), (axis,)) + + +def logspace( + axis: AxisSelector, + *, + start: float, + stop: float, + endpoint: bool = True, + base: float = 10.0, + dtype: Optional[DTypeLike] = None, +) -> NamedArray: + """ + Version of jnp.logspace that returns a NamedArray. + If `axis` is a string, the default number of samples (50, per numpy) will be used. + """ + if isinstance(axis, str): + axis = Axis(axis, 50) + return NamedArray(jnp.logspace(start, stop, axis.size, endpoint=endpoint, base=base, dtype=dtype), (axis,)) + + +def geomspace( + axis: AxisSelector, *, start: float, stop: float, endpoint: bool = True, dtype: Optional[DTypeLike] = None +) -> NamedArray: + """ + Version of jnp.geomspace that returns a NamedArray. + If `axis` is a string, the default number of samples (50, per numpy) will be used. + """ + if isinstance(axis, str): + axis = Axis(axis, 50) + return NamedArray(jnp.geomspace(start, stop, axis.size, endpoint=endpoint, dtype=dtype), (axis,)) + + def stack(axis: AxisSelector, arrays: Sequence[NamedArray]) -> NamedArray: - """Version of jnp.stack that returns a NamedArray""" + """Version of [jax.numpy.stack][] that returns a NamedArray""" if isinstance(axis, str): axis = Axis(axis, len(arrays)) if len(arrays) == 0: @@ -101,8 +152,10 @@ def stack(axis: AxisSelector, arrays: Sequence[NamedArray]) -> NamedArray: def concatenate(axis: AxisSelector, arrays: Sequence[NamedArray]) -> NamedArray: - """Version of jnp.concatenate that returns a NamedArray""" - total_size = _sum(a.resolve_axis(axis).size for a in arrays) + """Version of [jax.numpy.concatenate][] that returns a NamedArray. The returns array will have the same axis names in the + same order as the first, with the selected axis extended by the sum of the sizes of the selected axes in the + concatenated arrays.""" + total_size: int = _sum(a.resolve_axis(axis).size for a in arrays) # type: ignore if isinstance(axis, str): axis = Axis(axis, total_size) elif total_size != axis.size: @@ -124,131 +177,627 @@ def concatenate(axis: AxisSelector, arrays: Sequence[NamedArray]) -> NamedArray: # elementwise unary operations -abs = wrap_elemwise_unary(jnp.abs) -absolute = wrap_elemwise_unary(jnp.absolute) -angle = wrap_elemwise_unary(jnp.angle) -arccos = wrap_elemwise_unary(jnp.arccos) -arccosh = wrap_elemwise_unary(jnp.arccosh) -arcsin = wrap_elemwise_unary(jnp.arcsin) -arcsinh = wrap_elemwise_unary(jnp.arcsinh) -arctan = wrap_elemwise_unary(jnp.arctan) -arctanh = wrap_elemwise_unary(jnp.arctanh) -around = wrap_elemwise_unary(jnp.around) -bitwise_not = wrap_elemwise_unary(jnp.bitwise_not) -cbrt = wrap_elemwise_unary(jnp.cbrt) -ceil = wrap_elemwise_unary(jnp.ceil) -conj = wrap_elemwise_unary(jnp.conj) -conjugate = wrap_elemwise_unary(jnp.conjugate) -copy = wrap_elemwise_unary(jnp.copy) -cos = wrap_elemwise_unary(jnp.cos) -cosh = wrap_elemwise_unary(jnp.cosh) -deg2rad = wrap_elemwise_unary(jnp.deg2rad) -degrees = wrap_elemwise_unary(jnp.degrees) -exp = wrap_elemwise_unary(jnp.exp) -exp2 = wrap_elemwise_unary(jnp.exp2) -expm1 = wrap_elemwise_unary(jnp.expm1) -fabs = wrap_elemwise_unary(jnp.fabs) -fix = wrap_elemwise_unary(jnp.fix) -floor = wrap_elemwise_unary(jnp.floor) -frexp = wrap_elemwise_unary(jnp.frexp) -i0 = wrap_elemwise_unary(jnp.i0) -imag = wrap_elemwise_unary(jnp.imag) -invert = wrap_elemwise_unary(jnp.invert) -iscomplex = wrap_elemwise_unary(jnp.iscomplex) -isfinite = wrap_elemwise_unary(jnp.isfinite) -isinf = wrap_elemwise_unary(jnp.isinf) -isnan = wrap_elemwise_unary(jnp.isnan) -isneginf = wrap_elemwise_unary(jnp.isneginf) -isposinf = wrap_elemwise_unary(jnp.isposinf) -isreal = wrap_elemwise_unary(jnp.isreal) -log = wrap_elemwise_unary(jnp.log) -log10 = wrap_elemwise_unary(jnp.log10) -log1p = wrap_elemwise_unary(jnp.log1p) -log2 = wrap_elemwise_unary(jnp.log2) -logical_not = wrap_elemwise_unary(jnp.logical_not) -ndim = wrap_elemwise_unary(jnp.ndim) -negative = wrap_elemwise_unary(jnp.negative) -positive = wrap_elemwise_unary(jnp.positive) -rad2deg = wrap_elemwise_unary(jnp.rad2deg) -radians = wrap_elemwise_unary(jnp.radians) -real = wrap_elemwise_unary(jnp.real) -reciprocal = wrap_elemwise_unary(jnp.reciprocal) -rint = wrap_elemwise_unary(jnp.rint) -round = wrap_elemwise_unary(jnp.round) -rsqrt = wrap_elemwise_unary(jax.lax.rsqrt) # nb this is in lax -sign = wrap_elemwise_unary(jnp.sign) -signbit = wrap_elemwise_unary(jnp.signbit) -sin = wrap_elemwise_unary(jnp.sin) -sinc = wrap_elemwise_unary(jnp.sinc) -sinh = wrap_elemwise_unary(jnp.sinh) -square = wrap_elemwise_unary(jnp.square) -sqrt = wrap_elemwise_unary(jnp.sqrt) -tan = wrap_elemwise_unary(jnp.tan) -tanh = wrap_elemwise_unary(jnp.tanh) -trunc = wrap_elemwise_unary(jnp.trunc) +def abs(a: A) -> A: + return wrap_elemwise_unary(jnp.abs, a) + + +def absolute(a: A) -> A: + return wrap_elemwise_unary(jnp.absolute, a) + + +def angle(a: A) -> A: + return wrap_elemwise_unary(jnp.angle, a) + + +def arccos(a: A) -> A: + return wrap_elemwise_unary(jnp.arccos, a) + + +def arccosh(a: A) -> A: + return wrap_elemwise_unary(jnp.arccosh, a) + + +def arcsin(a: A) -> A: + return wrap_elemwise_unary(jnp.arcsin, a) + + +def arcsinh(a: A) -> A: + return wrap_elemwise_unary(jnp.arcsinh, a) + + +def arctan(a: A) -> A: + return wrap_elemwise_unary(jnp.arctan, a) + + +def arctanh(a: A) -> A: + return wrap_elemwise_unary(jnp.arctanh, a) + + +def around(a: A) -> A: + return wrap_elemwise_unary(jnp.around, a) + + +def bitwise_not(a: A) -> A: + return wrap_elemwise_unary(jnp.bitwise_not, a) + + +def cbrt(a: A) -> A: + return wrap_elemwise_unary(jnp.cbrt, a) + + +def ceil(a: A) -> A: + return wrap_elemwise_unary(jnp.ceil, a) + + +def conj(a: A) -> A: + return wrap_elemwise_unary(jnp.conj, a) + + +def conjugate(a: A) -> A: + return wrap_elemwise_unary(jnp.conjugate, a) + + +def copy(a: A) -> A: + return wrap_elemwise_unary(jnp.copy, a) + + +def cos(a: A) -> A: + return wrap_elemwise_unary(jnp.cos, a) + + +def cosh(a: A) -> A: + return wrap_elemwise_unary(jnp.cosh, a) + + +def deg2rad(a: A) -> A: + return wrap_elemwise_unary(jnp.deg2rad, a) + + +def degrees(a: A) -> A: + return wrap_elemwise_unary(jnp.degrees, a) + + +def exp(a: A) -> A: + return wrap_elemwise_unary(jnp.exp, a) + + +def exp2(a: A) -> A: + return wrap_elemwise_unary(jnp.exp2, a) + + +def expm1(a: A) -> A: + return wrap_elemwise_unary(jnp.expm1, a) + + +def fabs(a: A) -> A: + return wrap_elemwise_unary(jnp.fabs, a) + + +def fix(a: A) -> A: + return wrap_elemwise_unary(jnp.fix, a) + + +def floor(a: A) -> A: + return wrap_elemwise_unary(jnp.floor, a) + + +def frexp(a: A) -> A: + return wrap_elemwise_unary(jnp.frexp, a) + + +def i0(a: A) -> A: + return wrap_elemwise_unary(jnp.i0, a) + + +def imag(a: A) -> A: + return wrap_elemwise_unary(jnp.imag, a) + + +def invert(a: A) -> A: + return wrap_elemwise_unary(jnp.invert, a) + + +def iscomplex(a: A) -> A: + return wrap_elemwise_unary(jnp.iscomplex, a) + + +def isfinite(a: A) -> A: + return wrap_elemwise_unary(jnp.isfinite, a) + + +def isinf(a: A) -> A: + return wrap_elemwise_unary(jnp.isinf, a) + + +def isnan(a: A) -> A: + return wrap_elemwise_unary(jnp.isnan, a) + + +def isneginf(a: A) -> A: + return wrap_elemwise_unary(jnp.isneginf, a) + + +def isposinf(a: A) -> A: + return wrap_elemwise_unary(jnp.isposinf, a) + + +def isreal(a: A) -> A: + return wrap_elemwise_unary(jnp.isreal, a) + + +def log(a: A) -> A: + return wrap_elemwise_unary(jnp.log, a) + + +def log10(a: A) -> A: + return wrap_elemwise_unary(jnp.log10, a) + + +def log1p(a: A) -> A: + return wrap_elemwise_unary(jnp.log1p, a) + + +def log2(a: A) -> A: + return wrap_elemwise_unary(jnp.log2, a) + + +def logical_not(a: A) -> A: + return wrap_elemwise_unary(jnp.logical_not, a) + + +def ndim(a: A) -> A: + return wrap_elemwise_unary(jnp.ndim, a) + + +def negative(a: A) -> A: + return wrap_elemwise_unary(jnp.negative, a) + + +def positive(a: A) -> A: + return wrap_elemwise_unary(jnp.positive, a) + + +def rad2deg(a: A) -> A: + return wrap_elemwise_unary(jnp.rad2deg, a) + + +def radians(a: A) -> A: + return wrap_elemwise_unary(jnp.radians, a) + + +def real(a: A) -> A: + return wrap_elemwise_unary(jnp.real, a) + + +def reciprocal(a: A) -> A: + return wrap_elemwise_unary(jnp.reciprocal, a) + + +def rint(a: A) -> A: + return wrap_elemwise_unary(jnp.rint, a) + + +def round(a: A, decimals: int = 0) -> A: + return wrap_elemwise_unary(jnp.round, a, decimals=decimals) + + +def rsqrt(a: A) -> A: + return wrap_elemwise_unary(jax.lax.rsqrt, a) # nb this is in lax + + +def sign(a: A) -> A: + return wrap_elemwise_unary(jnp.sign, a) + + +def signbit(a: A) -> A: + return wrap_elemwise_unary(jnp.signbit, a) + + +def sin(a: A) -> A: + return wrap_elemwise_unary(jnp.sin, a) + + +def sinc(a: A) -> A: + return wrap_elemwise_unary(jnp.sinc, a) + + +def sinh(a: A) -> A: + return wrap_elemwise_unary(jnp.sinh, a) + + +def square(a: A) -> A: + return wrap_elemwise_unary(jnp.square, a) + + +def sqrt(a: A) -> A: + return wrap_elemwise_unary(jnp.sqrt, a) + + +def tan(a: A) -> A: + return wrap_elemwise_unary(jnp.tan, a) + + +def tanh(a: A) -> A: + return wrap_elemwise_unary(jnp.tanh, a) + + +def trunc(a: A) -> A: + return wrap_elemwise_unary(jnp.trunc, a) + # Reduction functions -all: ReductionFunction = wrap_reduction_call(jnp.all) -amax: ReductionFunction = wrap_reduction_call(jnp.amax) -any: ReductionFunction = wrap_reduction_call(jnp.any) -argmax: SimpleReductionFunction = wrap_reduction_call(jnp.argmax, single_axis_only=True, supports_where=False) -argmin: SimpleReductionFunction = wrap_reduction_call(jnp.argmin, single_axis_only=True, supports_where=False) -max: ReductionFunction = wrap_reduction_call(jnp.max) -mean: ReductionFunction = wrap_reduction_call(jnp.mean) -min: ReductionFunction = wrap_reduction_call(jnp.min) -prod: ReductionFunction = wrap_reduction_call(jnp.prod) -ptp: ReductionFunction = wrap_reduction_call(jnp.ptp) -product: ReductionFunction = wrap_reduction_call(jnp.product) -sometrue: ReductionFunction = wrap_reduction_call(jnp.sometrue) -std: ReductionFunction = wrap_reduction_call(jnp.std) +def all(array: NamedArray, axis: Optional[AxisSelection] = None, *, where: Optional[NamedArray] = None) -> NamedArray: + """ + Named version of [jax.numpy.all](https://jax.readthedocs.io/en/latest/_autosummary/jax.numpy.all.html#jax.numpy.all). + """ + return wrap_reduction_call(jnp.all, array, axis, where, single_axis_only=False, supports_where=True) + + +def amax(array: NamedArray, axis: Optional[AxisSelection] = None, *, where: Optional[NamedArray] = None) -> NamedArray: + """ + Aliax for max. See max for details. + """ + return wrap_reduction_call(jnp.amax, array, axis, where, single_axis_only=False, supports_where=True) + + +def any(array: NamedArray, axis: Optional[AxisSelection] = None, *, where: Optional[NamedArray] = None) -> NamedArray: + """True if any elements along a given axis or axes are True. If axis is None, any elements are True.""" + return wrap_reduction_call(jnp.any, array, axis, where, single_axis_only=False, supports_where=True) + + +def argmax(array: NamedArray, axis: Optional[AxisSelector] = None) -> NamedArray: + return wrap_reduction_call(jnp.argmax, array, axis, None, single_axis_only=True, supports_where=False) + + +def argmin(array: NamedArray, axis: Optional[AxisSelector] = None) -> NamedArray: + return wrap_reduction_call(jnp.argmin, array, axis, None, single_axis_only=True, supports_where=False) + + +def max(array: NamedArray, axis: Optional[AxisSelection] = None, *, where: Optional[NamedArray] = None) -> NamedArray: + return wrap_reduction_call(jnp.max, array, axis, where, single_axis_only=False, supports_where=True) + + +def mean( + array: NamedArray, + axis: Optional[AxisSelection] = None, + *, + where: Optional[NamedArray] = None, + dtype: Optional[DTypeLike] = None, +) -> NamedArray: + return wrap_reduction_call(jnp.mean, array, axis, where, single_axis_only=False, supports_where=True, dtype=dtype) + + +def min(array: NamedArray, axis: Optional[AxisSelection] = None, *, where: Optional[NamedArray] = None) -> NamedArray: + return wrap_reduction_call(jnp.min, array, axis, where, single_axis_only=False, supports_where=True) + + +def prod( + array: NamedArray, + axis: Optional[AxisSelection] = None, + *, + where: Optional[NamedArray] = None, + dtype: Optional[DTypeLike] = None, +) -> NamedArray: + return wrap_reduction_call(jnp.prod, array, axis, where, single_axis_only=False, supports_where=True, dtype=dtype) + + +def ptp(array: NamedArray, axis: Optional[AxisSelection] = None, *, where: Optional[NamedArray] = None) -> NamedArray: + return wrap_reduction_call(jnp.ptp, array, axis, where, single_axis_only=False, supports_where=True) + + +def product( + array: NamedArray, axis: Optional[AxisSelection] = None, *, where: Optional[NamedArray] = None +) -> NamedArray: + return wrap_reduction_call(jnp.product, array, axis, where, single_axis_only=False, supports_where=True) + + +def std( + array: NamedArray, + axis: Optional[AxisSelection] = None, + *, + where: Optional[NamedArray] = None, + ddof: int = 0, + dtype: Optional[DTypeLike] = None, +) -> NamedArray: + return wrap_reduction_call( + jnp.std, array, axis, where, single_axis_only=False, supports_where=True, dtype=dtype, ddof=ddof + ) + + _sum = sum -sum: ReductionFunction = wrap_reduction_call(jnp.sum) -var: ReductionFunction = wrap_reduction_call(jnp.var) + + +def sum( + array: NamedArray, + axis: Optional[AxisSelection] = None, + *, + where: Optional[NamedArray] = None, + dtype: Optional[DTypeLike] = None, +) -> NamedArray: + return wrap_reduction_call(jnp.sum, array, axis, where, single_axis_only=False, supports_where=True, dtype=dtype) + + +def var( + array: NamedArray, + axis: Optional[AxisSelection] = None, + *, + where: Optional[NamedArray] = None, + ddof: int = 0, + dtype: Optional[DTypeLike] = None, +) -> NamedArray: + return wrap_reduction_call( + jnp.var, array, axis, where, single_axis_only=False, supports_where=True, dtype=dtype, ddof=ddof + ) # "Normalization" functions that use an axis but don't change the shape -cumsum = wrap_axiswise_call(jnp.cumsum, True) -cumprod = wrap_axiswise_call(jnp.cumprod, True) -cumproduct = wrap_axiswise_call(jnp.cumproduct, True) -sort = wrap_axiswise_call(jnp.sort, True) -argsort = wrap_axiswise_call(jnp.argsort, True) + + +def cumsum(a: NamedArray, axis: Optional[AxisSelector] = None, dtype: Optional[DTypeLike] = None) -> NamedArray: + """ + Named version of [jax.numpy.cumsum](https://jax.readthedocs.io/en/latest/_autosummary/jax.numpy.cumsum.html) + """ + return wrap_axiswise_call(jnp.cumsum, a, axis, dtype=dtype, single_axis_only=True) + + +def cumprod(a: NamedArray, axis: Optional[AxisSelector] = None, dtype: Optional[DTypeLike] = None) -> NamedArray: + """ + Named version of [jax.numpy.cumprod](https://jax.readthedocs.io/en/latest/_autosummary/jax.numpy.cumprod.html) + """ + return wrap_axiswise_call(jnp.cumprod, a, axis, dtype=dtype, single_axis_only=True) + + +def sort(a: NamedArray, axis: Optional[AxisSelector] = None) -> NamedArray: + """ + Named version of [jax.numpy.sort](https://jax.readthedocs.io/en/latest/_autosummary/jax.numpy.sort.html) + """ + return wrap_axiswise_call(jnp.sort, a, axis, single_axis_only=True) + + +def argsort(a: NamedArray, axis: Optional[AxisSelector] = None) -> NamedArray: + """ + Named version of [jax.numpy.argsort](https://jax.readthedocs.io/en/latest/_autosummary/jax.numpy.argsort.html) + """ + return wrap_axiswise_call(jnp.argsort, a, axis, single_axis_only=True) + # elemwise binary ops -add = wrap_elemwise_binary(jnp.add) -arctan2 = wrap_elemwise_binary(jnp.arctan2) -bitwise_and = wrap_elemwise_binary(jnp.bitwise_and) -bitwise_or = wrap_elemwise_binary(jnp.bitwise_or) -bitwise_xor = wrap_elemwise_binary(jnp.bitwise_xor) -divide = wrap_elemwise_binary(jnp.divide) -divmod = wrap_elemwise_binary(jnp.divmod) -equal = wrap_elemwise_binary(jnp.equal) -float_power = wrap_elemwise_binary(jnp.float_power) -floor_divide = wrap_elemwise_binary(jnp.floor_divide) -fmax = wrap_elemwise_binary(jnp.fmax) -fmin = wrap_elemwise_binary(jnp.fmin) -fmod = wrap_elemwise_binary(jnp.fmod) -greater = wrap_elemwise_binary(jnp.greater) -greater_equal = wrap_elemwise_binary(jnp.greater_equal) -hypot = wrap_elemwise_binary(jnp.hypot) -left_shift = wrap_elemwise_binary(jnp.left_shift) -less = wrap_elemwise_binary(jnp.less) -less_equal = wrap_elemwise_binary(jnp.less_equal) -logaddexp = wrap_elemwise_binary(jnp.logaddexp) -logaddexp2 = wrap_elemwise_binary(jnp.logaddexp2) -logical_and = wrap_elemwise_binary(jnp.logical_and) -logical_or = wrap_elemwise_binary(jnp.logical_or) -logical_xor = wrap_elemwise_binary(jnp.logical_xor) -maximum = wrap_elemwise_binary(jnp.maximum) -minimum = wrap_elemwise_binary(jnp.minimum) -mod = wrap_elemwise_binary(jnp.mod) -multiply = wrap_elemwise_binary(jnp.multiply) -nextafter = wrap_elemwise_binary(jnp.nextafter) -not_equal = wrap_elemwise_binary(jnp.not_equal) -power = wrap_elemwise_binary(jnp.power) -remainder = wrap_elemwise_binary(jnp.remainder) -right_shift = wrap_elemwise_binary(jnp.right_shift) -subtract = wrap_elemwise_binary(jnp.subtract) -true_divide = wrap_elemwise_binary(jnp.true_divide) + +# Note that all the heavy lifting is done by the `wrap_elemwise_binary` decorator +@wrap_elemwise_binary +def add(x1: NamedOrNumeric, x2: NamedOrNumeric, /) -> NamedOrNumeric: + """ + Named version of [jax.numpy.add](https://jax.readthedocs.io/en/latest/_autosummary/jax.numpy.add.html) + """ + return jnp.add(x1, x2) # type: ignore + + +@wrap_elemwise_binary +def arctan2(x1: NamedOrNumeric, x2: NamedOrNumeric, /) -> NamedOrNumeric: + """ + Named version of [jax.numpy.arctan2](https://jax.readthedocs.io/en/latest/_autosummary/jax.numpy.arctan2.html) + """ + return jnp.arctan2(x1, x2) # type: ignore + + +@wrap_elemwise_binary +def bitwise_and(x1: NamedOrNumeric, x2: NamedOrNumeric, /) -> NamedOrNumeric: + """ + Named version of [jax.numpy.bitwise_and](https://jax.readthedocs.io/en/latest/_autosummary/jax.numpy.bitwise_and.html) + """ + return jnp.bitwise_and(x1, x2) # type: ignore + + +@wrap_elemwise_binary +def bitwise_or(x1: NamedOrNumeric, x2: NamedOrNumeric, /) -> NamedOrNumeric: + """ + Named version of [jax.numpy.bitwise_or](https://jax.readthedocs.io/en/latest/_autosummary/jax.numpy.bitwise_or.html) + """ + return jnp.bitwise_or(x1, x2) # type: ignore + + +@wrap_elemwise_binary +def bitwise_xor(x1: NamedOrNumeric, x2: NamedOrNumeric, /) -> NamedOrNumeric: + """ + Named version of [jax.numpy.bitwise_xor](https://jax.readthedocs.io/en/latest/_autosummary/jax.numpy.bitwise_xor.html) + """ + return jnp.bitwise_xor(x1, x2) # type: ignore + + +@wrap_elemwise_binary +def divide(x1: NamedOrNumeric, x2: NamedOrNumeric, /) -> NamedOrNumeric: + """ + Named version of [jax.numpy.divide](https://jax.readthedocs.io/en/latest/_autosummary/jax.numpy.divide.html) + """ + return jnp.divide(x1, x2) # type: ignore + + +@wrap_elemwise_binary +def divmod(x1: NamedOrNumeric, x2: NamedOrNumeric, /) -> NamedOrNumeric: + """ + Named version of [jax.numpy.divmod](https://jax.readthedocs.io/en/latest/_autosummary/jax.numpy.divmod.html) + """ + return jnp.divmod(x1, x2) # type: ignore + + +@wrap_elemwise_binary +def equal(x1: NamedOrNumeric, x2: NamedOrNumeric, /) -> NamedOrNumeric: + """ + Named version of [jax.numpy.equal](https://jax.readthedocs.io/en/latest/_autosummary/jax.numpy.equal.html) + """ + return jnp.equal(x1, x2) # type: ignore + + +@wrap_elemwise_binary +def float_power(x1: NamedOrNumeric, x2: NamedOrNumeric, /) -> NamedOrNumeric: + """ + Named version of [jax.numpy.float_power](https://jax.readthedocs.io/en/latest/_autosummary/jax.numpy.float_power.html) + """ + return jnp.float_power(x1, x2) # type: ignore + + +@wrap_elemwise_binary +def floor_divide(x1: NamedOrNumeric, x2: NamedOrNumeric, /) -> NamedOrNumeric: + """ + Named version of [jax.numpy.floor_divide](https://jax.readthedocs.io/en/latest/_autosummary/jax.numpy.floor_divide.html) + """ + return jnp.floor_divide(x1, x2) # type: ignore + + +@wrap_elemwise_binary +def fmax(x1: NamedOrNumeric, x2: NamedOrNumeric, /) -> NamedOrNumeric: + """ + Named version of [jax.numpy.fmax](https://jax.readthedocs.io/en/latest/_autosummary/jax.numpy.fmax.html) + """ + return jnp.fmax(x1, x2) # type: ignore + + +@wrap_elemwise_binary +def fmin(x1: NamedOrNumeric, x2: NamedOrNumeric, /) -> NamedOrNumeric: + """ + Named version of [jax.numpy.fmin](https://jax.readthedocs.io/en/latest/_autosummary/jax.numpy.fmin.html) + """ + return jnp.fmin(x1, x2) # type: ignore + + +@wrap_elemwise_binary +def fmod(x1: NamedOrNumeric, x2: NamedOrNumeric, /) -> NamedOrNumeric: + """ + Named version of [jax.numpy.fmod](https://jax.readthedocs.io/en/latest/_autosummary/jax.numpy.fmod.html) + """ + return jnp.fmod(x1, x2) # type: ignore + + +@wrap_elemwise_binary +def greater(x1: NamedOrNumeric, x2: NamedOrNumeric, /) -> NamedOrNumeric: + """ + Named version of [jax.numpy.greater](https://jax.readthedocs.io/en/latest/_autosummary/jax.numpy.greater.html) + """ + return jnp.greater(x1, x2) # type: ignore + + +@wrap_elemwise_binary +def greater_equal(x1: NamedOrNumeric, x2: NamedOrNumeric, /) -> NamedOrNumeric: + """ + Named version of [jax.numpy.greater_equal](https://jax.readthedocs.io/en/latest/_autosummary/jax.numpy.greater_equal.html) + """ + return jnp.greater_equal(x1, x2) # type: ignore + + +@wrap_elemwise_binary +def hypot(x1: NamedOrNumeric, x2: NamedOrNumeric, /) -> NamedOrNumeric: + """ + Named version of [jax.numpy.hypot](https://jax.readthedocs.io/en/latest/_autosummary/jax.numpy.hypot.html) + """ + return jnp.hypot(x1, x2) # type: ignore + + +@wrap_elemwise_binary +def left_shift(x1: NamedOrNumeric, x2: NamedOrNumeric, /) -> NamedOrNumeric: + """ + Named version of [jax.numpy.left_shift](https://jax.readthedocs.io/en/latest/_autosummary/jax.numpy.left_shift.html) + """ + return jnp.left_shift(x1, x2) # type: ignore + + +@wrap_elemwise_binary +def less(x1: NamedOrNumeric, x2: NamedOrNumeric, /) -> NamedOrNumeric: + """ + Named version of [jax.numpy.less](https://jax.readthedocs.io/en/latest/_autosummary/jax.numpy.less.html) + """ + return jnp.less(x1, x2) # type: ignore + + +@wrap_elemwise_binary +def less_equal(x1: NamedOrNumeric, x2: NamedOrNumeric, /) -> NamedOrNumeric: + """ + Named version of [jax.numpy.less_equal](https://jax.readthedocs.io/en/latest/_autosummary/jax.numpy.less_equal.html) + """ + return jnp.less_equal(x1, x2) # type: ignore + + +@wrap_elemwise_binary +def logaddexp(x1: NamedOrNumeric, x2: NamedOrNumeric, /) -> NamedOrNumeric: + """ + Named version of [jax.numpy.logaddexp](https://jax.readthedocs.io/en/latest/_autosummary/jax.numpy.logaddexp.html) + """ + return jnp.logaddexp(x1, x2) # type: ignore + + +@wrap_elemwise_binary +def logaddexp2(x1: NamedOrNumeric, x2: NamedOrNumeric, /) -> NamedOrNumeric: + return jnp.logaddexp2(x1, x2) # type: ignore + + +@wrap_elemwise_binary +def logical_and(x1: NamedOrNumeric, x2: NamedOrNumeric, /) -> NamedOrNumeric: + return jnp.logical_and(x1, x2) # type: ignore + + +@wrap_elemwise_binary +def logical_or(x1: NamedOrNumeric, x2: NamedOrNumeric, /) -> NamedOrNumeric: + return jnp.logical_or(x1, x2) # type: ignore + + +@wrap_elemwise_binary +def logical_xor(x1: NamedOrNumeric, x2: NamedOrNumeric, /) -> NamedOrNumeric: + return jnp.logical_xor(x1, x2) # type: ignore + + +@wrap_elemwise_binary +def maximum(x1: NamedOrNumeric, x2: NamedOrNumeric, /) -> NamedOrNumeric: + return jnp.maximum(x1, x2) # type: ignore + + +@wrap_elemwise_binary +def minimum(x1: NamedOrNumeric, x2: NamedOrNumeric, /) -> NamedOrNumeric: + return jnp.minimum(x1, x2) # type: ignore + + +@wrap_elemwise_binary +def mod(x1: NamedOrNumeric, x2: NamedOrNumeric, /) -> NamedOrNumeric: + return jnp.mod(x1, x2) # type: ignore + + +@wrap_elemwise_binary +def multiply(x1: NamedOrNumeric, x2: NamedOrNumeric, /) -> NamedOrNumeric: + return jnp.multiply(x1, x2) # type: ignore + + +@wrap_elemwise_binary +def nextafter(x1: NamedOrNumeric, x2: NamedOrNumeric, /) -> NamedOrNumeric: + return jnp.nextafter(x1, x2) # type: ignore + + +@wrap_elemwise_binary +def not_equal(x1: NamedOrNumeric, x2: NamedOrNumeric, /) -> NamedOrNumeric: + return jnp.not_equal(x1, x2) # type: ignore + + +@wrap_elemwise_binary +def power(x1: NamedOrNumeric, x2: NamedOrNumeric, /) -> NamedOrNumeric: + return jnp.power(x1, x2) # type: ignore + + +@wrap_elemwise_binary +def remainder(x1: NamedOrNumeric, x2: NamedOrNumeric, /) -> NamedOrNumeric: + return jnp.remainder(x1, x2) # type: ignore + + +@wrap_elemwise_binary +def right_shift(x1: NamedOrNumeric, x2: NamedOrNumeric, /) -> NamedOrNumeric: + return jnp.right_shift(x1, x2) # type: ignore + + +@wrap_elemwise_binary +def subtract(x1: NamedOrNumeric, x2: NamedOrNumeric, /) -> NamedOrNumeric: + return jnp.subtract(x1, x2) # type: ignore + + +@wrap_elemwise_binary +def true_divide(x1: NamedOrNumeric, x2: NamedOrNumeric, /) -> NamedOrNumeric: + return jnp.true_divide(x1, x2) # type: ignore + # deprecated name concat_axis_specs = concat_axes @@ -357,13 +906,11 @@ __all__ = [ "prod", "product", "ptp", - "sometrue", "std", "sum", "var", "cumsum", "cumprod", - "cumproduct", "sort", "scan", "fold", diff --git a/src/haliax/core.py b/src/haliax/core.py index 58c470d..741e20d 100644 --- a/src/haliax/core.py +++ b/src/haliax/core.py @@ -17,7 +17,7 @@ from haliax.jax_utils import is_jax_array_like from haliax.util import ensure_tuple, index_where, py_slice, slice_t from .axis import Axis, AxisSelection, AxisSelector, AxisSpec, eliminate_axes, selects_axis, union_axes -from .types import PrecisionLike, Scalar +from .types import IntScalar, PrecisionLike, Scalar NamedOrNumeric = Union[Scalar, "NamedArray"] @@ -78,6 +78,7 @@ class NamedArray: raise ValueError(f"Shape of underlying array {s} does not match shape of axes {self.axes}") def item(self): + """Returns the value of this NamedArray as a python scalar.""" return self.array.item() def scalar(self) -> jnp.ndarray: @@ -97,9 +98,13 @@ class NamedArray: # shape = property(lambda self: self.array.shape) dtype = property(lambda self: self.array.dtype) + """The dtype of the underlying array""" ndim = property(lambda self: self.array.ndim) + """The number of dimensions of the underlying array""" size = property(lambda self: self.array.size) + """The number of elements in the underlying array""" nbytes = property(lambda self: self.array.nbytes) + """The number of bytes in the underlying array""" def tree_flatten(self) -> Any: return ((self.array,), self.axes) @@ -110,6 +115,7 @@ class NamedArray: return cls(tree[0], axes=aux) def has_axis(self, axis: AxisSelection) -> bool: + """Returns true if the given axis is present in this NamedArray.""" return self._lookup_indices(axis) is not None @overload @@ -146,7 +152,10 @@ class NamedArray: ... def resolve_axis(self, axes: AxisSelection) -> AxisSpec: # type: ignore - """Returns the axes corresponding to the given axis selection.""" + """ + Returns the axes corresponding to the given axis selection. + That is, it return the [haliax.Axis][] values themselves, not just their names. + """ indices = self._lookup_indices(axes) if isinstance(indices, int): return self.axes[indices] @@ -249,7 +258,7 @@ class NamedArray: return haliax.take(self, axis=axis, index=index) @overload - def __getitem__(self, item: Tuple[str, Union[int, slice_t, "NamedArray"]]) -> Union["NamedArray", jnp.ndarray]: + def __getitem__(self, item: Tuple[str, Union[int, slice_t, "NamedArray"]]) -> Union["NamedArray", Scalar]: ... # pragma: no cover @overload @@ -263,7 +272,7 @@ class NamedArray: ... def __getitem__(self, idx) -> Union["NamedArray", jnp.ndarray]: - """Syntactic sugar for slice_nd, which is the actual implementation. + """Syntactic sugar for [haliax.index][], which is the actual implementation. Supports indexing like: @@ -334,10 +343,10 @@ class NamedArray: def copy(self) -> "NamedArray": return NamedArray(self.array.copy(), self.axes) - def cumprod(self, axis: Optional[AxisSelection] = None, *, dtype=None) -> "NamedArray": + def cumprod(self, axis: Optional[AxisSelector] = None, *, dtype=None) -> "NamedArray": return haliax.cumprod(self, axis=axis, dtype=dtype) - def cumsum(self, axis: Optional[AxisSelection] = None, *, dtype=None) -> "NamedArray": + def cumsum(self, axis: Optional[AxisSelector] = None, *, dtype=None) -> "NamedArray": return haliax.cumsum(self, axis=axis, dtype=dtype) def dot(self, axis: AxisSelection, b, *, precision: PrecisionLike = None) -> "NamedArray": @@ -351,10 +360,9 @@ class NamedArray: self, axis: Optional[AxisSelection] = None, *, - initial=None, where=None, ) -> "NamedArray": - return haliax.max(self, axis=axis, initial=initial, where=where) + return haliax.max(self, axis=axis, where=where) def mean( self, @@ -369,24 +377,21 @@ class NamedArray: self, axis: Optional[AxisSelection] = None, *, - initial=None, where=None, ) -> "NamedArray": - return haliax.min(self, axis=axis, initial=initial, where=where) + return haliax.min(self, axis=axis, where=where) def prod( self, axis: Optional[AxisSelection] = None, *, dtype=None, - initial=None, where=None, ) -> "NamedArray": return haliax.prod( self, axis=axis, dtype=dtype, - initial=initial, where=where, ) @@ -408,8 +413,8 @@ class NamedArray: def round(self, decimals=0) -> "NamedArray": return haliax.round(self, decimals=decimals) - def sort(self, axis: AxisSelector, kind="quicksort") -> Any: - return haliax.sort(self, axis=axis, kind=kind) + def sort(self, axis: AxisSelector) -> Any: + return haliax.sort(self, axis=axis) def std(self, axis: Optional[AxisSelection] = None, *, dtype=None, ddof=0, where=None) -> "NamedArray": return haliax.std(self, axis=axis, dtype=dtype, ddof=ddof, where=where) @@ -419,14 +424,12 @@ class NamedArray: axis: Optional[AxisSelection] = None, *, dtype=None, - initial=None, where=None, ) -> "NamedArray": return haliax.sum( self, axis=axis, dtype=dtype, - initial=initial, where=where, ) @@ -659,14 +662,15 @@ def slice( @typing.overload def slice( array: NamedArray, - start: Mapping[AxisSelector, Union[int, jnp.ndarray]], - length: Optional[Mapping[AxisSelector, int]], + start: Mapping[AxisSelector, IntScalar], + length: Optional[Mapping[AxisSelector, int]] = None, ) -> NamedArray: """ Slices the array along the specified axes, replacing them with new axes (or a shortened version of the old one) - :arg start: the starting index of each axis to slice - :arg length: the length of each axis to slice. If not specified, the length of the new axis will be the same as the old one + Args: + start (Mapping[AxisSelector, Union[int, jnp.ndarray]]): the start index of each axis to slice. If an int, the axis will be sliced at that index. If a NamedArray, the axis will be sliced at the indices in the NamedArray + length (Mapping[AxisSelector, int]): the length of the dimension for that slice. """ pass @@ -676,8 +680,9 @@ def slice(array: NamedArray, *args, **kwargs) -> NamedArray: Slices the array along the specified axis or axes, replacing them with new axes (or a shortened version of the old one) This method has two signatures: - slice(array, axis, new_axis=None, start=0, length=None) - slice(array, start: Mapping[AxisSelector, Union[int, jnp.ndarray]], length: Mapping[AxisSelector, int]) + + * `slice(array, axis, new_axis=None, start=0, length=None)` + * `slice(array, start: Mapping[AxisSelector, IntScalar], length: Mapping[AxisSelector, int])` They both do similar things. The former slices an array along a single axis, replacing it with a new axis. The latter slices an array along multiple axes, replacing them with new axes. @@ -701,15 +706,19 @@ def _slice_old( length: Optional[int] = None, ) -> NamedArray: """ - Selects elements from an array along an axis, by an index or by another named array - This is somewhat better than take if you want a contiguous slice of an array - - :arg axis: the axis to slice - :arg new_axis: the name of the new axis that replaces the old one. If none, the old name will be used - :arg start: the index to start the slice at - :arg length: the length of the slice. either new_axis must be an Axis or length must be specified - - Note: this method is basically a wrapper around jax.lax.dynamic_slice_in_dim + Selects elements from an array along an axis, either by an index or by another named array. + This method offers an advantage over 'take' when a contiguous slice of an array is wanted. + + Args: + axis (AxisSelector): The axis to slice. + new_axis (str, optional): The name of the new axis that replaces the old one. + If none, the old name will be used. + start (int): The index at which the slice will start. + length (int, optional): The length of the slice. Either new_axis must be an `Axis` or + `length` must be specified. + + Note: + This method is basically a wrapper around jax.lax.dynamic_slice_in_dim. """ axis_index = array._lookup_indices(axis) if axis_index is None: @@ -777,11 +786,15 @@ def updated_slice( array: NamedArray, start: Mapping[AxisSelector, Union[int, jnp.ndarray]], update: NamedArray ) -> NamedArray: """ - Updates a slice of an array with another array + Updates a slice of an array with another array. - :arg array: the array to update - :arg start: the starting index of each axis to update - :arg update: the array to update with + Args: + array (NamedArray): The array to update. + start (Mapping[AxisSelector, Union[int, jnp.ndarray]]): The starting index of each axis to update. + update (NamedArray): The array to update with. + + Returns: + NamedArray: The updated array. """ array_slice_indices = [0] * len(array.axes) @@ -820,14 +833,17 @@ def updated_slice( def index( array: NamedArray, slices: Mapping[AxisSelector, Union[int, slice_t, NamedArray]] -) -> Union[NamedArray, jnp.ndarray]: +) -> Union[NamedArray, Scalar]: """ - Selects elements from an array along an axis, by an index or by another named array. - Typically, you would call this via `array[...]` syntax. For example, you might call - `array[{"batch": slice(0, 10)}]` to select the first 10 elements of the batch axis. - :param array: - :param slices: - :return: a scalar jnp.ndarray is all axes are sliced with ints, otherwise a NamedArray + Selects elements from an array along an axis via index or another named array. + + This function is typically invoked using `array[...]` syntax. For instance, + you might use `array[{"batch": slice(0, 10)}]` or `array["batch", 0:10]` to select the first 10 elements + of the 'batch' axis. + + Returns: + NamedArray or jnp.ndarray: A NamedArray is returned if there are any axes remaining after selection, + otherwise a scalar (0-dimensional) jnp.ndarray is returned if all axes are indexed out. """ # indices where we have array args array_slice_indices = [] @@ -906,6 +922,15 @@ def dot(axis: AxisSelection, *arrays: NamedArray, precision: PrecisionLike = Non """Returns the tensor product of two NamedArrays. The axes `axis` are contracted over, and any other axes that are shared between the arrays are batched over. Non-contracted Axes in one that are not in the other are preserved. + + Args: + axis (AxisSelection): The axes to contract over. + *arrays (NamedArray): The arrays to contract. + precision (PrecisionLike, optional): The precision to use. Defaults to None. This argument is passed to `jax.numpy.einsum`, + which in turn passes it to jax.lax.dot_general. + + Returns: + NamedArray: The result of the contraction. """ _ensure_no_mismatched_axes(*arrays) output_axes: Tuple[Axis, ...] = ft.reduce(union_axes, (a.axes for a in arrays), ()) # type: ignore @@ -944,6 +969,14 @@ def dot(axis: AxisSelection, *arrays: NamedArray, precision: PrecisionLike = Non def split(a: NamedArray, axis: AxisSelector, new_axes: Sequence[Axis]) -> Sequence[NamedArray]: + """ + Splits an array along an axis into multiple arrays, one for each element of new_axes. + + Args: + a (NamedArray): the array to split + axis (AxisSelector): the axis to split along + new_axes (Sequence[Axis]): the axes to split into. Must have the same total length as the axis being split. + """ # check the lengths of the new axes index = a._lookup_indices(axis) if index is None: @@ -974,6 +1007,13 @@ def rearrange(array: NamedArray, axes: Sequence[Union[AxisSelector, EllipsisType Rearrange an array so that its underlying storage conforms to axes. axes may include up to 1 ellipsis, indicating that the remaining axes should be permuted in the same order as the array's axes. + + For example, if array has axes (a, b, c, d, e, f) and axes is (e, f, a, ..., c), + then the output array will have axes (e, f, a, b, c, d). + + Args: + array (NamedArray): The array to rearrange. + axes (Sequence[Union[AxisSelector, EllipsisType]]): The axes to rearrange to. """ if len(axes) == 0 and len(array.axes) != 0: raise ValueError("No axes specified") @@ -1027,7 +1067,8 @@ def rearrange(array: NamedArray, axes: Sequence[Union[AxisSelector, EllipsisType def unbind(array: NamedArray, axis: AxisSelector) -> List[NamedArray]: """ - Unbind an array along an axis, returning a list of NamedArrays. Analogous to torch.unbind or np.rollaxis + Unbind an array along an axis, returning a list of NamedArrays, one for each position on that axis. + Analogous to torch.unbind or np.rollaxis """ axis_index = array._lookup_indices(axis) if axis_index is None: @@ -1054,6 +1095,12 @@ def roll(array: NamedArray, shift: Union[int, Tuple[int, ...]], axis: AxisSelect def rename(array: NamedArray, renames: Mapping[AxisSelector, AxisSelector]) -> NamedArray: + """ + Rename the axes of an array. + Args: + array: the array to rename + renames: a mapping from old axes to new axes. If the value is a string, the axis will be renamed to that string. + """ for old, new in renames.items(): if isinstance(old, Axis) and isinstance(new, Axis) and old.size != new.size: raise ValueError(f"Cannot rename axis {old} to {new}: size mismatch") @@ -1085,7 +1132,8 @@ def rename(array: NamedArray, renames: Mapping[AxisSelector, AxisSelector]) -> N def flatten_axes(array: NamedArray, old_axes: AxisSelection, new_axis: AxisSelector) -> NamedArray: """ Merge a sequence of axes into a single axis. The new axis must have the same size as the product of the old axes. - For now the new axis will always be the last axis + + The new axis is always inserted starting at the index of the first old axis in theunderlying array. """ old_axes = ensure_tuple(old_axes) old_axes = array.resolve_axis(old_axes) @@ -1152,7 +1200,7 @@ def unflatten_axis(array: NamedArray, axis: AxisSelector, new_axes: AxisSpec) -> def named(a: jnp.ndarray, axis: AxisSelection) -> NamedArray: - """Creates a NamedArray from a numpy array and a list of axes""" + """Creates a NamedArray from a numpy array and a list of axes.""" axes = check_shape(a.shape, axis) return NamedArray(a, axes) @@ -1284,6 +1332,20 @@ def broadcast_arrays( require_subset: bool = True, ensure_order: bool = True, ) -> Tuple[Optional[NamedOrNumeric], ...]: + """ + Broadcasts a sequence of arrays to a common set of axes. + Args: + *arrays: Arrays, Scalars, or None. If None, then None is returned. Scalars and None are supported for convenience. + require_subset: If true, then one of the arrays must be a subset of the others. This is a bit stricter than numpy's broadcasting + rules, but I've been bitten by numpy's rules too many times. False is looser than numpy's rules, and allows + broadcasting any pair of arrays (so long as the axes don't overtly conflict with different sizes for the same + name.) + ensure_order: If true, then the returned arrays will be reordered to all have the same axes in the same order. + + Returns: + The arrays, broadcast to a common set of axes, reordered if necessary. + + """ return broadcast_arrays_and_return_axes(*arrays, require_subset=require_subset, ensure_order=ensure_order)[0] @@ -1351,8 +1413,10 @@ def broadcast_arrays_and_return_axes( # TODO: convert to AxisSelection? def broadcast_axis(a: NamedArray, axis: AxisSpec) -> NamedArray: """ - Broadcasts a, ensuring that it has all the axes in axis. - broadcast_axis is an alias for broadcast_to(a, axis, enforce_no_extra_axes=False, ensure_order=True) + Broadcasts `a`, ensuring that it has all the axes in `axis`. + `broadcast_axis` is an alias for `broadcast_to(a, axis, enforce_no_extra_axes=False, ensure_order=True)` + + You typically use this function when you want to broadcast an array to a common set of axes. """ if isinstance(axis, Axis) and axis in a.axes: return a diff --git a/src/haliax/hof.py b/src/haliax/hof.py index 796f04d..7750742 100644 --- a/src/haliax/hof.py +++ b/src/haliax/hof.py @@ -32,17 +32,17 @@ def scan( """ Scan over a named axis. Arrays that are not part of a NamedArray will have their 0th dim scanned over - Unlike jax.lax.scan, this function is curried: it takes the function, axis, and configuration arguments first, and + Unlike [jax.lax.scan][], this function is curried: it takes the function, axis, and configuration arguments first, and then the initial carry and then any arguments to scan over as a separate curried function call. - That is, scan(f, axis)(init, xs) is equivalent to jax.lax.scan(f, init, xs) + That is, `scan(f, axis)(init, xs)` is equivalent to `jax.lax.scan(f, init, xs)` Args: - :param f: function to scan over - :param axis: axis to scan over - :param reverse: if True, scan in reverse - :param unroll: unroll the loop by this amount - :param is_scanned: a function that takes a leaf of the tree and returns True if it should be scanned over, + f (Callable): function to scan over + axis (AxisSelector): axis to scan over + reverse (bool): if True, scan in reverse + unroll (int): unroll the loop by this amount + is_scanned (BoolAxisSpec): a function that takes a leaf of the tree and returns True if it should be scanned over, False otherwise. Behaves similarly to the `default` argument in filter_jit """ @@ -114,6 +114,9 @@ def fold( :param unroll: unroll the loop by this amount :param is_scanned: a function that takes a leaf of the tree and returns True if it should be scanned over, False otherwise. Behaves similarly to the `default` argument in filter_jit + + Returns: + A function that takes the initial carry and then the arguments to reduce over, and returns the final carry """ def scan_compatible_fn(carry, *args, **kwargs): @@ -140,6 +143,13 @@ def map( You'll typically want to use map (instead of a vmap or just vectorized code) when you want to encourage XLA to loop over the axis to control memory. + + Args: + fn (Callable): function to map over + axis (Axis): axis to map over + reverse (bool): if True, map in reverse + unroll (int): unroll the loop by this amount + """ def scan_compatible_fn(_, x): @@ -171,18 +181,21 @@ def vmap( kwargs: PyTree[UnnamedAxisSpec] = None, ): """ - NamedArray aware version of jax.vmap. Normal arrays are mapped according to the specs as in equinox.filter_vmap, - except that the output axis is always 0 b/c it's annoying to make anything else work - - Because of NamedArrays, vmap is typically less useful than in vanilla jax, but it is sometimes - useful for initializing modules that will be scanned over. - - default: how to handle (unnamed) arrays by default. Should be either an integer or None, or a callable that takes a PyTree leaf - and returns an integer or None, or a PyTree prefix of the same. If an integer, the array will be mapped over that axis. If None, the array will not be mapped over. - args: optional per-argument overrides for how to handle arrays. Should be a PyTree prefix of the same type as default. - kwargs: optional per-keyword-argument overrides for how to handle arrays. Should be a PyTree prefix of the same type as default. - out: optional override for how to handle the output. Should be a PyTree prefix of the same type as default. Defaults - to 0 if the output is an unnamed array, and the Axis otherwise. + [haliax.NamedArray][]-aware version of [jax.vmap][]. Normal arrays are mapped according to the specs as in + [equinox.filter_vmap][], except that the output axis is always 0 b/c it's annoying to make anything else work + + Because of NamedArrays, vmap is typically less useful than in vanilla JAX, but it is sometimes + useful for initializing modules that will be scanned over. See [haliax.nn.Stacked][] for an example. + + Args: + fn: function to vmap over + axis: axis to vmap over + default: how to handle (unnamed) arrays by default. Should be either an integer or None, or a callable that takes a PyTree leaf + and returns an integer or None, or a PyTree prefix of the same. If an integer, the array will be mapped over that axis. If None, the array will not be mapped over. + args: optional per-argument overrides for how to handle arrays. Should be a PyTree prefix of the same type as default. + kwargs: optional per-keyword-argument overrides for how to handle arrays. Should be a PyTree prefix of the same type as default. + out: optional override for how to handle the output. Should be a PyTree prefix of the same type as default. Defaults + to 0 if the output is an unnamed array, and the Axis otherwise. """ if kwargs is None: diff --git a/src/haliax/nn/__init__.py b/src/haliax/nn/__init__.py index 7a663b2..7803897 100644 --- a/src/haliax/nn/__init__.py +++ b/src/haliax/nn/__init__.py @@ -1,4 +1,5 @@ import functools +import typing import warnings from typing import Optional, Tuple, Union @@ -9,8 +10,9 @@ import haliax import haliax as hax import haliax.nn.attention as attention -from ..axis import Axis, AxisSelector, AxisSpec +from ..axis import Axis, AxisSelection, AxisSelector, AxisSpec from ..core import NamedArray +from ..types import Scalar from ..util import UNSPECIFIED, Unspecified from ..wrap import ReductionFunction, unwrap_namedarrays, wrap_axiswise_call, wrap_elemwise_unary, wrap_reduction_call from .dropout import Dropout, dropout @@ -20,23 +22,75 @@ from .normalization import LayerNorm from .scan import Stacked -relu = wrap_elemwise_unary(jnn.relu) -relu6 = wrap_elemwise_unary(jnn.relu6) -sigmoid = wrap_elemwise_unary(jnn.sigmoid) -softplus = wrap_elemwise_unary(jnn.softplus) -soft_sign = wrap_elemwise_unary(jnn.soft_sign) -silu = wrap_elemwise_unary(jnn.silu) -swish = wrap_elemwise_unary(jnn.swish) -log_sigmoid = wrap_elemwise_unary(jnn.log_sigmoid) -leaky_relu = wrap_elemwise_unary(jnn.leaky_relu) -hard_sigmoid = wrap_elemwise_unary(jnn.hard_sigmoid) -hard_silu = wrap_elemwise_unary(jnn.hard_silu) -hard_swish = wrap_elemwise_unary(jnn.hard_swish) -hard_tanh = wrap_elemwise_unary(jnn.hard_tanh) -elu = wrap_elemwise_unary(jnn.elu) -celu = wrap_elemwise_unary(jnn.celu) -selu = wrap_elemwise_unary(jnn.selu) -gelu = wrap_elemwise_unary(jnn.gelu) +A = typing.TypeVar("A", Scalar, NamedArray, jnp.ndarray) + + +def relu(a: A) -> A: + return wrap_elemwise_unary(jnn.relu, a) + + +def relu6(a: A) -> A: + return wrap_elemwise_unary(jnn.relu6, a) + + +def sigmoid(a: A) -> A: + return wrap_elemwise_unary(jnn.sigmoid, a) + + +def softplus(a: A) -> A: + return wrap_elemwise_unary(jnn.softplus, a) + + +def soft_sign(a: A) -> A: + return wrap_elemwise_unary(jnn.soft_sign, a) + + +def silu(a: A) -> A: + return wrap_elemwise_unary(jnn.silu, a) + + +def swish(a: A) -> A: + return wrap_elemwise_unary(jnn.swish, a) + + +def log_sigmoid(a: A) -> A: + return wrap_elemwise_unary(jnn.log_sigmoid, a) + + +def leaky_relu(a: A) -> A: + return wrap_elemwise_unary(jnn.leaky_relu, a) + + +def hard_sigmoid(a: A) -> A: + return wrap_elemwise_unary(jnn.hard_sigmoid, a) + + +def hard_silu(a: A) -> A: + return wrap_elemwise_unary(jnn.hard_silu, a) + + +def hard_swish(a: A) -> A: + return wrap_elemwise_unary(jnn.hard_swish, a) + + +def hard_tanh(a: A) -> A: + return wrap_elemwise_unary(jnn.hard_tanh, a) + + +def elu(a: A) -> A: + return wrap_elemwise_unary(jnn.elu, a) + + +def celu(a: A) -> A: + return wrap_elemwise_unary(jnn.celu, a) + + +def selu(a: A) -> A: + return wrap_elemwise_unary(jnn.selu, a) + + +def gelu(a: A, approximate: bool = True) -> A: + return wrap_elemwise_unary(jnn.gelu, a, approximate=approximate) def glu(x: NamedArray, axis: Axis) -> NamedArray: @@ -44,11 +98,18 @@ def glu(x: NamedArray, axis: Axis) -> NamedArray: return jnn.glu(x.array, axis_index) -logsumexp = wrap_reduction_call(jnn.logsumexp, False, supports_where=False) +def logsumexp(a: A, axis: Optional[AxisSelection] = None) -> A: + # TODO: logsumexp indirectly supports where via `b`. we should support it directly + return wrap_reduction_call(jnn.logsumexp, a, axis=axis, single_axis_only=False, supports_where=False) + # TODO: support where in softmax, etc -softmax = wrap_axiswise_call(jnn.softmax, False) -log_softmax = wrap_axiswise_call(jnn.log_softmax, False) +def softmax(a: A, axis: Optional[AxisSelection] = None) -> A: + return wrap_axiswise_call(jnn.softmax, a, axis=axis, single_axis_only=False) + + +def log_softmax(a: A, axis: Optional[AxisSelection] = None) -> A: + return wrap_axiswise_call(jnn.log_softmax, a, axis=axis, single_axis_only=False) def standardize( @@ -60,7 +121,7 @@ def standardize( epsilon: float = 1e-5, where: Optional[NamedArray] = None, ) -> NamedArray: - """Analogous to `jax.nn.standardize`, but with support for NamedArrays.""" + """Analogous to [jax.nn.standardize][], but with support for NamedArrays.""" x, mean, variance, where = haliax.broadcast_arrays(x, mean, variance, where) # type: ignore raw_x, mean, variance, where = unwrap_namedarrays(x, mean, variance, where) axis_indices = x._lookup_indices(axis) diff --git a/src/haliax/nn/scan.py b/src/haliax/nn/scan.py index 7a5e66b..7d5f7bb 100644 --- a/src/haliax/nn/scan.py +++ b/src/haliax/nn/scan.py @@ -24,7 +24,7 @@ class Stacked(eqx.Module, Generic[M]): where you have multiple instances of the same transformer block and the input is applied in a fold/for loop in sequence. - It's similar in spirit to an equinox.nn.Sequential, but it must be homogeneous. In Jax, this is much cheaper to + It's similar in spirit to an [equinox.nn.Sequential], but it must be homogeneous. In Jax, this is much cheaper to compile than a sequential (or moral equivalent), because Jax compiles the module's method once, instead of unrolling the sequential and compiling everything as a giant graph. In Jax, this pattern is often called "scan layers" or "scan over layers". diff --git a/src/haliax/partitioning.py b/src/haliax/partitioning.py index 21df8d1..6bfa6ac 100644 --- a/src/haliax/partitioning.py +++ b/src/haliax/partitioning.py @@ -3,7 +3,7 @@ import functools import threading import typing from math import prod -from typing import Mapping, Optional, Sequence, TypeVar, Union +from typing import Callable, Mapping, Optional, Sequence, TypeVar, Union import equinox as eqx import jax @@ -24,10 +24,8 @@ from .tree_util import hashable_combine, hashable_partition from .util import StringHolderEnum, ensure_tuple, is_named_array -LogicalAxisName = str -PhysicalAxis = str -PhysicalAxisSpec = Union[PhysicalAxis, Sequence[PhysicalAxis]] -ResourceMapping = Mapping[LogicalAxisName, PhysicalAxisSpec] +PhysicalAxisSpec = Union[(str), Sequence[str]] +ResourceMapping = Mapping[(str), PhysicalAxisSpec] """Mapping from logical axis names to physical axis names""" F = typing.TypeVar("F", bound=typing.Callable) @@ -206,7 +204,7 @@ def infer_resource_partitions( def named_jit( - fn=None, + fn: Callable = None, axis_resources: Optional[ResourceMapping] = None, *, in_axis_resources: Optional[ResourceMapping] = None, @@ -216,32 +214,40 @@ def named_jit( **pjit_args, ): """ - A version of pjit that uses NamedArrays and the provided resource mapping to infer the resource partitions. + A version of pjit that uses NamedArrays and the provided resource mapping to infer resource partitions for + sharded computation for. - If no resource mapping is provided, this function attempts to use the global resource mapping. - axis_resources will be used for a context-specific resource mapping. In addition, if in_axis_resources is not - provided, the arguments' own (pre-existing) shardings will be used as the in_axis_resources. + `axis_resources` will be used for a context-specific resource mapping when the function is invoked. + In addition, if in_axis_resources is not provided, the arguments' own (pre-existing) shardings will be used as the in_axis_resources. If out_axis_resources is not provided, axis_resources will be used as the out_axis_resources. - functionally this is very similar to something like: + If no resource mapping is provided, this function attempts to use the context resource mapping. + + Functionally this is very similar to something like: ```python arg = hax.shard_with_axis_mapping(arg, in_axis_resources) - with hax.use_resource_mapping(axis_resources): - result = jit(fn, **pjit_args)(arg) + with hax.axis_mapping(axis_resources): + result = jax.jit(fn, **pjit_args)(arg) result = hax.shard_with_axis_mapping(result, out_axis_resources) return result ``` - but it uses the jit decorator directly - - :param fn: The function to be jit'd - :param axis_resources: A mapping from logical axis names to physical axis names use for the contextual resource mapping - :param in_axis_resources: A mapping from logical axis names to physical axis names for arguments. If not passed, it uses the arguments' own shardings - :param out_axis_resources: A mapping from logical axis names to physical axis names for the result, defaults to axis_resources - :param donate_args: A PyTree of booleans or function leaf->bool, indicating whether to donate arguments to the - computation - :param donate_kwargs: A PyTree of booleans or function leaf->bool, indicating whether to donate keyword arguments to - the computation + + Args: + fn (Callable, optional): The function to be jit'd. + axis_resources (ResourceMapping, optional): A mapping from logical axis names to physical axis names use for th + e context-specific resource mapping. + in_axis_resources (ResourceMapping, optional): A mapping from logical axis names to physical axis names for + arguments. If not passed, it uses the argument's own shardings. + out_axis_resources (ResourceMapping, optional): A mapping from logical axis names to physical axis names for the + result, defaults to axis_resources. + donate_args (PyTree, optional): A PyTree of booleans or function leaf->bool, indicating if the arguments should + be donated to the computation. + donate_kwargs (PyTree, optional): A PyTree of booleans or function leaf->bool, indication if the keyword + arguments should be donated to the computation. + + Returns: + A jit'd version of the function. """ if fn is None: @@ -478,8 +484,6 @@ def _is_jit_tracer(x) -> bool: __all__ = [ - "LogicalAxisName", - "PhysicalAxis", "PhysicalAxisSpec", "ResourceAxis", "ResourceMapping", diff --git a/src/haliax/random.py b/src/haliax/random.py index 0f8c26e..486cb02 100644 --- a/src/haliax/random.py +++ b/src/haliax/random.py @@ -1,6 +1,7 @@ """Wrappers around jax.random functions.""" import functools import inspect +import warnings from typing import Optional import jax @@ -131,6 +132,7 @@ _enforce_sharded_generate = False def generate_sharded(fn, axis: Optional[AxisSelector] = None): """ + DEPRECATED: use jax.config.update("jax_threefry_partitionable", True) instead Create a wrapped version of fn (which should be a random generator) that generates the random array in a sharded manner, using vmap over the provided axis, or inferring the "best" one if not provided. @@ -141,14 +143,15 @@ def generate_sharded(fn, axis: Optional[AxisSelector] = None): not a [1024] vector but a [1600, 6400] matrix (for say, gpt-2). So we split the key here, and then let vmap hopefully only generate the random numbers for the local shard. - - However, we don't want to oversplit or it kind of ruins the whole point since we have to split the key on every node... So instead we just split along the *largest* physical axis, or the provided axis if it's provided. """ - # TODO: we won't need to do this when they add better splitting for random numbers - # (froystig is maybe going to do this?) + if not _enforce_sharded_generate: + warnings.warn( + 'generate_sharded is deprecated. Use jax.config.update("jax_threefry_partitionable", True) instead', + DeprecationWarning, + ) @functools.wraps(fn) def wrapped_fn(*args, **kwargs): @@ -243,7 +246,7 @@ def categorical(key, logits: NamedArray, axis: AxisSelector, shape: Optional[Axi so that `softmax(logits, axis)` gives the corresponding probabilities. axis: Axis along which logits belong to the same categorical distribution. shape: A tuple of axes representing the result shape, or None. if None, the shape is - logits.axes \ {axis}. If not None, logits.axes \ {axis} must be a subset of shape. + `logits.axes - {axis}`. If not None, `logits.axes - {axis}` must be a subset of shape. Returns: A random array with int dtype and shape given by ``shape`` """ diff --git a/src/haliax/types.py b/src/haliax/types.py index b674b69..512d453 100644 --- a/src/haliax/types.py +++ b/src/haliax/types.py @@ -1,8 +1,10 @@ from typing import Tuple, Union +import jax.numpy as jnp from jax.lax import Precision -Scalar = Union[float, int] +Scalar = Union[float, int, jnp.ndarray] # ndarray b/c array(1) is a scalar +IntScalar = Union[int, jnp.ndarray] PrecisionLike = Union[None, str, Precision, Tuple[str, str], Tuple[Precision, Precision]] diff --git a/src/haliax/wrap.py b/src/haliax/wrap.py index f7fb956..f5d0c7c 100644 --- a/src/haliax/wrap.py +++ b/src/haliax/wrap.py @@ -1,4 +1,3 @@ -import functools from typing import Optional, Protocol import jax @@ -10,114 +9,89 @@ from haliax.util import ensure_tuple from .axis import AxisSelection, AxisSelector, selects_axis -def wrap_elemwise_unary(f): - """Wraps a unary elementwise function to take and return NamedArrays""" - - @functools.wraps(f) - def wrapper(a, *args, **kwargs): +def wrap_elemwise_unary(f, a, *args, **kwargs): + if isinstance(a, NamedArray): + return NamedArray(f(a.array, *args, **kwargs), a.axes) + else: + return f(a, *args, **kwargs) + + +def wrap_reduction_call( + fn, + a, + axis: Optional[AxisSelection], + where: Optional[NamedArray] = None, + single_axis_only: bool = False, + supports_where: bool = True, + **kwargs, +): + kwargs = dict(kwargs) + if where is not None and not supports_where: + raise ValueError(f"where is not supported by {fn.__name__}") + + if kwargs.get("out", None) is not None: + raise ValueError("out is not supported yet for NamedArray") + if kwargs.get("keepdims", False): + raise ValueError("keepdims is not supported for NamedArray") + + def reduce_one_leaf(a): + nonlocal axis, where if isinstance(a, NamedArray): - return NamedArray(f(a.array, *args, **kwargs), a.axes) - else: - return f(a, *args, **kwargs) - - return wrapper - - -def wrap_reduction_call(fn, single_axis_only: bool = False, supports_where: bool = True): - @functools.wraps(fn) - def wrapper(a, axis: Optional[AxisSelection] = None, where: NamedArray = None, **kwargs): - kwargs = dict(kwargs) - if where is not None and not supports_where: - raise ValueError(f"where is not supported by {fn.__name__}") - - if kwargs.get("out", None) is not None: - raise ValueError("out is not supported yet for NamedArray") - if kwargs.get("keepdims", False): - raise ValueError("keepdims is not supported for NamedArray") - - def reduce_one_leaf(a): - nonlocal axis, where - if isinstance(a, NamedArray): - if where is not None: - if not isinstance(where, NamedArray): - raise TypeError("where must be a NamedArray if a is a NamedArray") - where = broadcast_to(where, a.axes) - kwargs["where"] = where.array - - if axis is None: - result = fn(a.array, axis=None, **kwargs) - if jnp.isscalar(result): - return result - else: - return NamedArray(result, ()) - else: - axis = ensure_tuple(axis) - if single_axis_only and len(axis) > 1: - raise ValueError(f"{fn.__name__} only supports a single axis") - indices = a._lookup_indices(axis) - if indices is None or any(x is None for x in indices): - raise ValueError(f"axis {axis} is not in {a.axes}") - new_axes = [ax for ax in a.axes if not selects_axis(axis, ax)] - if single_axis_only: - result = fn(a.array, axis=indices[0], **kwargs) - else: - result = fn(a.array, axis=indices, **kwargs) - if jnp.isscalar(result): - return result - return NamedArray(result, tuple(new_axes)) - else: - if where is not None: - kwargs["where"] = where - return fn(a, axis=axis, **kwargs) - - return jax.tree_util.tree_map(reduce_one_leaf, a, is_leaf=lambda x: isinstance(x, NamedArray)) + if where is not None: + if not isinstance(where, NamedArray): + raise TypeError("where must be a NamedArray if a is a NamedArray") + where = broadcast_to(where, a.axes) + kwargs["where"] = where.array - wrapper.__doc__ = ( - """ - This function augments the behavior of `{fn}` to support NamedArrays, so that axis is a NamedArray. - At the moment, neither `where` nor `out` are supported. - ===== - - """ - + fn.__doc__ - ) - return wrapper - - -def wrap_axiswise_call(fn, single_axis_only: bool): - @functools.wraps(fn) - def wrapper(a, axis: Optional[AxisSelection] = None, **kwargs): - if isinstance(a, NamedArray): if axis is None: - return NamedArray(fn(a.array, axis=None, **kwargs), a.axes) + result = fn(a.array, axis=None, **kwargs) + if jnp.isscalar(result): + return result + else: + return NamedArray(result, ()) else: - indices = ensure_tuple(a._lookup_indices(axis)) - if any(x is None for x in indices): - raise ValueError(f"axis {axis} is not in {a.axes}") - if len(indices) == 1: - return NamedArray(fn(a.array, axis=indices[0], **kwargs), a.axes) - elif single_axis_only: + axis = ensure_tuple(axis) + if single_axis_only and len(axis) > 1: raise ValueError(f"{fn.__name__} only supports a single axis") + indices = a._lookup_indices(axis) + if indices is None or any(x is None for x in indices): + raise ValueError(f"axis {axis} is not in {a.axes}") + new_axes = [ax for ax in a.axes if not selects_axis(axis, ax)] + if single_axis_only: + result = fn(a.array, axis=indices[0], **kwargs) else: - return NamedArray(fn(a.array, axis=indices, **kwargs), a.axes) - + result = fn(a.array, axis=indices, **kwargs) + if jnp.isscalar(result): + return result + return NamedArray(result, tuple(new_axes)) else: + if where is not None: + kwargs["where"] = where return fn(a, axis=axis, **kwargs) - wrapper.__doc__ = ( - """ - This function augments the behavior of `{fn}` to support NamedArrays, so that axis is an Axis of sequence of axes. - At the moment, neither `where` nor `out` are supported. - ===== + return jax.tree_util.tree_map(reduce_one_leaf, a, is_leaf=lambda x: isinstance(x, NamedArray)) + + +def wrap_axiswise_call(fn, a, axis: Optional[AxisSelection], *, single_axis_only: bool, **kwargs): + if isinstance(a, NamedArray): + if axis is None: + return NamedArray(fn(a.array, axis=None, **kwargs), a.axes) + else: + indices = ensure_tuple(a._lookup_indices(axis)) + if any(x is None for x in indices): + raise ValueError(f"axis {axis} is not in {a.axes}") + if len(indices) == 1: + return NamedArray(fn(a.array, axis=indices[0], **kwargs), a.axes) + elif single_axis_only: + raise ValueError(f"{fn.__name__} only supports a single axis") + else: + return NamedArray(fn(a.array, axis=indices, **kwargs), a.axes) - """ - + fn.__doc__ - ) - return wrapper + else: + return fn(a, axis=axis, **kwargs) def wrap_elemwise_binary(op): - @functools.wraps(op) def binop(a, b): if isinstance(a, NamedArray) and isinstance(b, NamedArray): axes = _broadcast_order(a, b) commit f9e00305a9d98178e443abffc76142b693066e17 Date: 2023-08-24T15:16:34-07:00 default to not donating args that aren't specified diff --git a/src/haliax/partitioning.py b/src/haliax/partitioning.py index 6bfa6ac..72ee0de 100644 --- a/src/haliax/partitioning.py +++ b/src/haliax/partitioning.py @@ -285,6 +285,9 @@ def named_jit( else: dargs = donate_args + if len(dargs) < len(args): + dargs = dargs + (False,) * (len(args) - len(dargs)) + if len(dargs) != len(args): raise ValueError(f"Expected {len(args)} donate_args, got {len(dargs)}") commit e3daa946d98b4cdb5e7104ee0cf93a184f5c4679 Date: 2023-08-29T13:36:40-07:00 suppress warning in concatenate by using axis name for the concatenated axis diff --git a/src/haliax/__init__.py b/src/haliax/__init__.py index 76f5171..37e2712 100644 --- a/src/haliax/__init__.py +++ b/src/haliax/__init__.py @@ -166,12 +166,15 @@ def concatenate(axis: AxisSelector, arrays: Sequence[NamedArray]) -> NamedArray: if len(arrays) == 0: return zeros(axis) - arrays = [a.rearrange(arrays[0].axes) for a in arrays] axis_index = arrays[0]._lookup_indices(axis.name) - if axis_index is None: raise ValueError(f"Axis {axis.name} not found in 0th array {arrays[0]}") + axes: typing.Tuple[AxisSelector, ...] = arrays[0].axes + # we want to use the axis name for `axis`, because it's not uncommon for those to be different lengths in the arrays + axes = axes[:axis_index] + (axis.name,) + axes[axis_index + 1 :] + arrays = [a.rearrange(axes) for a in arrays] + new_axes = arrays[0].axes[:axis_index] + (axis,) + arrays[0].axes[axis_index + 1 :] return NamedArray(jnp.concatenate([a.array for a in arrays], axis=axis_index), new_axes) commit 0ff60ec1d16780c4d42d74e96cbe0cdb5a585427 Date: 2023-08-29T23:12:55-07:00 suppress warning in concatenate by using axis name for the concatenated axis diff --git a/src/haliax/__init__.py b/src/haliax/__init__.py index 37e2712..9ee99dc 100644 --- a/src/haliax/__init__.py +++ b/src/haliax/__init__.py @@ -155,24 +155,25 @@ def concatenate(axis: AxisSelector, arrays: Sequence[NamedArray]) -> NamedArray: """Version of [jax.numpy.concatenate][] that returns a NamedArray. The returns array will have the same axis names in the same order as the first, with the selected axis extended by the sum of the sizes of the selected axes in the concatenated arrays.""" - total_size: int = _sum(a.resolve_axis(axis).size for a in arrays) # type: ignore + axis_name = axis.name if isinstance(axis, Axis) else axis + total_size: int = _sum(a.resolve_axis(axis_name).size for a in arrays) # type: ignore if isinstance(axis, str): axis = Axis(axis, total_size) elif total_size != axis.size: raise ValueError( - f"Cannot concatenate arrays along axis {axis.name} of size {axis.size} with total size {total_size}" + f"Cannot concatenate arrays along axis {axis_name} of size {axis.size} with total size {total_size}" ) if len(arrays) == 0: return zeros(axis) - axis_index = arrays[0]._lookup_indices(axis.name) + axis_index = arrays[0]._lookup_indices(axis_name) if axis_index is None: - raise ValueError(f"Axis {axis.name} not found in 0th array {arrays[0]}") + raise ValueError(f"Axis {axis_name} not found in 0th array {arrays[0]}") axes: typing.Tuple[AxisSelector, ...] = arrays[0].axes # we want to use the axis name for `axis`, because it's not uncommon for those to be different lengths in the arrays - axes = axes[:axis_index] + (axis.name,) + axes[axis_index + 1 :] + axes = axes[:axis_index] + (axis_name,) + axes[axis_index + 1 :] arrays = [a.rearrange(axes) for a in arrays] new_axes = arrays[0].axes[:axis_index] + (axis,) + arrays[0].axes[axis_index + 1 :] commit 18631a5bcc8c7c4a47c46e6037794f86a66126b0 Date: 2023-08-31T10:33:19-07:00 Use `inference` field a la equinox (#29) * Use an inference field a la equinox for dropout * make vmap automatically partition out non-array args diff --git a/src/haliax/hof.py b/src/haliax/hof.py index 7750742..564c639 100644 --- a/src/haliax/hof.py +++ b/src/haliax/hof.py @@ -182,7 +182,7 @@ def vmap( ): """ [haliax.NamedArray][]-aware version of [jax.vmap][]. Normal arrays are mapped according to the specs as in - [equinox.filter_vmap][], except that the output axis is always 0 b/c it's annoying to make anything else work + [equinox.filter_vmap][] Because of NamedArrays, vmap is typically less useful than in vanilla JAX, but it is sometimes useful for initializing modules that will be scanned over. See [haliax.nn.Stacked][] for an example. @@ -238,20 +238,19 @@ def vmap( len(actual_bound.args) - len(axis_spec_bound_sig.args) ) - # want to support padded_spec_args being a tree prefix of the actual args, which this enables - padded_spec_args = broadcast_prefix(padded_spec_args, actual_bound.args, is_leaf=is_named_array) - - arg_axis_specs = jax.tree_util.tree_map( - _index_of_batch_axis, actual_bound.args, padded_spec_args, is_leaf=is_named_array - ) - padded_spec_kwargs = { **axis_spec_bound_sig.kwargs, **{k: default for k in actual_bound.kwargs.keys() - axis_spec_bound_sig.kwargs.keys()}, } + # want to support padded_spec_args being a tree prefix of the actual args, which this enables + padded_spec_args = broadcast_prefix(padded_spec_args, actual_bound.args, is_leaf=is_named_array) padded_spec_kwargs = broadcast_prefix(padded_spec_kwargs, actual_bound.kwargs) + arg_axis_specs = jax.tree_util.tree_map( + _index_of_batch_axis, actual_bound.args, padded_spec_args, is_leaf=is_named_array + ) + kwarg_axis_specs = jax.tree_util.tree_map( _index_of_batch_axis, actual_bound.kwargs, padded_spec_kwargs, is_leaf=is_named_array ) @@ -261,9 +260,6 @@ def vmap( arg_axis_specs = jax.tree_util.tree_map(_pacify_named_arrays, arg_axis_specs, is_leaf=is_named_array) kwarg_axis_specs = jax.tree_util.tree_map(_pacify_named_arrays, kwarg_axis_specs, is_leaf=is_named_array) - args = jax.tree_util.tree_map(_pacify_named_arrays, actual_bound.args, is_leaf=is_named_array) - kwargs = jax.tree_util.tree_map(_pacify_named_arrays, actual_bound.kwargs, is_leaf=is_named_array) - def wrapped_fn(args, kwargs): # the args that come in here are pacified. Their names will still have the batch axis even though the array # itself will already have that one removed. We need to turn them back into NamedArrays by removing the axis @@ -276,11 +272,14 @@ def vmap( # now we need to pacify the output, which may include NamedArrays, and add the batch axis back at the end chilled = jax.tree_util.tree_map(_pacify_named_arrays, out, is_leaf=is_named_array) - arrays, nonarrays = eqx.partition(chilled, eqx.is_array_like) + arrays, nonarrays = eqx.partition(chilled, is_jax_array_like) return arrays, Static(nonarrays) spmd_axis_name = physical_axis_name(axis) + args = jax.tree_util.tree_map(_pacify_named_arrays, actual_bound.args, is_leaf=is_named_array) + kwargs = jax.tree_util.tree_map(_pacify_named_arrays, actual_bound.kwargs, is_leaf=is_named_array) + result_dynamic, result_static = jax.vmap( wrapped_fn, in_axes=(arg_axis_specs, kwarg_axis_specs), diff --git a/src/haliax/nn/dropout.py b/src/haliax/nn/dropout.py index 6a058ec..2a5f1f6 100644 --- a/src/haliax/nn/dropout.py +++ b/src/haliax/nn/dropout.py @@ -63,20 +63,23 @@ class Dropout(eqx.Module): # key difference from equinox: these are static fields pdrop: float = eqx.static_field() broadcast_axes: Optional[AxisSpec] = eqx.static_field() + inference: bool = False # note: not static def __init__( self, pdrop: float = 0.5, broadcast_axes: Optional[AxisSpec] = None, + inference: bool = False, ): self.pdrop = pdrop self.broadcast_axes = broadcast_axes + self.inference = inference def __call__( self, x: NamedArray, *, - inference: bool, + inference: Optional[bool] = None, key: Optional[PRNGKeyArray] = None, ) -> NamedArray: """**Arguments:** @@ -87,8 +90,10 @@ class Dropout(eqx.Module): - `inference`: As per [`equinox.nn.Dropout.__init__`][]. If `True` or `False` then it will take priority over `self.inference`. If `None` then the value from `self.inference` will be used. - - `deterministic`: Deprecated alternative to `inference`. """ + if inference is None: + inference = self.inference + return dropout( x, self.pdrop, diff --git a/src/haliax/nn/embedding.py b/src/haliax/nn/embedding.py index 649a91a..7a7c1fb 100644 --- a/src/haliax/nn/embedding.py +++ b/src/haliax/nn/embedding.py @@ -26,7 +26,7 @@ class Embedding(eqx.Module): return Embedding(weight=weight, Vocab=Vocab, Embed=Embed) @named_call - def __call__(self, input_ids, inference, *, key): + def __call__(self, input_ids, *, key: Optional[PRNGKeyArray] = None): return self.embed(input_ids) def embed(self, input_ids): diff --git a/src/haliax/partitioning.py b/src/haliax/partitioning.py index 72ee0de..10416e3 100644 --- a/src/haliax/partitioning.py +++ b/src/haliax/partitioning.py @@ -182,7 +182,7 @@ def infer_resource_partitions( else: sharding = NamedSharding(mesh, pspec_for_axis(node.axes, resource_mapping)) return NamedArray(sharding, node.axes) # type: ignore - else: + elif is_jax_array_like(node): sharding = getattr(node, "sharding", None) # TODO: these are usually replicated. Is there a better way to tell? if isinstance(sharding, SingleDeviceSharding): @@ -199,6 +199,8 @@ def infer_resource_partitions( # else: # return AUTO return NamedSharding(mesh, PartitionSpec(None)) + else: + return None return jax.tree_util.tree_map(partition_spec, tree, is_leaf=is_named_array) diff --git a/tests/test_hof.py b/tests/test_hof.py index 6577eb1..3923837 100644 --- a/tests/test_hof.py +++ b/tests/test_hof.py @@ -136,6 +136,27 @@ def test_vmap_unmapped_args(): assert selected.axes == expected_names +def test_vmap_non_static_bool_fields(): + Batch = Axis("Batch", 10) + Width = Axis("Width", 3) + Depth = Axis("Depth", 4) + named1 = hax.random.uniform(PRNGKey(0), (Width, Depth)) + + class Foo(eqx.Module): + field: NamedArray + flag: bool = False + + def __init__(self): + super().__init__() + self.field = named1 + self.flag = True + + vmap_foo = hax.vmap(Foo, Batch)() + + assert vmap_foo.field.axes == (Batch, Width, Depth) + assert vmap_foo.flag is True + + def test_vmap_mapped_args(): Batch = Axis("Batch", 10) Width = Axis("Width", 3) commit e47ddb8ab18adc5874e0333106c35e956fd3c88d Date: 2023-09-01T16:36:28-07:00 better support for the `inference` field in dropout (#30) * support key in `Linear` so we can lora dropout * don't cause returned non-array values in named_jit to turn into arrays * add is_active to Dropout so it's easy to check if we need to pass keys * fix tests diff --git a/src/haliax/nn/dropout.py b/src/haliax/nn/dropout.py index 2a5f1f6..ca0c233 100644 --- a/src/haliax/nn/dropout.py +++ b/src/haliax/nn/dropout.py @@ -75,6 +75,11 @@ class Dropout(eqx.Module): self.broadcast_axes = broadcast_axes self.inference = inference + @property + def is_active(self): + """Returns `True` if dropout is active (and therefore needs a key), `False` otherwise.""" + return not self.inference and self.pdrop > 0 + def __call__( self, x: NamedArray, diff --git a/src/haliax/nn/linear.py b/src/haliax/nn/linear.py index 01bf134..810daa3 100644 --- a/src/haliax/nn/linear.py +++ b/src/haliax/nn/linear.py @@ -36,7 +36,13 @@ class Linear(eqx.Module): return Linear(weight, bias, In, Out) @named_call - def __call__(self, inputs): + def __call__(self, inputs, *, key=None): + """ + Args: + inputs (NamedArray): Input array + key: Not used, but there for compat with other modules + """ + del key q = inputs.dot(self.In, self.weight) q = hax.auto_sharded(q) diff --git a/src/haliax/partitioning.py b/src/haliax/partitioning.py index 10416e3..99df59a 100644 --- a/src/haliax/partitioning.py +++ b/src/haliax/partitioning.py @@ -19,7 +19,7 @@ from jaxtyping import PyTree from .axis import Axis, AxisSelection, AxisSelector from .core import NamedArray -from .jax_utils import is_jax_array_like +from .jax_utils import Static, is_jax_array_like from .tree_util import hashable_combine, hashable_partition from .util import StringHolderEnum, ensure_tuple, is_named_array @@ -330,7 +330,10 @@ def named_jit( my_pjit_args["out_shardings"] = out_resources cached_pjitted_fun = _named_pjit_cache(fn, **my_pjit_args) - return cached_pjitted_fun(dynamic_donated, dynamic_reserved, static) + out, out_static = cached_pjitted_fun(dynamic_donated, dynamic_reserved, static) + out = hashable_combine(out, out_static.value) + + return out return f @@ -396,14 +399,26 @@ def _named_pjit_cache(fun_names, **jitkwargs): fun = hashable_combine(dynamic_fun, static_fun) args, kwargs = hashable_combine(dynamic_spec, static_spec) out = fun(*args, **kwargs) - return out + out_dynamic, out_static = hashable_partition(out, is_jax_array_like) + return out_dynamic, Static(out_static) fun_name, fun_qualname = fun_names fun_wrapped.__name__ = fun_name fun_wrapped.__qualname__ = fun_qualname + jitkwargs = dict(jitkwargs) + if "out_shardings" in jitkwargs: + out_shardings = jitkwargs["out_shardings"] + # None for the static + jitkwargs["out_shardings"] = (out_shardings, None) + # TODO: jit should work here, but there's a weird error. see if it goes away on its own - return pjit(fun_wrapped, donate_argnums=0, static_argnums=2, **jitkwargs) + return pjit( + fun_wrapped, + donate_argnums=0, + static_argnums=2, + **jitkwargs, + ) _eval_shape_cache = {} commit 38b1b53fd5f04dfe9283539c2220c3fbaf483cc7 Date: 2023-09-05T13:07:56-04:00 added implementation and tests for ravel function (#33) Co-authored-by: Rohan Mehta <rohanmehta@Rohans-MacBook-Air.local> diff --git a/src/haliax/__init__.py b/src/haliax/__init__.py index 9ee99dc..9ac54b6 100644 --- a/src/haliax/__init__.py +++ b/src/haliax/__init__.py @@ -22,6 +22,7 @@ from .core import ( flatten_axes, index, named, + ravel, rearrange, rename, roll, diff --git a/src/haliax/core.py b/src/haliax/core.py index 741e20d..cfc9ff4 100644 --- a/src/haliax/core.py +++ b/src/haliax/core.py @@ -229,6 +229,9 @@ class NamedArray: def unflatten_axis(self, axis: AxisSelector, new_axes: AxisSpec) -> "NamedArray": return haliax.unflatten_axis(self, axis=axis, new_axes=new_axes) + def ravel(self, new_axis_name: AxisSelector) -> "NamedArray": + return haliax.ravel(self, new_axis_name=new_axis_name) + def unbind(self, axis: AxisSelector) -> Sequence["NamedArray"]: return haliax.unbind(self, axis=axis) @@ -1199,6 +1202,14 @@ def unflatten_axis(array: NamedArray, axis: AxisSelector, new_axes: AxisSpec) -> return NamedArray(new_array, resolved_new_axes) +def ravel(array: NamedArray, new_axis_name: AxisSelector) -> NamedArray: + """ + Returns a flattened view of the array, with all axes merged into one + """ + flattened = flatten_axes(array, array.axes, new_axis_name) + return flattened + + def named(a: jnp.ndarray, axis: AxisSelection) -> NamedArray: """Creates a NamedArray from a numpy array and a list of axes.""" axes = check_shape(a.shape, axis) @@ -1471,6 +1482,7 @@ __all__ = [ "split", "flatten_axes", "unflatten_axis", + "ravel", "unbind", "roll", "_broadcast_order", diff --git a/tests/core_test.py b/tests/core_test.py index fd1147d..08ed94a 100644 --- a/tests/core_test.py +++ b/tests/core_test.py @@ -454,6 +454,19 @@ def test_unflatten_axis(): assert hax.unflatten_axis(flattened_HD, "Z", (H, D)).axes == (H, D, W) +def test_ravel(): + H = Axis("Height", 2) + W = Axis("Width", 3) + D = Axis("Depth", 4) + + named1 = hax.random.uniform(PRNGKey(0), (H, W, D)) + raveled = named1.ravel("Z") + + assert raveled.size == H.size * W.size * D.size + assert hax.all(hax.equal(raveled, named1.flatten_axes((H, W, D), "Z"))) + assert jnp.all(jnp.equal(raveled.array, jnp.ravel(named1.array))) + + def test_rename(): H = Axis("H", 2) W = Axis("W", 3) commit 202417941a678584c980b91abbce24c10f8f8d2a Date: 2023-09-07T22:16:43-07:00 `haliax.debug.diagnose_common_issues` (#34) * add haliax.debug.diagnose_common_problems * add haliax.debug.diagnose_common_problems diff --git a/docs/tips.md b/docs/tips.md new file mode 100644 index 0000000..f6d7ed2 --- /dev/null +++ b/docs/tips.md @@ -0,0 +1,11 @@ +# Tips and FAQ + +See also the [Equinox FAQ](https://docs.kidger.site/equinox/faq/) + +## Tip 1: `hax.debug.diagnose_common_issues` + +`hax.debug.diagnose_common_issues` is a function that will raise an exception if it detects problems with your module. +Currently, we diagnose: + +* Reuse of arrays or NamedArrays in a field. [Equinox modules must be trees.](https://docs.kidger.site/equinox/faq/#a-module-saved-in-two-places-has-become-two-independent-copies) +* Use of arrays or NamedArrays in a static field. Static data in JAX/Equinox must be hashable, and arrays are not hashable. diff --git a/src/haliax/__init__.py b/src/haliax/__init__.py index 9ac54b6..ab14ac8 100644 --- a/src/haliax/__init__.py +++ b/src/haliax/__init__.py @@ -5,6 +5,7 @@ import jax import jax.numpy as jnp from jax._src.typing import DTypeLike +import haliax.debug as debug import haliax.nn as nn import haliax.random as random import haliax.tree_util as tree_util @@ -809,6 +810,7 @@ concat_axis_specs = concat_axes __all__ = [ + "debug", "random", "tree_util", "nn", diff --git a/src/haliax/_src/__init__.py b/src/haliax/_src/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/src/haliax/_src/util.py b/src/haliax/_src/util.py new file mode 100644 index 0000000..79a10ad --- /dev/null +++ b/src/haliax/_src/util.py @@ -0,0 +1,55 @@ +from typing import Callable, MutableMapping, Sequence, Type, TypeVar + + +T = TypeVar("T") +py_slice = slice +slice_t = Type[slice] + + +def index_where(pred: Callable[[T], bool], xs: Sequence[T]) -> int: + for i, x in enumerate(xs): + if pred(x): + return i + raise ValueError("No element satisfies predicate") + + +class IdentityMap(MutableMapping): + """Map that compares keys by identity. + + This is a map that compares keys by identity instead of equality. It is + useful for storing objects that are not hashable or that should be compared + by identity. + + This is a mutable mapping, but it does not support the ``__hash__`` method + and therefore cannot be used as a dictionary key or as an element of another + set. + """ + + def __init__(self, iterable=None): + self._data = {} + if iterable is not None: + self.update(iterable) + + def __contains__(self, key): + return id(key) in self._data + + def __getitem__(self, key): + return self._data[id(key)][1] + + def __setitem__(self, key, value): + self._data[id(key)] = [key, value] + + def __delitem__(self, key): + del self._data[id(key)] + + def __iter__(self): + return (x[0] for x in self._data.values()) + + def __len__(self): + return len(self._data) + + def __repr__(self): + return f"IdentityMap({list(repr(x) for x in self._data.values())})" + + def __str__(self): + return f"IdentityMap({list(str(x) for x in self._data.values())})" diff --git a/src/haliax/axis.py b/src/haliax/axis.py index 5fcd8ad..84dcc0a 100644 --- a/src/haliax/axis.py +++ b/src/haliax/axis.py @@ -2,7 +2,9 @@ import typing from dataclasses import dataclass from typing import Dict, List, Mapping, Optional, Sequence, Tuple, Union, overload -from haliax.util import ensure_tuple, index_where +from haliax.util import ensure_tuple + +from ._src.util import index_where @dataclass(frozen=True) diff --git a/src/haliax/core.py b/src/haliax/core.py index cfc9ff4..e4426f4 100644 --- a/src/haliax/core.py +++ b/src/haliax/core.py @@ -14,8 +14,9 @@ import numpy as np import haliax import haliax.axis from haliax.jax_utils import is_jax_array_like -from haliax.util import ensure_tuple, index_where, py_slice, slice_t +from haliax.util import ensure_tuple +from ._src.util import index_where, py_slice, slice_t from .axis import Axis, AxisSelection, AxisSelector, AxisSpec, eliminate_axes, selects_axis, union_axes from .types import IntScalar, PrecisionLike, Scalar diff --git a/src/haliax/debug.py b/src/haliax/debug.py new file mode 100644 index 0000000..85820bd --- /dev/null +++ b/src/haliax/debug.py @@ -0,0 +1,119 @@ +import dataclasses +from typing import List, Tuple, Union + +import equinox as eqx +import jax.numpy as jnp +import jax.tree_util as jtu + +from haliax.core import NamedArray +from haliax.util import is_jax_or_hax_array_like + +from ._src.util import IdentityMap + + +ArrayLike = Union[jnp.ndarray, NamedArray] + + +def describe_array(arr): + if isinstance(arr, NamedArray): + return f"NamedArray(axes={arr.axes}, dtype={arr.dtype})" + else: + return f"ndarray(shape={arr.shape}, dtype={arr.dtype})" + + +class ModuleProblems(Exception): + def __init__(self): + self.reused_arrays: List[Tuple[ArrayLike, List]] = [] + self.static_arrays: List[str] = [] + + def __bool__(self): + return bool(self.reused_arrays or self.static_arrays) + + def __str__(self): + if not self: + return "No problems found" + else: + return "\n".join( + [ + "Found some problems with your module:", + *self._format_reused_arrays(), + *self._format_static_arrays(), + ] + ) + + def _format_reused_arrays(self): + return [f" Reused array {describe_array(arr)} at paths {paths}" for arr, paths in self.reused_arrays] + + def _format_static_arrays(self): + return [f" Static array at field {field}" for field in self.static_arrays] + + +def diagnose_common_issues(module: eqx.Module): + """ + Checks for common issues in a module, such as reused arrays and static arrays. + Equinox modules (and therefore Haliax modules) should not have arrays that are stored + in multiple places, and should not have arrays stored as static fields. + + We'll add more checks here as we find them. + + Args: + module: The module to check for problems + + Returns: + None + + Raises: + ModuleProblems: if any problems are found + + """ + + problems = ModuleProblems() + _check_for_reused_arrays(problems, module) + _check_for_static_arrays(problems, module) + + if problems: + raise problems + + # just in case we missed anything, raise equinox's errors: + eqx.tree_check(module) + + +def _check_for_reused_arrays(problems, module): + used_arrays = IdentityMap[ArrayLike, List[str]]() + + path_leaves, _ = jtu.tree_flatten_with_path(module, is_leaf=is_jax_or_hax_array_like) + + for path, leaf in path_leaves: + if is_jax_or_hax_array_like(leaf): + if leaf in used_arrays: + used_arrays[leaf].append(jtu.keystr(path)) + else: + used_arrays[leaf] = [jtu.keystr(path)] + + for arr, paths in used_arrays.items(): + if len(paths) > 1: + problems.reused_arrays.append((arr, paths)) + + +def _check_for_static_arrays(problems, module): + static_arrays = [] + + def recurse(module, path): + if isinstance(module, eqx.Module): + for field in dataclasses.fields(module): + value = getattr(module, field.name) + if field.metadata.get("static", False) and is_jax_or_hax_array_like(value): + static_arrays.append(f"{path}.{field.name}") + else: + recurse(value, f"{path}.{field.name}") + else: + leaves, _ = eqx.tree_flatten_one_level(module) + if leaves != [module]: + leaves_with_names = jtu.tree_leaves_with_path(module, is_leaf=lambda x: x in leaves) + for name, leaf in leaves_with_names: + recurse(leaf, f"{path}{name}") + + recurse(module, "") + + if static_arrays: + problems.static_arrays.extend(static_arrays) diff --git a/src/haliax/hof.py b/src/haliax/hof.py index 564c639..8df3ecf 100644 --- a/src/haliax/hof.py +++ b/src/haliax/hof.py @@ -8,11 +8,12 @@ import jax import jax.lax as lax from jaxtyping import PyTree +from ._src.util import index_where from .axis import Axis, AxisSelector, selects_axis from .core import NamedArray from .jax_utils import Static, broadcast_prefix, is_jax_array_like from .partitioning import physical_axis_name -from .util import index_where, is_jax_or_hax_array_like, is_named_array +from .util import is_jax_or_hax_array_like, is_named_array BoolAxisSpec = Union[bool, Callable[[Any], bool]] diff --git a/src/haliax/util.py b/src/haliax/util.py index 7badc03..83aa486 100644 --- a/src/haliax/util.py +++ b/src/haliax/util.py @@ -1,15 +1,10 @@ -from typing import Callable, Sequence, Tuple, Type, TypeAlias, TypeVar, Union +from typing import Sequence, Tuple, TypeAlias, TypeVar, Union from haliax.jax_utils import is_jax_array_like T = TypeVar("T") - -py_slice = slice - -slice_t = Type[slice] - Unspecified: TypeAlias = type("NotSpecified", (), {}) # type: ignore UNSPECIFIED = Unspecified() @@ -50,19 +45,9 @@ def is_jax_or_hax_array_like(x): return is_jax_array_like(x) or is_named_array(x) -def index_where(pred: Callable[[T], bool], xs: Sequence[T]) -> int: - for i, x in enumerate(xs): - if pred(x): - return i - raise ValueError("No element satisfies predicate") - - __all__ = [ "is_named_array", "ensure_tuple", "StringHolderEnum", "is_jax_or_hax_array_like", - "index_where", - "slice_t", - "py_slice", ] diff --git a/tests/test_debug.py b/tests/test_debug.py new file mode 100644 index 0000000..1d7867f --- /dev/null +++ b/tests/test_debug.py @@ -0,0 +1,96 @@ +import equinox as eqx +import jax.numpy as jnp +import pytest + +import haliax as hax + + +def test_diagnose_common_issues_repeated(): + class M(eqx.Module): + a: jnp.ndarray = eqx.field() + b: jnp.ndarray = eqx.field() + + def __init__(self): + super().__init__() + self.a = jnp.zeros(1) + self.b = self.a + + try: + hax.debug.diagnose_common_issues(M()) + pytest.fail("Should have raised an exception") + except hax.debug.ModuleProblems as e: + assert len(e.reused_arrays) == 1 + assert len(e.static_arrays) == 0 + + +def test_diagnose_common_issues_repeated_nested(): + class M(eqx.Module): + a: jnp.ndarray = eqx.field() + b: jnp.ndarray = eqx.field() + + def __init__(self): + super().__init__() + self.a = jnp.zeros(1) + self.b = self.a + + class N(eqx.Module): + m: M = eqx.field() + c: jnp.ndarray = eqx.field() + + def __init__(self): + super().__init__() + self.m = M() + self.c = self.m.a + + try: + hax.debug.diagnose_common_issues(N()) + pytest.fail("Should have raised an exception") + except hax.debug.ModuleProblems as e: + assert len(e.reused_arrays) == 1 + assert e.reused_arrays[0][1] == [".m.a", ".m.b", ".c"] + assert len(e.static_arrays) == 0 + + +def test_diagnose_common_issues_static(): + class M(eqx.Module): + a: jnp.ndarray = eqx.static_field() + b: hax.NamedArray = eqx.static_field() + + def __init__(self): + super().__init__() + self.a = jnp.zeros(1) + self.b = hax.named(jnp.zeros(3), "a") + + try: + hax.debug.diagnose_common_issues(M()) + pytest.fail("Should have raised an exception") + except hax.debug.ModuleProblems as e: + assert len(e.reused_arrays) == 0 + assert len(e.static_arrays) == 2 + + +def test_diagnose_common_issues_static_nested(): + class M(eqx.Module): + a: jnp.ndarray = eqx.static_field() + b: hax.NamedArray = eqx.static_field() + + def __init__(self): + super().__init__() + self.a = jnp.zeros(1) + self.b = hax.named(jnp.zeros(3), "a") + + class N(eqx.Module): + m: M = eqx.field() + c: jnp.ndarray = eqx.field() + + def __init__(self): + super().__init__() + self.m = M() + self.c = self.m.a + + try: + hax.debug.diagnose_common_issues(N()) + pytest.fail("Should have raised an exception") + except hax.debug.ModuleProblems as e: + assert len(e.reused_arrays) == 0 + assert len(e.static_arrays) == 2 commit 17c4fc2458229a75dc41017dd4d2f8ac546801b0 Date: 2023-09-09T00:59:12-04:00 added custom wrapper for jax.lax.top_k in new file (#38) * added custom wrapper for jax.lax.top_k in new file * addressed review; added option for user to rename new axis, or just resize by default * added top_k to __all__ --------- Co-authored-by: Rohan Mehta <rohanmehta@Rohans-MacBook-Air.local> diff --git a/src/haliax/__init__.py b/src/haliax/__init__.py index ab14ac8..cd8b40e 100644 --- a/src/haliax/__init__.py +++ b/src/haliax/__init__.py @@ -37,6 +37,7 @@ from .core import ( from .hof import fold, map, scan, vmap from .ops import clip, isclose, pad_left, trace, tril, triu, where from .partitioning import auto_sharded, axis_mapping, fsdp, named_jit, shard_with_axis_mapping +from .specialized_fns import top_k from .types import Scalar from .wrap import ( ReductionFunction, @@ -978,4 +979,5 @@ __all__ = [ "selects_axis", "concat_axes", "concat_axis_specs", + "top_k", ] diff --git a/src/haliax/specialized_fns.py b/src/haliax/specialized_fns.py new file mode 100644 index 0000000..ec1008c --- /dev/null +++ b/src/haliax/specialized_fns.py @@ -0,0 +1,25 @@ +from typing import Optional + +import jax +import jax.numpy as jnp + +from .axis import Axis, AxisSelector +from .core import NamedArray + + +def top_k(arr: NamedArray, axis: AxisSelector, k: int, new_axis: Optional[AxisSelector] = None) -> NamedArray: + pos = arr._lookup_indices(axis) + if pos is None: + raise ValueError(f"Axis {axis} not found in {arr}") + new_array = jnp.moveaxis(arr.array, pos, -1) # move axis to the last position + values, _ = jax.lax.top_k(new_array, k=k) + values = jnp.moveaxis(values, -1, pos) # move axis back to its original position + + if new_axis is None: + axis = arr.resolve_axis(axis) + new_axis = axis.resize(k) + elif isinstance(new_axis, str): + new_axis = Axis(new_axis, k) + + updated_axes = arr.axes[:pos] + (new_axis,) + arr.axes[pos + 1 :] + return NamedArray(values, updated_axes) diff --git a/tests/test_specialized_fns.py b/tests/test_specialized_fns.py new file mode 100644 index 0000000..0e9c5a3 --- /dev/null +++ b/tests/test_specialized_fns.py @@ -0,0 +1,25 @@ +import jax +import jax.numpy as jnp + +import haliax.specialized_fns as hfns +from haliax import Axis, NamedArray + + +def test_top_k(): + H = Axis("H", 5) + W = Axis("W", 6) + D = Axis("D", 7) + + rand = jax.random.uniform(jax.random.PRNGKey(0), (H.size, W.size, D.size)) + n_rand = NamedArray(rand, (H, W, D)) + + assert hfns.top_k(n_rand, D, 2).array.shape == (H.size, W.size, 2) + assert jnp.all( + jnp.equal(jax.lax.top_k(rand, 2)[0], hfns.top_k(n_rand, D, 2).array) + ) # test that selecting last axis is same as default + + for idx, i in enumerate(n_rand.axes): # then test selecting all axes + t = jnp.transpose(rand, (*range(idx), *range(idx + 1, len(n_rand.axes)), idx)) + t = jax.lax.top_k(t, 2)[0] + t = jnp.moveaxis(t, -1, idx) + assert jnp.all(jnp.equal(t, hfns.top_k(n_rand, i, 2).array)) commit 9ef0db58c59f40196b0f2973a0760c6b99540018 Date: 2023-09-19T13:07:54-07:00 Lowerable Named Jit (#39) * refactor named_jit to support lower * typo * update jax version * oops * make private diff --git a/.github/workflows/run_tests.yaml b/.github/workflows/run_tests.yaml index ab1b9f8..1e43042 100644 --- a/.github/workflows/run_tests.yaml +++ b/.github/workflows/run_tests.yaml @@ -20,7 +20,7 @@ jobs: run: | python -m pip install --upgrade pip pip install flake8 pytest - pip install --upgrade "jax[cpu]==0.4.11" "jaxlib[cpu]==0.4.11" + pip install --upgrade "jax[cpu]==0.4.14" "jaxlib[cpu]==0.4.14" pip install . # - name: Lint with flake8 # run: | diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml index 1a53e46..7a18c75 100644 --- a/.pre-commit-config.yaml +++ b/.pre-commit-config.yaml @@ -33,7 +33,7 @@ repos: additional_dependencies: [flake8-isort] - repo: https://github.com/pre-commit/mirrors-mypy - rev: 'v0.960' + rev: 'v1.5.1' hooks: - id: mypy args: [--ignore-missing-imports] diff --git a/src/haliax/core.py b/src/haliax/core.py index e4426f4..cd77aaa 100644 --- a/src/haliax/core.py +++ b/src/haliax/core.py @@ -399,7 +399,7 @@ class NamedArray: where=where, ) - def ptp(self, axis: AxisSelection = None) -> "NamedArray": + def ptp(self, axis: Optional[AxisSelection] = None) -> "NamedArray": return haliax.ptp(self, axis=axis) # TODO: implement ravel. Can only do if we either ask for an axis or add ProductAxis or something diff --git a/src/haliax/nn/embedding.py b/src/haliax/nn/embedding.py index 7a7c1fb..561c10f 100644 --- a/src/haliax/nn/embedding.py +++ b/src/haliax/nn/embedding.py @@ -38,4 +38,4 @@ class Embedding(eqx.Module): def resize_embeddings(self, new_size: int, key: Optional[PRNGKeyArray] = None): new_weights = resize_axis(self.weight, self.Vocab, new_size, key=key) - return dataclasses.replace(self, Vocab=self.Vocab.resize(new_size), weight=new_weights) + return dataclasses.replace(self, Vocab=self.Vocab.resize(new_size), weight=new_weights) # type: ignore diff --git a/src/haliax/partitioning.py b/src/haliax/partitioning.py index 99df59a..0aaf1b7 100644 --- a/src/haliax/partitioning.py +++ b/src/haliax/partitioning.py @@ -3,10 +3,11 @@ import functools import threading import typing from math import prod -from typing import Callable, Mapping, Optional, Sequence, TypeVar, Union +from typing import Callable, Mapping, Optional, ParamSpec, Sequence, TypeVar, Union import equinox as eqx import jax +from equinox import Module, module_update_wrapper # TODO: avoid depending on private Equinox internals. from equinox._compile_utils import compile_cache @@ -29,6 +30,8 @@ ResourceMapping = Mapping[(str), PhysicalAxisSpec] """Mapping from logical axis names to physical axis names""" F = typing.TypeVar("F", bound=typing.Callable) +Args = ParamSpec("Args") +R = typing.TypeVar("R", covariant=True) class ResourceAxis(StringHolderEnum): @@ -205,77 +208,55 @@ def infer_resource_partitions( return jax.tree_util.tree_map(partition_spec, tree, is_leaf=is_named_array) -def named_jit( - fn: Callable = None, - axis_resources: Optional[ResourceMapping] = None, - *, - in_axis_resources: Optional[ResourceMapping] = None, - out_axis_resources: Optional[ResourceMapping] = None, - donate_args: Optional[PyTree] = None, - donate_kwargs: Optional[PyTree] = None, - **pjit_args, -): +class WrappedCallable(typing.Protocol[Args, R]): + """ + A wrapper for a callable that preserves the original function's name and qualname. """ - A version of pjit that uses NamedArrays and the provided resource mapping to infer resource partitions for - sharded computation for. - - `axis_resources` will be used for a context-specific resource mapping when the function is invoked. - In addition, if in_axis_resources is not provided, the arguments' own (pre-existing) shardings will be used as the in_axis_resources. - If out_axis_resources is not provided, axis_resources will be used as the out_axis_resources. - If no resource mapping is provided, this function attempts to use the context resource mapping. + def __call__(self, *args: Args.args, **kwargs: Args.kwargs) -> R: + raise NotImplementedError - Functionally this is very similar to something like: + def lower(self, *args: Args.args, **kwargs: Args.kwargs) -> jax.stages.Lowered: + raise NotImplementedError - ```python - arg = hax.shard_with_axis_mapping(arg, in_axis_resources) - with hax.axis_mapping(axis_resources): - result = jax.jit(fn, **pjit_args)(arg) - result = hax.shard_with_axis_mapping(result, out_axis_resources) - return result - ``` - Args: - fn (Callable, optional): The function to be jit'd. - axis_resources (ResourceMapping, optional): A mapping from logical axis names to physical axis names use for th - e context-specific resource mapping. - in_axis_resources (ResourceMapping, optional): A mapping from logical axis names to physical axis names for - arguments. If not passed, it uses the argument's own shardings. - out_axis_resources (ResourceMapping, optional): A mapping from logical axis names to physical axis names for the - result, defaults to axis_resources. - donate_args (PyTree, optional): A PyTree of booleans or function leaf->bool, indicating if the arguments should - be donated to the computation. - donate_kwargs (PyTree, optional): A PyTree of booleans or function leaf->bool, indication if the keyword - arguments should be donated to the computation. +class _NamedJitWrapper(Module): + _fn: Callable # [Args, R] + _dynamic_fun: PyTree + _static_fun: typing.Any + _axis_resources: Optional[ResourceMapping] + _in_axis_resources: Optional[ResourceMapping] + _out_axis_resources: Optional[ResourceMapping] + _donate_args: Optional[PyTree] + _donate_kwargs: Optional[PyTree] + _pjit_args: Mapping[str, typing.Any] - Returns: - A jit'd version of the function. - """ + @property + def __wrapped__(self): + return self._fn - if fn is None: - return functools.partial( - named_jit, - axis_resources=axis_resources, - in_axis_resources=in_axis_resources, - out_axis_resources=out_axis_resources, - donate_args=donate_args, - donate_kwargs=donate_kwargs, - **pjit_args, - ) + def __call__(self, *args, **kwargs): + return self._call(False, *args, **kwargs) - @functools.wraps(fn) - def f(*args, **kwargs): - nonlocal axis_resources, in_axis_resources, out_axis_resources, donate_args, donate_kwargs + def lower(self, *args, **kwargs) -> jax.stages.Lowered: + return self._call(True, *args, **kwargs) + def _call(self, is_lower, *args, **kwargs): + axis_resources = self._axis_resources if axis_resources is None: axis_resources = current_thread_local_mapping() + in_axis_resources = self._in_axis_resources + out_axis_resources = self._out_axis_resources + if out_axis_resources is None: out_axis_resources = axis_resources - dynamic_fun, static_fun = hashable_partition(fn, is_jax_array_like) dynamic_argspec, static_argspec = hashable_partition((args, kwargs), is_jax_array_like) - dynamic = (dynamic_fun, dynamic_argspec) + dynamic = (self._dynamic_fun, dynamic_argspec) + + donate_args = self._donate_args + donate_kwargs = self._donate_kwargs if donate_args is not None or donate_kwargs is not None: if donate_args is None: @@ -300,7 +281,7 @@ def named_jit( dynamic_donated = jax.tree_util.tree_map(lambda _: None, dynamic) dynamic_reserved = dynamic - static = (static_fun, static_argspec) + static = (self._static_fun, static_argspec) if axis_resources is not None: cmanager = axis_mapping(axis_resources) @@ -308,11 +289,12 @@ def named_jit( cmanager = contextlib.nullcontext() with cmanager: - output_shape = _cached_filter_eval_shape(fn, *args, **kwargs) + output_shape = _cached_filter_eval_shape(self._fn, *args, **kwargs) # TODO: with new jax.Array I shouldn't have to specify shardings, but I do for now # https://github.com/google/jax/issues/15600 # we don't really need in_shardings though - my_pjit_args = dict(**pjit_args) + + my_pjit_args = dict(**self._pjit_args) if in_axis_resources is not None or axis_resources is not None: if in_axis_resources is None: @@ -329,13 +311,89 @@ def named_jit( out_resources = infer_resource_partitions(output_shape, out_axis_resources, use_auto_sharding=False) my_pjit_args["out_shardings"] = out_resources - cached_pjitted_fun = _named_pjit_cache(fn, **my_pjit_args) - out, out_static = cached_pjitted_fun(dynamic_donated, dynamic_reserved, static) - out = hashable_combine(out, out_static.value) + cached_pjitted_fun = _named_pjit_cache(self._fn, **my_pjit_args) + if is_lower: + return cached_pjitted_fun.lower(dynamic_donated, dynamic_reserved, static) + else: + out, out_static = cached_pjitted_fun(dynamic_donated, dynamic_reserved, static) + out = hashable_combine(out, out_static.value) + + return out + - return out +def named_jit( + fn: Optional[Callable[Args, R]] = None, + axis_resources: Optional[ResourceMapping] = None, + *, + in_axis_resources: Optional[ResourceMapping] = None, + out_axis_resources: Optional[ResourceMapping] = None, + donate_args: Optional[PyTree] = None, + donate_kwargs: Optional[PyTree] = None, + **pjit_args, +) -> WrappedCallable[Args, R]: + """ + A version of pjit that uses NamedArrays and the provided resource mapping to infer resource partitions for + sharded computation for. + + `axis_resources` will be used for a context-specific resource mapping when the function is invoked. + In addition, if in_axis_resources is not provided, the arguments' own (pre-existing) shardings will be used as the in_axis_resources. + If out_axis_resources is not provided, axis_resources will be used as the out_axis_resources. + + If no resource mapping is provided, this function attempts to use the context resource mapping. + + Functionally this is very similar to something like: + + ```python + arg = hax.shard_with_axis_mapping(arg, in_axis_resources) + with hax.axis_mapping(axis_resources): + result = jax.jit(fn, **pjit_args)(arg) + result = hax.shard_with_axis_mapping(result, out_axis_resources) + return result + ``` + + Args: + fn (Callable, optional): The function to be jit'd. + axis_resources (ResourceMapping, optional): A mapping from logical axis names to physical axis names use for + the context-specific resource mapping. + in_axis_resources (ResourceMapping, optional): A mapping from logical axis names to physical axis names for + arguments. If not passed, it uses the argument's own shardings. + out_axis_resources (ResourceMapping, optional): A mapping from logical axis names to physical axis names for the + result, defaults to axis_resources. + donate_args (PyTree, optional): A PyTree of booleans or function leaf->bool, indicating if the arguments should + be donated to the computation. + donate_kwargs (PyTree, optional): A PyTree of booleans or function leaf->bool, indication if the keyword + arguments should be donated to the computation. + + Returns: + A jit'd version of the function. + """ + + if fn is None: + return functools.partial( # type: ignore + named_jit, + axis_resources=axis_resources, + in_axis_resources=in_axis_resources, + out_axis_resources=out_axis_resources, + donate_args=donate_args, + donate_kwargs=donate_kwargs, + **pjit_args, + ) + + dynamic_fun, static_fun = hashable_partition(fn, is_jax_array_like) + + wrapper = _NamedJitWrapper( + fn, + dynamic_fun, + static_fun, + axis_resources, + in_axis_resources, + out_axis_resources, + donate_args, + donate_kwargs, + pjit_args, + ) - return f + return module_update_wrapper(wrapper, fn) # type: ignore @typing.overload @@ -390,7 +448,7 @@ def _fsdp_impl(fn: F, parameter_mapping, compute_mapping): # returns. This is useful for conserving memory, but we also have to splice them back in. # Also recall that a "pytree" can split into leaves and a "treedef", which can then be reconstructed. @compile_cache -def _named_pjit_cache(fun_names, **jitkwargs): +def _named_pjit_cache(fun_names, **jitkwargs) -> WrappedCallable: def fun_wrapped(dynamic_donated, dynamic_reserved, static): dynamic = eqx.combine(dynamic_donated, dynamic_reserved) dynamic_fun, dynamic_spec = dynamic diff --git a/tests/test_partitioning.py b/tests/test_partitioning.py index da9b470..6e9e747 100644 --- a/tests/test_partitioning.py +++ b/tests/test_partitioning.py @@ -257,3 +257,26 @@ def test_named_jit_with_donation_nested_pytrees(): with Mesh(np.array(devices).reshape(-1, 1), (ResourceAxis.DATA, ResourceAxis.MODEL)): mod = named_jit(init, donate_args=(True, False))(jnp.zeros((8, 8)), jnp.zeros((8, 16))) assert mod.mod.array.sharding.is_fully_replicated + + +def test_jit_lower_doesnt_blow_up(): + with ((axis_mapping(resource_map))): + + class MyModule(eqx.Module): + array: jnp.ndarray + array2: jnp.ndarray + + class MyModule2(eqx.Module): + mod: MyModule + mod2: MyModule + + def init(a1, a2): + return MyModule2(MyModule(a1, a2), MyModule(a1, a2)) + + devices = jax.devices() + with Mesh(np.array(devices).reshape(-1, 1), (ResourceAxis.DATA, ResourceAxis.MODEL)): + jit_init = named_jit(init, donate_args=(True, False)) + lowered = jit_init.lower(jnp.zeros((8, 8)), jnp.zeros((8, 16))) + assert lowered + lowered.cost_analysis() + lowered.as_text() commit bfa98afeaef9be7298aa265f1768a7bae516d2fa Date: 2023-09-19T14:04:44-07:00 add safe_wraps for wrapping fns or Modules (#40) diff --git a/src/haliax/partitioning.py b/src/haliax/partitioning.py index 0aaf1b7..d398c9b 100644 --- a/src/haliax/partitioning.py +++ b/src/haliax/partitioning.py @@ -7,7 +7,7 @@ from typing import Callable, Mapping, Optional, ParamSpec, Sequence, TypeVar, Un import equinox as eqx import jax -from equinox import Module, module_update_wrapper +from equinox import module_update_wrapper # TODO: avoid depending on private Equinox internals. from equinox._compile_utils import compile_cache @@ -220,7 +220,7 @@ class WrappedCallable(typing.Protocol[Args, R]): raise NotImplementedError -class _NamedJitWrapper(Module): +class _NamedJitWrapper(eqx.Module): _fn: Callable # [Args, R] _dynamic_fun: PyTree _static_fun: typing.Any diff --git a/src/haliax/util.py b/src/haliax/util.py index 83aa486..a4d75d9 100644 --- a/src/haliax/util.py +++ b/src/haliax/util.py @@ -1,5 +1,8 @@ +import functools from typing import Sequence, Tuple, TypeAlias, TypeVar, Union +import equinox + from haliax.jax_utils import is_jax_array_like @@ -45,6 +48,34 @@ def is_jax_or_hax_array_like(x): return is_jax_array_like(x) or is_named_array(x) +def safe_wraps(fn): + """ + Equinox has a special [equinox.module_update_wrapper][] that works with [equinox.Module][]s, but + doesn't work with regular functions. Likewise, functools.update_wrapper doesn't work with [equinox.Module][]s. + + This function is a wrapper around both of them that works with both [equinox.Module][]s and regular functions. + + Use this if you get this exception: `dataclasses.FrozenInstanceError: cannot assign to field '__module__'` + """ + return functools.partial(safe_update_wrapper, wrapped=fn) + + +def safe_update_wrapper(wrapper, wrapped): + """ + As [safe_wraps][] but not a decorator. + Args: + wrapper: + wrapped: + + Returns: + + """ + if isinstance(wrapper, equinox.Module): + return equinox.module_update_wrapper(wrapper, wrapped) + else: + return functools.update_wrapper(wrapper, wrapped) + + __all__ = [ "is_named_array", "ensure_tuple", commit 0ae14ba0c1b4694626e88027af5dc6fc63aefc03 Date: 2023-09-21T11:40:56-07:00 fix tests for latest jax diff --git a/tests/core_test.py b/tests/core_test.py index 08ed94a..db5c954 100644 --- a/tests/core_test.py +++ b/tests/core_test.py @@ -265,18 +265,18 @@ def test_take_overlapping_2(): loss = cross_entropy(logits, labels) assert loss.axes == (Batch, Block) - assert jnp.alltrue(loss.array == jnp.take_along_axis(logits.array, labels.array[..., None], axis=-1)[..., 0]) + assert jnp.all(loss.array == jnp.take_along_axis(logits.array, labels.array[..., None], axis=-1)[..., 0]) logits = hax.random.uniform(PRNGKey(0), (Batch, Embed, Block)) loss = cross_entropy(logits, labels) assert loss.axes == (Batch, Block) - assert jnp.alltrue(loss.array == jnp.take_along_axis(logits.array, labels.array[..., None, :], axis=-2)[..., 0, :]) + assert jnp.all(loss.array == jnp.take_along_axis(logits.array, labels.array[..., None, :], axis=-2)[..., 0, :]) index = hax.random.randint(PRNGKey(0), (Block, Batch), 0, Embed.size) loss = cross_entropy(logits, index) assert loss.axes == (Batch, Block) - assert jnp.alltrue( + assert jnp.all( loss.array == jnp.take_along_axis(logits.array, index.array.transpose()[..., None, :], axis=-2)[..., 0, :] ) @@ -662,17 +662,17 @@ def test_slice_old_style(): named1 = hax.random.randint(PRNGKey(0), (H, W, D), minval=0, maxval=10) - assert jnp.alltrue(named1.slice("H", start=4, length=2).array == named1.array[4:6, :, :]) - assert jnp.alltrue(named1.slice("W", start=4, length=2).array == named1.array[:, 4:6, :]) - assert jnp.alltrue(named1.slice("D", start=4, length=2).array == named1.array[:, :, 4:6]) + assert jnp.all(named1.slice("H", start=4, length=2).array == named1.array[4:6, :, :]) + assert jnp.all(named1.slice("W", start=4, length=2).array == named1.array[:, 4:6, :]) + assert jnp.all(named1.slice("D", start=4, length=2).array == named1.array[:, :, 4:6]) H2 = Axis("H2", 5) W2 = Axis("W2", 10) D2 = Axis("D2", 15) - assert jnp.alltrue(named1.slice("H", H2, start=4).array == named1.array[4 : 4 + H2.size, :, :]) - assert jnp.alltrue(named1.slice("W", W2, start=4).array == named1.array[:, 4 : 4 + W2.size, :]) - assert jnp.alltrue(named1.slice("D", D2, start=4).array == named1.array[:, :, 4 : 4 + D2.size]) + assert jnp.all(named1.slice("H", H2, start=4).array == named1.array[4 : 4 + H2.size, :, :]) + assert jnp.all(named1.slice("W", W2, start=4).array == named1.array[:, 4 : 4 + W2.size, :]) + assert jnp.all(named1.slice("D", D2, start=4).array == named1.array[:, :, 4 : 4 + D2.size]) def test_slice_new_style(): @@ -683,7 +683,7 @@ def test_slice_new_style(): named1 = hax.random.randint(PRNGKey(0), (H, W, D), minval=0, maxval=10) x1 = named1.slice({"H": 4, "W": 5, "D": 7}, length={"H": 2, "W": 3, "D": 4}) - assert jnp.alltrue(x1.array == named1.array[4:6, 5:8, 7:11]) + assert jnp.all(x1.array == named1.array[4:6, 5:8, 7:11]) with pytest.raises(TypeError): named1.slice({"H": 4, "W": 5, "D": 7}, length={"H": 2, "W": 3, "D": 4}, start={"H": 1, "W": 2, "D": 3}) @@ -696,7 +696,7 @@ def test_slice_new_style(): D2 = Axis("D2", 15) x2 = named1.slice({"H": 4, "W": 5, "D": 7}, length={"H": H2, "W": W2, "D": D2}) - assert jnp.alltrue(x2.array == named1.array[4 : 4 + H2.size, 5 : 5 + W2.size, 7 : 7 + D2.size]) + assert jnp.all(x2.array == named1.array[4 : 4 + H2.size, 5 : 5 + W2.size, 7 : 7 + D2.size]) def test_updated_slice(): @@ -714,16 +714,16 @@ def test_updated_slice(): named1_updated = named1.updated_slice({"H": 0, "W": 0, "D": 0}, named2) assert named1_updated.axes == named1.axes - assert jnp.alltrue(named1_updated["H", 0 : H2.size, "W", 0 : W2.size, "D", 0 : D2.size].array == named2.array) + assert jnp.all(named1_updated["H", 0 : H2.size, "W", 0 : W2.size, "D", 0 : D2.size].array == named2.array) # test broadcasting for pair in [(H2, D2), (H2, W2), (W2, D2), (D2, H2), (D2, W2), (W2, H2)]: n3 = hax.random.randint(PRNGKey(0), pair, minval=10, maxval=30) named1_updated = named1.updated_slice({ax.name: 0 for ax in pair}, n3) assert named1_updated.axes == named1.axes - assert jnp.alltrue((named1_updated[{ax.name: slice(0, ax.size) for ax in pair}] == n3).array) + assert jnp.all((named1_updated[{ax.name: slice(0, ax.size) for ax in pair}] == n3).array) # check that the array outside the slice is unchanged - assert jnp.alltrue( + assert jnp.all( ( named1_updated[{ax.name: slice(ax.size, None) for ax in pair}] == named1[{ax.name: slice(ax.size, None) for ax in pair}] commit 47d23199e0714c86c30d09f60ee4adf3fcd48eac Date: 2023-09-21T11:42:06-07:00 switch to int/float instead of np.float_ etc diff --git a/src/haliax/random.py b/src/haliax/random.py index 486cb02..b4893f5 100644 --- a/src/haliax/random.py +++ b/src/haliax/random.py @@ -5,7 +5,6 @@ import warnings from typing import Optional import jax -import jax.numpy as jnp import jax.random as jrandom import haliax @@ -19,7 +18,7 @@ from .partitioning import auto_sharded, physical_axis_name, physical_axis_size, @named_call def uniform( - key, shape: AxisSpec, dtype=jnp.float_, minval: NamedOrNumeric = 0.0, maxval: NamedOrNumeric = 1.0 + key, shape: AxisSpec, dtype=float, minval: NamedOrNumeric = 0.0, maxval: NamedOrNumeric = 1.0 ) -> NamedArray: shape = ensure_tuple(shape) minval = broadcast_to(minval, shape).array @@ -30,7 +29,7 @@ def uniform( @named_call -def normal(key, shape: AxisSpec, dtype=jnp.float_): +def normal(key, shape: AxisSpec, dtype=float): shape = ensure_tuple(shape) jax_shape = _to_jax_shape(shape) jax_array = jrandom.normal(key=key, shape=jax_shape, dtype=dtype) @@ -47,7 +46,7 @@ def bernoulli(key, shape: AxisSpec, p: NamedOrNumeric): @named_call -def randint(key, shape: AxisSpec, minval: NamedOrNumeric, maxval: NamedOrNumeric, dtype=jnp.int_): +def randint(key, shape: AxisSpec, minval: NamedOrNumeric, maxval: NamedOrNumeric, dtype=int): shape = ensure_tuple(shape) minval = broadcast_to(minval, shape).array maxval = broadcast_to(maxval, shape).array @@ -57,7 +56,7 @@ def randint(key, shape: AxisSpec, minval: NamedOrNumeric, maxval: NamedOrNumeric @named_call -def poisson(key, shape: AxisSpec, lam: NamedOrNumeric, dtype=jnp.int_): +def poisson(key, shape: AxisSpec, lam: NamedOrNumeric, dtype=int): shape = ensure_tuple(shape) lam = broadcast_to(lam, shape).array jax_shape = _to_jax_shape(shape) @@ -66,7 +65,7 @@ def poisson(key, shape: AxisSpec, lam: NamedOrNumeric, dtype=jnp.int_): @named_call -def exponential(key, shape: AxisSpec, dtype=jnp.float_): +def exponential(key, shape: AxisSpec, dtype=float): shape = ensure_tuple(shape) jax_shape = _to_jax_shape(shape) jax_array = jrandom.exponential(key=key, shape=jax_shape, dtype=dtype) @@ -74,7 +73,7 @@ def exponential(key, shape: AxisSpec, dtype=jnp.float_): @named_call -def gamma(key, shape: AxisSpec, a: NamedOrNumeric, dtype=jnp.float_): +def gamma(key, shape: AxisSpec, a: NamedOrNumeric, dtype=float): shape = ensure_tuple(shape) a = broadcast_to(a, shape).array jax_shape = _to_jax_shape(shape) @@ -83,7 +82,7 @@ def gamma(key, shape: AxisSpec, a: NamedOrNumeric, dtype=jnp.float_): @named_call -def beta(key, shape: AxisSpec, a: NamedOrNumeric, b: NamedOrNumeric, dtype=jnp.float_): +def beta(key, shape: AxisSpec, a: NamedOrNumeric, b: NamedOrNumeric, dtype=float): shape = ensure_tuple(shape) a = broadcast_to(a, shape).array b = broadcast_to(b, shape).array @@ -93,7 +92,7 @@ def beta(key, shape: AxisSpec, a: NamedOrNumeric, b: NamedOrNumeric, dtype=jnp.f @named_call -def laplace(key, shape: AxisSpec, dtype=jnp.float_): +def laplace(key, shape: AxisSpec, dtype=float): shape = ensure_tuple(shape) jax_shape = _to_jax_shape(shape) jax_array = jrandom.laplace(key=key, shape=jax_shape, dtype=dtype) @@ -101,7 +100,7 @@ def laplace(key, shape: AxisSpec, dtype=jnp.float_): @named_call -def cauchy(key, shape: AxisSpec, dtype=jnp.float_): +def cauchy(key, shape: AxisSpec, dtype=float): shape = ensure_tuple(shape) jax_shape = _to_jax_shape(shape) jax_array = jrandom.cauchy(key=key, shape=jax_shape, dtype=dtype) @@ -109,7 +108,7 @@ def cauchy(key, shape: AxisSpec, dtype=jnp.float_): @named_call -def logistic(key, shape: AxisSpec, dtype=jnp.float_): +def logistic(key, shape: AxisSpec, dtype=float): shape = ensure_tuple(shape) jax_shape = _to_jax_shape(shape) jax_array = jrandom.logistic(key=key, shape=jax_shape, dtype=dtype) @@ -117,7 +116,7 @@ def logistic(key, shape: AxisSpec, dtype=jnp.float_): @named_call -def truncated_normal(key, shape: AxisSpec, lower: NamedOrNumeric, upper: NamedOrNumeric, dtype=jnp.float_): +def truncated_normal(key, shape: AxisSpec, lower: NamedOrNumeric, upper: NamedOrNumeric, dtype=float): shape = ensure_tuple(shape) lower = broadcast_to(lower, shape).array upper = broadcast_to(upper, shape).array @@ -200,7 +199,7 @@ def generate_sharded(fn, axis: Optional[AxisSelector] = None): @named_call -def ball(key, shape: AxisSpec, D: Axis, p: float = 2.0, dtype=jnp.float_): +def ball(key, shape: AxisSpec, D: Axis, p: float = 2.0, dtype=float): shape = ensure_tuple(shape) jax_shape = _to_jax_shape(shape) jax_array = jrandom.ball(key=key, shape=jax_shape, d=D.size, p=p, dtype=dtype) @@ -272,7 +271,7 @@ def categorical(key, logits: NamedArray, axis: AxisSelector, shape: Optional[Axi @named_call -def gumbel(key, shape: AxisSpec, dtype=jnp.float_): +def gumbel(key, shape: AxisSpec, dtype=float): shape = ensure_tuple(shape) jax_shape = _to_jax_shape(shape) jax_array = jrandom.gumbel(key, jax_shape, dtype=dtype) @@ -287,7 +286,7 @@ def permutation(key, x: NamedArray, axis: AxisSelector, independent: bool = Fals @named_call -def rademacher(key, shape: AxisSpec, dtype=jnp.float_): +def rademacher(key, shape: AxisSpec, dtype=float): shape = ensure_tuple(shape) jax_shape = _to_jax_shape(shape) jax_array = jrandom.rademacher(key, jax_shape, dtype=dtype) @@ -295,7 +294,7 @@ def rademacher(key, shape: AxisSpec, dtype=jnp.float_): @named_call -def t(key, shape: AxisSpec, df: NamedOrNumeric, dtype=jnp.float_): +def t(key, shape: AxisSpec, df: NamedOrNumeric, dtype=float): shape = ensure_tuple(shape) df = broadcast_to(df, shape) jax_shape = _to_jax_shape(shape) @@ -304,7 +303,7 @@ def t(key, shape: AxisSpec, df: NamedOrNumeric, dtype=jnp.float_): @named_call -def weibull_min(key, shape: AxisSpec, scale: NamedOrNumeric, concentration: NamedOrNumeric, dtype=jnp.float_): +def weibull_min(key, shape: AxisSpec, scale: NamedOrNumeric, concentration: NamedOrNumeric, dtype=float): shape = ensure_tuple(shape) scale = broadcast_to(scale, shape) concentration = broadcast_to(concentration, shape) @@ -314,7 +313,7 @@ def weibull_min(key, shape: AxisSpec, scale: NamedOrNumeric, concentration: Name @named_call -def pareto(key, shape: AxisSpec, b: NamedOrNumeric, dtype=jnp.float_): +def pareto(key, shape: AxisSpec, b: NamedOrNumeric, dtype=float): shape = ensure_tuple(shape) b = broadcast_to(b, shape) jax_shape = _to_jax_shape(shape) @@ -323,7 +322,7 @@ def pareto(key, shape: AxisSpec, b: NamedOrNumeric, dtype=jnp.float_): @named_call -def loggamma(key, shape: AxisSpec, a: NamedOrNumeric, dtype=jnp.float_): +def loggamma(key, shape: AxisSpec, a: NamedOrNumeric, dtype=float): shape = ensure_tuple(shape) a = broadcast_to(a, shape) jax_shape = _to_jax_shape(shape) commit 4dcedb0b0c7a58e5d4766fd97071c152f47b6e93 Date: 2023-09-21T11:45:02-07:00 more doc for topk diff --git a/src/haliax/specialized_fns.py b/src/haliax/specialized_fns.py index ec1008c..263ed37 100644 --- a/src/haliax/specialized_fns.py +++ b/src/haliax/specialized_fns.py @@ -8,6 +8,17 @@ from .core import NamedArray def top_k(arr: NamedArray, axis: AxisSelector, k: int, new_axis: Optional[AxisSelector] = None) -> NamedArray: + """ + Select the top k elements along the given axis. + Args: + arr (NamedArray): array to select from + axis (AxisSelector): axis to select from + k (int): number of elements to select + new_axis (Optional[AxisSelector]): new axis name, if none, the original axis will be resized to k + + Returns: + NamedArray: array with the top k elements along the given axis + """ pos = arr._lookup_indices(axis) if pos is None: raise ValueError(f"Axis {axis} not found in {arr}") commit a58cb05dace980a62981d8c2716755db14ada77d Date: 2023-09-21T11:46:44-07:00 doc fixup diff --git a/docs/api.md b/docs/api.md index 2136bde..0a93742 100644 --- a/docs/api.md +++ b/docs/api.md @@ -240,6 +240,7 @@ These are all more or less directly from JAX's NumPy API. ::: haliax.clip ::: haliax.isclose +::: haliax.top_k ::: haliax.trace ::: haliax.tril ::: haliax.triu diff --git a/src/haliax/hof.py b/src/haliax/hof.py index 8df3ecf..1fb3d67 100644 --- a/src/haliax/hof.py +++ b/src/haliax/hof.py @@ -109,11 +109,11 @@ def fold( then the initial carry and then any arguments to scan over as a separate curried function call. Args: - :param fn: function to reduce over - :param axis: axis to reduce over - :param reverse: if True, reduce in reverse - :param unroll: unroll the loop by this amount - :param is_scanned: a function that takes a leaf of the tree and returns True if it should be scanned over, + fn: function to reduce over + axis: axis to reduce over + reverse: if True, reduce in reverse + unroll: unroll the loop by this amount + is_scanned: a function that takes a leaf of the tree and returns True if it should be scanned over, False otherwise. Behaves similarly to the `default` argument in filter_jit Returns: @@ -189,14 +189,12 @@ def vmap( useful for initializing modules that will be scanned over. See [haliax.nn.Stacked][] for an example. Args: - fn: function to vmap over - axis: axis to vmap over + fn (Callable): function to vmap over + axis (Axis): axis to vmap over default: how to handle (unnamed) arrays by default. Should be either an integer or None, or a callable that takes a PyTree leaf and returns an integer or None, or a PyTree prefix of the same. If an integer, the array will be mapped over that axis. If None, the array will not be mapped over. args: optional per-argument overrides for how to handle arrays. Should be a PyTree prefix of the same type as default. kwargs: optional per-keyword-argument overrides for how to handle arrays. Should be a PyTree prefix of the same type as default. - out: optional override for how to handle the output. Should be a PyTree prefix of the same type as default. Defaults - to 0 if the output is an unnamed array, and the Axis otherwise. """ if kwargs is None: diff --git a/src/haliax/nn/linear.py b/src/haliax/nn/linear.py index 810daa3..4f9a659 100644 --- a/src/haliax/nn/linear.py +++ b/src/haliax/nn/linear.py @@ -1,6 +1,7 @@ from typing import Optional import equinox as eqx +from jaxtyping import PRNGKeyArray import haliax as hax @@ -36,7 +37,7 @@ class Linear(eqx.Module): return Linear(weight, bias, In, Out) @named_call - def __call__(self, inputs, *, key=None): + def __call__(self, inputs, *, key: Optional[PRNGKeyArray] = None): """ Args: inputs (NamedArray): Input array commit 480ca8818fd10159de11544f3cf4ab13fb1d58d7 Date: 2023-09-25T16:16:30-07:00 add badges to the readme and link to readthedocs diff --git a/README.md b/README.md index 3d0a926..d7aacc3 100644 --- a/README.md +++ b/README.md @@ -1,6 +1,17 @@ <!--haliax-intro-start--> # Haliax +<a href="https://github.com/stanford-crfm/haliax/actions?query=branch%3Amain++"> + <img alt="Build Status" src="https://img.shields.io/github/actions/workflow/status/stanford-crfm/haliax/run_tests.yaml?branch=main"> +</a> +<a href="https://haliax.readthedocs.io/en/latest/?badge=latest"> + <img alt="Documentation Status" src="https://readthedocs.org/projects/haliax/badge/?version=latest"> +</a> +<img alt="License" src="https://img.shields.io/github/license/stanford-crfm/haliax?color=blue" /> +<a href="https://https://pypi.org/project/haliax/"> + <img alt="PyPI" src="https://img.shields.io/pypi/v/haliax?color=blue" /> +</a> + > *Though you don’t seem to be much for listening, it’s best to be careful. If you managed to catch hold of even just a piece of my name, you’d have all manner of power over me.*<br/> > — Patrick Rothfuss, *The Name of the Wind* @@ -88,6 +99,10 @@ You can find us in the #levanter channel on the unofficial [Jax LLM Discord](htt ## Documentation +Haliax's API documentation is available at [haliax.readthedocs.io](https://haliax.readthedocs.io/en/latest/). + +### Tutorials + Currently, we have four tutorials for Haliax : <!--haliax-tutorials-start--> commit 215c5e1335fca4236ee5c1d0d30ffc32bdf2949a Date: 2023-09-25T23:30:47-07:00 don't provide shardings when we're not output arrays diff --git a/src/haliax/partitioning.py b/src/haliax/partitioning.py index d398c9b..ded5054 100644 --- a/src/haliax/partitioning.py +++ b/src/haliax/partitioning.py @@ -175,8 +175,13 @@ def infer_resource_partitions( def partition_spec(node: typing.Any): if isinstance(node, NamedArray): + # If our NamedArray doesn't have an array (or a shapedtypestruct), we can't shard it + # so better to not try + if not is_jax_array_like(node.array): + return None + if preserve_existing_shardings: - current_sharding = getattr(node, "sharding", None) + current_sharding = getattr(node.array, "sharding", None) else: current_sharding = None @@ -308,7 +313,9 @@ class _NamedJitWrapper(eqx.Module): if out_axis_resources is not None: # TODO: when AUTO is fixed (or eval_shape can give shardings), use it here - out_resources = infer_resource_partitions(output_shape, out_axis_resources, use_auto_sharding=False) + out_resources = infer_resource_partitions( + output_shape, out_axis_resources, preserve_existing_shardings=False, use_auto_sharding=False + ) my_pjit_args["out_shardings"] = out_resources cached_pjitted_fun = _named_pjit_cache(self._fn, **my_pjit_args) diff --git a/tests/test_partitioning.py b/tests/test_partitioning.py index 6e9e747..fe87c73 100644 --- a/tests/test_partitioning.py +++ b/tests/test_partitioning.py @@ -32,7 +32,7 @@ def test_infer_named_axes(): with axis_mapping(resource_map), mesh: mod = MyModule(named=hax.ones((Dim1, Dim2, Dim3)), unnamed1=jnp.ones(Dim2.size), static_field=1) - axes: MyModule = infer_resource_partitions(mod) + axes: MyModule = infer_resource_partitions(mod, preserve_existing_shardings=False) spec = PartitionSpec(None, ResourceAxis.DATA, ResourceAxis.MODEL) commit adc45008545c4ac6776e11ef4f19ffcbd76155e7 Date: 2023-10-02T12:43:38-07:00 Release 1.1 (#41) * bump version for release * add flatten as an alias for ravel * update cheatsheet * update cheatsheet * fix docs diff --git a/docs/api.md b/docs/api.md index 0a93742..c8ca3cc 100644 --- a/docs/api.md +++ b/docs/api.md @@ -77,11 +77,13 @@ See also the section on [Indexing and Slicing](indexing.md). ### Shape Manipulation +::: haliax.flatten ::: haliax.flatten_axes ::: haliax.rearrange ::: haliax.unbind ::: haliax.unflatten_axis ::: haliax.split +::: haliax.ravel ## Operations diff --git a/docs/cheatsheet.md b/docs/cheatsheet.md index 1b82e9b..3c4c68c 100644 --- a/docs/cheatsheet.md +++ b/docs/cheatsheet.md @@ -17,6 +17,9 @@ import haliax as hax Batch = hax.Axis("batch", 32) Embed = hax.Axis("embed", 64) +Step = hax.axis("step", 2) +Mini = hax.axis("mini", 16) + # for jax x = jnp.zeros((32, 64)) y = jnp.zeros((32, 64)) @@ -44,6 +47,8 @@ ind = hax.arange(Axis("Index", 8), dtype=jnp.int32) | [`jnp.eye(32)`][jax.numpy.eye] | ❌ | | [`jnp.arange(32)`][jax.numpy.arange] | [`hax.arange(Batch)`][haliax.arange] | | [`jnp.linspace(0, 1, 32)`][jax.numpy.linspace] | [`hax.linspace(Batch, 0, 1)`][haliax.linspace] | +| [`jnp.logspace(0, 1, 32)`][jax.numpy.logspace] | [`hax.logspace(Batch, 0, 1)`][haliax.logspace] | +| [`jnp.geomspace(0, 1, 32)`][jax.numpy.geomspace] | [`hax.geomspace(Batch, 0, 1)`][haliax.geomspace] | ### Combining Arrays @@ -56,6 +61,15 @@ ind = hax.arange(Axis("Index", 8), dtype=jnp.int32) ## Array Manipulation +| JAX | Haliax | +|--------------------------------------------------|-------------------------------------------------------------------------| +| [`jnp.ravel(x)`][jax.numpy.ravel] | [`hax.ravel(x, "Embed")`][haliax.flatten] | +| [`jnp.ravel(x)`][jax.numpy.ravel] | [`hax.flatten(x, "Embed")`][haliax.flatten] | +| [`jnp.reshape(x, (2, 16, 64))`][jax.numpy.reshape] | [`hax.unflatten_axis(x, "batch", (Step, Mini)`][haliax.unflatten_axis] | +| [`jnp.reshape(x, (-1,))`][jax.numpy.reshape] | [`hax.flatten_axes(x, ("batch", "embed"), "foo")`][haliax.flatten_axes] | +| [`jnp.transpose(x, (1, 0))`][jax.numpy.transpose] | [`hax.rearrange(x, ("embed", "batch"))`][haliax.rearrange] | + + ### Broadcasting See also the section on [Broadcasting](broadcasting.md). diff --git a/docs/tips.md b/docs/faq.md similarity index 100% rename from docs/tips.md rename to docs/faq.md diff --git a/mkdocs.yml b/mkdocs.yml index b08e28f..53d98fa 100644 --- a/mkdocs.yml +++ b/mkdocs.yml @@ -85,3 +85,4 @@ nav: - Partitioning: 'partitioning.md' - Higher Order Functions: 'hof.md' - API Reference: 'api.md' + - FAQ: 'faq.md' diff --git a/pyproject.toml b/pyproject.toml index 9340073..4ce5634 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta" [project] name = "haliax" -version = "1.0.2" +version = "1.1" authors = [ { name="David Hall", email="dlwh@cs.stanford.edu" }, ] diff --git a/src/haliax/__init__.py b/src/haliax/__init__.py index cd8b40e..203fb26 100644 --- a/src/haliax/__init__.py +++ b/src/haliax/__init__.py @@ -20,6 +20,7 @@ from .core import ( broadcast_to, dot, enable_shape_checks, + flatten, flatten_axes, index, named, @@ -980,4 +981,6 @@ __all__ = [ "concat_axes", "concat_axis_specs", "top_k", + "ravel", + "flatten", ] diff --git a/src/haliax/core.py b/src/haliax/core.py index cd77aaa..7be2edb 100644 --- a/src/haliax/core.py +++ b/src/haliax/core.py @@ -233,6 +233,9 @@ class NamedArray: def ravel(self, new_axis_name: AxisSelector) -> "NamedArray": return haliax.ravel(self, new_axis_name=new_axis_name) + def flatten(self, new_axis_name: AxisSelector) -> "NamedArray": + return haliax.flatten(self, new_axis_name=new_axis_name) + def unbind(self, axis: AxisSelector) -> Sequence["NamedArray"]: return haliax.unbind(self, axis=axis) @@ -402,10 +405,6 @@ class NamedArray: def ptp(self, axis: Optional[AxisSelection] = None) -> "NamedArray": return haliax.ptp(self, axis=axis) - # TODO: implement ravel. Can only do if we either ask for an axis or add ProductAxis or something - # def ravel(self, order='C') -> Any: - # ... - @property def real(self) -> "NamedArray": return NamedArray(self.array.real, self.axes) @@ -1211,6 +1210,13 @@ def ravel(array: NamedArray, new_axis_name: AxisSelector) -> NamedArray: return flattened +def flatten(array: NamedArray, new_axis_name: AxisSelector) -> NamedArray: + """ + Returns a flattened view of the array, with all axes merged into one. Aliax for [haliax.ravel][] + """ + return ravel(array, new_axis_name) + + def named(a: jnp.ndarray, axis: AxisSelection) -> NamedArray: """Creates a NamedArray from a numpy array and a list of axes.""" axes = check_shape(a.shape, axis) @@ -1484,6 +1490,7 @@ __all__ = [ "flatten_axes", "unflatten_axis", "ravel", + "flatten", "unbind", "roll", "_broadcast_order", commit bed0d7d997935315f5e4e1a835debf510d34da2a Date: 2023-10-08T18:46:30-07:00 Add Conv and ConvTranspose (#42) diff --git a/docs/api.md b/docs/api.md index c8ca3cc..e18708f 100644 --- a/docs/api.md +++ b/docs/api.md @@ -27,9 +27,11 @@ Occasionally, an axis size can be inferred in some circumstances but not others. ### Axis Manipulation +::: haliax.axis.axis_name ::: haliax.axis.concat_axes ::: haliax.axis.union_axes ::: haliax.axis.eliminate_axes +::: haliax.axis.without_axes ::: haliax.axis.overlapping_axes ::: haliax.axis.selects_axis ::: haliax.axis.is_axis_compatible diff --git a/docs/nn.md b/docs/nn.md index 884536e..f3a5031 100644 --- a/docs/nn.md +++ b/docs/nn.md @@ -48,6 +48,15 @@ of the same module (e.g. transformer blocks), which is a common pattern in deep ::: haliax.nn.LayerNorm ::: haliax.nn.Stacked +### Convolutional Layers + +Unlike other frameworks, Haliax doesn't distinguish between 1D, 2D, and 3D, and general convolutions. Instead, we have +a single [haliax.nn.Conv][] module that can be used for all of these, depending on the number of axes +provided. Similarly, for transposed convolutions, we have [haliax.nn.ConvTranspose][]. + +::: haliax.nn.Conv +::: haliax.nn.ConvTranspose + ## Attention We don't provide an explicit attention module, but we do provide an attention function and several related functions: diff --git a/src/haliax/__init__.py b/src/haliax/__init__.py index 203fb26..7010adc 100644 --- a/src/haliax/__init__.py +++ b/src/haliax/__init__.py @@ -10,7 +10,7 @@ import haliax.nn as nn import haliax.random as random import haliax.tree_util as tree_util -from .axis import Axis, AxisSelection, AxisSelector, AxisSpec, concat_axes, eliminate_axes, selects_axis +from .axis import Axis, AxisSelection, AxisSelector, AxisSpec, axis_name, concat_axes, eliminate_axes, selects_axis from .core import ( NamedArray, NamedOrNumeric, @@ -159,25 +159,25 @@ def concatenate(axis: AxisSelector, arrays: Sequence[NamedArray]) -> NamedArray: """Version of [jax.numpy.concatenate][] that returns a NamedArray. The returns array will have the same axis names in the same order as the first, with the selected axis extended by the sum of the sizes of the selected axes in the concatenated arrays.""" - axis_name = axis.name if isinstance(axis, Axis) else axis - total_size: int = _sum(a.resolve_axis(axis_name).size for a in arrays) # type: ignore + aname = axis_name(axis) + total_size: int = _sum(a.resolve_axis(aname).size for a in arrays) # type: ignore if isinstance(axis, str): axis = Axis(axis, total_size) elif total_size != axis.size: raise ValueError( - f"Cannot concatenate arrays along axis {axis_name} of size {axis.size} with total size {total_size}" + f"Cannot concatenate arrays along axis {aname} of size {axis.size} with total size {total_size}" ) if len(arrays) == 0: return zeros(axis) - axis_index = arrays[0]._lookup_indices(axis_name) + axis_index = arrays[0]._lookup_indices(aname) if axis_index is None: - raise ValueError(f"Axis {axis_name} not found in 0th array {arrays[0]}") + raise ValueError(f"Axis {aname} not found in 0th array {arrays[0]}") axes: typing.Tuple[AxisSelector, ...] = arrays[0].axes # we want to use the axis name for `axis`, because it's not uncommon for those to be different lengths in the arrays - axes = axes[:axis_index] + (axis_name,) + axes[axis_index + 1 :] + axes = axes[:axis_index] + (aname,) + axes[axis_index + 1 :] arrays = [a.rearrange(axes) for a in arrays] new_axes = arrays[0].axes[:axis_index] + (axis,) + arrays[0].axes[axis_index + 1 :] diff --git a/src/haliax/axis.py b/src/haliax/axis.py index 84dcc0a..1d3d00b 100644 --- a/src/haliax/axis.py +++ b/src/haliax/axis.py @@ -117,15 +117,15 @@ def concat_axes(a1: AxisSelection, a2: AxisSelection) -> AxisSelection: """Concatenates two AxisSpec. Raises ValueError if any axis is present in both specs""" if isinstance(a1, Axis) and isinstance(a2, Axis): - if _ax_name(a1) == _ax_name(a2): + if axis_name(a1) == axis_name(a2): raise ValueError(f"Axis {a1} specified twice") return (a1, a2) else: a1 = ensure_tuple(a1) a2 = ensure_tuple(a2) - a1_names = [_ax_name(ax) for ax in a1] - a2_names = [_ax_name(ax) for ax in a2] + a1_names = [axis_name(ax) for ax in a1] + a2_names = [axis_name(ax) for ax in a2] if len(set(a1_names) & set(a2_names)) > 0: overlap = [ax for ax in a1_names if ax in a2_names] @@ -182,7 +182,7 @@ def eliminate_axes(axis_spec: AxisSelection, to_remove: AxisSelection) -> AxisSe to_remove = ensure_tuple(to_remove) axis_spec_dict = _spec_to_dict(axis_spec) for ax in to_remove: - name = _ax_name(ax) + name = axis_name(ax) if name not in axis_spec_dict: raise ValueError(f"Axis {name} not present in axis spec {axis_spec}") del axis_spec_dict[name] @@ -190,6 +190,51 @@ def eliminate_axes(axis_spec: AxisSelection, to_remove: AxisSelection) -> AxisSe return _dict_to_spec(axis_spec_dict) +@typing.overload +def without_axes(axis_spec: AxisSpec, to_remove: AxisSelection) -> AxisSpec: # type: ignore + ... + + +@typing.overload +def without_axes(axis_spec: AxisSelection, to_remove: AxisSelection) -> AxisSelection: # type: ignore + """As eliminate_axes, but does not raise if any axis in to_remove is not present in axis_spec""" + + +def without_axes(axis_spec: AxisSelection, to_remove: AxisSelection) -> AxisSelection: # type: ignore + """As eliminate_axes, but does not raise if any axis in to_remove is not present in axis_spec""" + + to_remove = ensure_tuple(to_remove) + axis_spec_dict = _spec_to_dict(axis_spec) + for ax in to_remove: + name = axis_name(ax) + if name in axis_spec_dict: + del axis_spec_dict[name] + + return _dict_to_spec(axis_spec_dict) + + +@overload +def replace_axis(axis_spec: AxisSpec, old: AxisSelector, new: AxisSpec) -> AxisSpec: + ... + + +@overload +def replace_axis(axis_spec: AxisSelection, old: AxisSelector, new: AxisSelection) -> AxisSelection: + ... + + +def replace_axis(axis_spec: AxisSelection, old: AxisSelector, new: AxisSelection) -> AxisSelection: + """Returns a new axis spec that is the same as the original, but with any axes in old replaced with new. Raises if old is + not present in axis_spec""" + axis_spec = ensure_tuple(axis_spec) + index_of_old = index_where(lambda ax: is_axis_compatible(ax, old), axis_spec) + + if index_of_old < 0: + raise ValueError(f"Axis {old} not present in axis spec {axis_spec}") + + return axis_spec[:index_of_old] + ensure_tuple(new) + axis_spec[index_of_old + 1 :] # type: ignore + + @overload def overlapping_axes(ax1: AxisSpec, ax2: AxisSelection) -> Tuple[Axis, ...]: ... @@ -231,7 +276,10 @@ def overlapping_axes(ax1: AxisSelection, ax2: AxisSelection) -> Tuple[AxisSelect return tuple(out) -def _ax_name(ax: AxisSelector) -> str: +def axis_name(ax: AxisSelector) -> str: + """ + Returns the name of the axis. If ax is a string, returns ax. If ax is an Axis, returns ax.name + """ if isinstance(ax, Axis): return ax.name else: diff --git a/src/haliax/core.py b/src/haliax/core.py index 7be2edb..360d7c2 100644 --- a/src/haliax/core.py +++ b/src/haliax/core.py @@ -17,7 +17,7 @@ from haliax.jax_utils import is_jax_array_like from haliax.util import ensure_tuple from ._src.util import index_where, py_slice, slice_t -from .axis import Axis, AxisSelection, AxisSelector, AxisSpec, eliminate_axes, selects_axis, union_axes +from .axis import Axis, AxisSelection, AxisSelector, AxisSpec, axis_name, eliminate_axes, selects_axis, union_axes from .types import IntScalar, PrecisionLike, Scalar @@ -755,7 +755,7 @@ def _slice_new( new_lengths = [axis.size for axis in array.axes] for axis, s in start.items(): - axis_index = array._lookup_indices(axis.name if isinstance(axis, Axis) else axis) + axis_index = array._lookup_indices(axis_name(axis)) if axis_index is None: raise ValueError(f"axis {axis} not found in {array}") @@ -802,12 +802,12 @@ def updated_slice( array_slice_indices = [0] * len(array.axes) for axis, s in start.items(): - axis_index = array._lookup_indices(axis.name if isinstance(axis, Axis) else axis) + axis_index = array._lookup_indices(axis_name(axis)) if axis_index is None: raise ValueError(f"axis {axis} not found in {array}") array_slice_indices[axis_index] = s total_length = array.axes[axis_index].size - update_axis = update._lookup_indices(axis.name if isinstance(axis, Axis) else axis) + update_axis = update._lookup_indices(axis_name(axis)) if update_axis is None: raise ValueError(f"axis {axis} not found in {update}") diff --git a/src/haliax/nn/__init__.py b/src/haliax/nn/__init__.py index 7803897..2f25003 100644 --- a/src/haliax/nn/__init__.py +++ b/src/haliax/nn/__init__.py @@ -15,6 +15,7 @@ from ..core import NamedArray from ..types import Scalar from ..util import UNSPECIFIED, Unspecified from ..wrap import ReductionFunction, unwrap_namedarrays, wrap_axiswise_call, wrap_elemwise_unary, wrap_reduction_call +from .conv import Conv, ConvTranspose from .dropout import Dropout, dropout from .embedding import Embedding from .linear import Linear @@ -220,6 +221,8 @@ __all__ = [ "cross_entropy_loss", "cross_entropy_loss_and_log_normalizers", "quick_gelu", + "Conv", + "ConvTranspose", "Dropout", "dropout", "LayerNorm", diff --git a/src/haliax/nn/conv.py b/src/haliax/nn/conv.py new file mode 100644 index 0000000..0a2f675 --- /dev/null +++ b/src/haliax/nn/conv.py @@ -0,0 +1,447 @@ +import string +from functools import cached_property +from typing import Optional, Sequence, TypeVar + +import equinox as eqx +import jax +import numpy as np +from jaxtyping import PRNGKeyArray + +import haliax.partitioning + +from ..axis import Axis, AxisSelection, axis_name, replace_axis, selects_axis, without_axes +from ..core import NamedArray, named +from ..jax_utils import named_call +from ..random import uniform +from ..util import ensure_tuple + + +T = TypeVar("T") + + +class _ConvBase(eqx.Module): + """ + Base class for Conv and ConvTranspose. Mostly just contains shared code. + """ + + Spatial: tuple[str | Axis, ...] = eqx.field(static=True) + In: Axis = eqx.field(static=True) + Out: Axis = eqx.field(static=True) + weight: NamedArray = eqx.field(static=True) + bias: Optional[NamedArray] = eqx.field(static=True) + + def _lhs_dim_spec(self, batch_index, inputs): + # the dim spec are single letters, for things like NCHW + lhs_dim_spec = "" + for i, ax in enumerate(inputs.axes): + if i == batch_index: + lhs_dim_spec += "N" + elif ax.name == self.In.name: + lhs_dim_spec += "C" + else: + index_in_spatial = _index_of_name(self.Spatial, ax.name) + if index_in_spatial >= 0: + lhs_dim_spec += self._spatial_dim_short_names[index_in_spatial] + else: + # shouldn't happen + raise ValueError(f"Unexpected axis {ax.name}") + return lhs_dim_spec + + @cached_property + def _spatial_dim_short_names(self) -> str: + banned_letters = "NCIO" + spec = "" + for x in self.Spatial: + name = axis_name(x) + assert len(name) > 0 + if name[0] not in banned_letters and name[0] not in spec: + spec += name[0] + else: + for x in string.ascii_uppercase: + if x not in spec and x not in banned_letters: + spec += x + break + else: + raise RuntimeError("Too many spatial dimensions") + + return spec + + @cached_property + def _weight_dim_spec(self) -> str: + # dim spec in format jax.lax.conv_general_dilated expects + # it's typically OIWH or similar but in case anyone does something funny with the weight array: + # "OI" + self._spatial_dim_short_names + spec = "" + for ax in self.weight.axes: + # check name for grouped convolutions + if ax.name == self.In.name: + spec += "I" + elif ax == self.Out: + spec += "O" + else: + index_in_spatial = _index_of_name(self.Spatial, ax.name) + if index_in_spatial >= 0: + spec += self._spatial_dim_short_names[index_in_spatial] + else: + # shouldn't happen + raise ValueError(f"Unexpected axis {ax.name}") + return spec + + +# Based on Equinox's Conv class +class Conv(_ConvBase): + """General N-dimensional convolution.""" + + kernel_size: tuple[int, ...] = eqx.field(static=True) + stride: tuple[int, ...] = eqx.field(static=True) + padding: tuple[tuple[int, int], ...] = eqx.field(static=True) + dilation: tuple[int, ...] = eqx.field(static=True) + groups: int = eqx.field(static=True) + + @staticmethod + def init( + Spatial: AxisSelection, + In: Axis, + Out: Axis, + kernel_size: int | Sequence[int], + *, + stride: int | Sequence[int] = 1, + padding: int | Sequence[int] | Sequence[tuple[int, int]] = 0, + dilation: int | Sequence[int] = 1, + groups: int = 1, + use_bias: bool = True, + key: PRNGKeyArray, + ): + """ + Args: + Spatial: names of spatial dimensions + In: Axis of input channels + Out: Axis of output channels + kernel_size: The size of the convolutional kernel. + stride: The stride of the convolution. Can be a single number or a tuple + padding: The amount of padding to apply before and after each spatial + dimension. + dilation: The dilation of the convolution. + groups: The number of groups to split the input channels into. Each + group is convolved separately with its own kernel. + use_bias: Whether to add a bias after the convolution. + key: Random key + """ + Spatial = ensure_tuple(Spatial) + if len(Spatial) == 0: + raise ValueError("Spatial must have at least one element") + + kernel_size = _expand_and_check_shape(len(Spatial), kernel_size, "kernel_size") + stride = _expand_and_check_shape(len(Spatial), stride, "stride") + dilation = _expand_and_check_shape(len(Spatial), dilation, "dilation") + padding = _convert_padding_spec(Spatial, padding) + + kernel_spec = tuple(Axis(axis_name(n), s) for n, s in zip(Spatial, kernel_size)) + in_spec = In.resize(In.size // groups) + + weight_key, bias_key = jax.random.split(key, 2) + + limit = 1 / np.sqrt(np.prod(kernel_size) * in_spec.size) + + weight = uniform(weight_key, (Out, in_spec, *kernel_spec), minval=-limit, maxval=limit) + if use_bias: + bias = uniform(bias_key, (Out,), minval=-limit, maxval=limit) + else: + bias = None + + return Conv(Spatial, In, Out, weight, bias, kernel_size, stride, padding, dilation, groups) + + @named_call + def __call__(self, inputs, *, key: Optional[PRNGKeyArray] = None): + """ + Args: + inputs (NamedArray): Input array + key (PRNGKeyArray: Not used, compat with other modules + + Returns: + (NamedArray): Output array, with shape similar to inputs except: + - `Spatial` dimensions are reduced via the usual convolution formula + - `In` is replaced with `Out` + + Notes: + That formula is: + `out_size = (in_size + 2 * padding - dilation * (kernel_size - 1) - 1) // stride + 1` + """ + del key + + # check input + for ax in self.Spatial: + if not selects_axis(inputs.axes, ax): + raise ValueError(f"Missing spatial axis {ax} in inputs: {inputs.axes}") + + if not selects_axis(inputs.axes, self.In): + raise ValueError(f"Missing input axis {self.In} in inputs: {inputs.axes}") + + if selects_axis(inputs.axes, self.Out): + raise ValueError(f"Output axis {self.Out} already in inputs: {inputs.axes}") + + # this is a bit subtle, but we need to make sure that the input is in the right order + # and has the right set of dimensions + + # Constraints: + # * at most 1 batch dimension (we'll vmap as necessary) + # * at most 1 channel dimension (which we enforce for this module) + # Spatial dimensions are reduced via the usual convolution formula, so we have to drop to names + + # identify batch dims, which get special treatment + # jax's conv_general_dilated only supports exactly one batch dimension (not 0), so we vmap over any others. + # We could choose instead to flatten them, but then we'd definitely lose sharding. + batch_dims = without_axes(inputs.axes, self.weight.axes) + x = _vmap_all_but_one_batch_dim(self._do_conv, batch_dims)(inputs) + + if self.bias is not None: + x = x + self.bias + + output_axes = _compute_output_axes(inputs, batch_dims, self.In, self.Out) + x = x.rearrange(output_axes) + + return x + + def _do_conv(self, inputs): + batch_dims = without_axes(inputs.axes, self.weight.axes) + output_axes = _compute_output_axes(inputs, batch_dims, self.In, self.Out) + + if len(batch_dims) == 1: + batch_index = inputs.axes.index(batch_dims[0]) + else: + assert len(batch_dims) == 0 + # there must be a batch dimension, even if it's size 1 + inputs = inputs.broadcast_axis(Axis("__batch__", 1)) + batch_index = 0 + + lhs_dim_spec = self._lhs_dim_spec(batch_index, inputs) + rhs_dim_spec = self._weight_dim_spec + output_dim_spec = lhs_dim_spec + x = jax.lax.conv_general_dilated( + lhs=inputs.array, + rhs=self.weight.array, + window_strides=self.stride, + padding=self.padding, + rhs_dilation=self.dilation, + feature_group_count=self.groups, + dimension_numbers=(lhs_dim_spec, rhs_dim_spec, output_dim_spec), + ) + + if len(batch_dims) == 0: + x = x.squeeze(0) + + return named(x, output_axes) + + +class ConvTranspose(_ConvBase): + """ + General N-dimensional transposed convolution. + + Based on Equinox's ConvTranspose class + """ + + kernel_size: tuple[int, ...] = eqx.field(static=True) + stride: tuple[int, ...] = eqx.field(static=True) + padding: tuple[tuple[int, int], ...] = eqx.field(static=True) + output_padding: tuple[int, ...] = eqx.field(static=True) + dilation: tuple[int, ...] = eqx.field(static=True) + groups: int = eqx.field(static=True) + + @staticmethod + def init( + Spatial: AxisSelection, + In: Axis, + Out: Axis, + kernel_size: int | Sequence[int], + *, + stride: int | Sequence[int] = 1, + padding: int | Sequence[int] | Sequence[tuple[int, int]] = 0, + output_padding: int | Sequence[int] = 0, + dilation: int | Sequence[int] = 1, + groups: int = 1, + use_bias: bool = True, + key: PRNGKeyArray, + ): + """ + + Args: + Spatial: Spatial dimensions + In: Input channels + Out: Output channels + kernel_size: Kernel size, can be a single number or a tuple + stride: Stride, can be a single number or a tuple + padding: Padding, can be a single number or a tuple + output_padding: Output padding, can be a single number or a tuple + dilation: Dilation, can be a single number or a tuple + groups: Number of groups to split the input channels into + use_bias: Whether to add on a bias after the convolution + key: Random key + + Notes: + Output padding is the amount of extra padding to add to the output. + Because the output size is not uniquely determined by the input size for transposed convolutions. + """ + k_w, k_b = jax.random.split(key, 2) + + Spatial = ensure_tuple(Spatial) + + kernel_size = _expand_and_check_shape(len(Spatial), kernel_size, "kernel_size") + stride = _expand_and_check_shape(len(Spatial), stride, "stride") + dilation = _expand_and_check_shape(len(Spatial), dilation, "dilation") + padding = _convert_padding_spec(Spatial, padding) + output_padding = _expand_and_check_shape(len(Spatial), output_padding, "output_padding") + + kernel_spec = tuple(Axis(axis_name(n), s) for n, s in zip(Spatial, kernel_size)) + in_spec = In.resize(In.size // groups) + + lim = 1 / np.sqrt(np.prod(kernel_size) * in_spec.size) + weight = uniform(k_w, (Out, in_spec, *kernel_spec), minval=-lim, maxval=lim) + if use_bias: + bias = uniform(k_b, (Out,), minval=-lim, maxval=lim) + else: + bias = None + + return ConvTranspose( + Spatial, + In, + Out, + weight, + bias, + kernel_size, + stride, + padding, + output_padding, + dilation, + groups, + ) + + @named_call + def __call__(self, inputs, *, key: Optional[PRNGKeyArray] = None): + """ + Args: + inputs (NamedArray): Input array + key (PRNGKeyArray: Not used, compat with other modules + + Returns: + (NamedArray): Output array, with shape similar to inputs except: + - `Spatial` dimensions are increased via the usual (de)convolution formula + - `In` is replaced with `Out` + + Notes: + That formula is: + `out_size = (in_size - 1) * stride - 2 * padding + dilation * (kernel_size - 1) + output_padding + 1` + """ + del key + + batch_dims = without_axes(inputs.axes, self.weight.axes) + x = _vmap_all_but_one_batch_dim(self._do_conv, batch_dims)(inputs) + + if self.bias is not None: + x = x + self.bias + + output_axes = _compute_output_axes(inputs, batch_dims, self.In, self.Out) + + return x.rearrange(output_axes) + + def _do_conv(self, inputs): + batch_dims = without_axes(inputs.axes, self.weight.axes) + output_axes = _compute_output_axes(inputs, batch_dims, self.In, self.Out) + + if len(batch_dims) == 1: + batch_index = inputs.axes.index(batch_dims[0]) + else: + assert len(batch_dims) == 0 + # there must be a batch dimension, even if it's size 1 + inputs = inputs.broadcast_axis(Axis("__batch__", 1)) + batch_index = 0 + + # cribbed from Equinox's ConvTranspose class + padding = tuple( + (d * (k - 1) - p0, d * (k - 1) - p1 + o) + for k, (p0, p1), o, d in zip(self.kernel_size, self.padding, self.output_padding, self.dilation) + ) + + lhs_dim_spec = self._lhs_dim_spec(batch_index, inputs) + rhs_dim_spec = self._weight_dim_spec + output_dim_spec = lhs_dim_spec + + x = jax.lax.conv_general_dilated( + lhs=inputs.array, + rhs=self.weight.array, + window_strides=(1,) * len(self.Spatial), + padding=padding, + lhs_dilation=self.stride, + rhs_dilation=self.dilation, + feature_group_count=self.groups, + dimension_numbers=(lhs_dim_spec, rhs_dim_spec, output_dim_spec), + ) + + if len(batch_dims) == 0: + x = x.squeeze(0) + + return named(x, output_axes) + + +def _expand_and_check_shape(expected_len: int, spec: T | Sequence[T], name: str) -> tuple[T, ...]: + spec = ensure_tuple(spec) + if len(spec) == 1: + spec = spec * expected_len + if len(spec) != expected_len: + raise ValueError(f"Expected {expected_len} elements for {name}, got {len(spec)}") + + return spec + + +def _convert_padding_spec(Spatial, padding): + if isinstance(padding, int): + padding = ((padding, padding),) * len(Spatial) + elif isinstance(padding, tuple): + padding = _expand_and_check_shape(len(Spatial), padding, "padding") + padding_spec = [] + for p in padding: + if isinstance(p, int): + padding_spec.append((p, p)) + elif isinstance(p, tuple): + padding_spec.append(p) + else: + raise ValueError(f"Invalid padding spec: {padding}") + + padding = tuple(padding_spec) + else: + raise ValueError(f"Invalid padding spec: {padding}") + + return padding + + +def _index_of_name(names: Sequence[str | Axis], name) -> int: + for i, x in enumerate(names): + if isinstance(x, Axis): + x = axis_name(x) + if x == name: + return i + return -1 + + +def _vmap_all_but_one_batch_dim(op, batch_dims): + batch_dims = list(batch_dims) + # We want to prioritize vmapping over *sharded* batch dimensions (TODO: make sure this is correct) + # TODO: I think we may need to do shard_map or something to make sure we don't lose sharding + sharded_batch_dims = [ax for ax in batch_dims if haliax.partitioning.physical_axis_name(ax) is not None] + while len(sharded_batch_dims) > 1: + dim = sharded_batch_dims.pop() + batch_dims.remove(dim) + op = haliax.vmap(op, axis=dim.name) + while len(batch_dims) > 1: + dim = batch_dims.pop() + op = haliax.vmap(op, axis=dim.name) + return op + + +def _compute_output_axes(inputs, batch_dims, In, Out): + """ + Does two things: + 1. Replace In with Out + 2. turn spatial dims (non-batch, non-In, non-Out) into raw names b/c they change size in convolutions + """ + unchanging_dims = [Out, *batch_dims] + return [ax.name if ax not in unchanging_dims else ax for ax in replace_axis(inputs.axes, In, Out)] diff --git a/tests/test_conv.py b/tests/test_conv.py new file mode 100644 index 0000000..f2fb028 --- /dev/null +++ b/tests/test_conv.py @@ -0,0 +1,171 @@ +import equinox as eqx +import jax +import jax.numpy as jnp + +import haliax as hax +from haliax.nn.conv import Conv, ConvTranspose + + +def test_conv_basic_equiv_to_eqx(): + key = jax.random.PRNGKey(0) + In = hax.Axis("In", 3) + Out = hax.Axis("Out", 4) + hax_conv = Conv.init(("Height", "Width"), In, Out, kernel_size=3, key=key) + eqx_conv = eqx.nn.Conv(2, 3, 4, kernel_size=3, key=key) + + assert hax_conv.weight.array.shape == eqx_conv.weight.shape + assert hax_conv.bias.array.shape == eqx_conv.bias.shape[0:1] + assert jnp.all(hax_conv.weight.array == eqx_conv.weight) + + input = hax.random.normal(jax.random.PRNGKey(1), (In, hax.Axis("Height", 5), hax.Axis("Width", 6))) + hax_output = hax_conv(input) + eqx_output = eqx_conv(input.array) + + assert hax_output.array.shape == eqx_output.shape + assert jnp.all(hax_output.array == eqx_output) + + # test batched + input = hax.random.normal( + jax.random.PRNGKey(1), (hax.Axis("Batch", 2), In, hax.Axis("Height", 5), hax.Axis("Width", 6)) + ) + hax_output = hax_conv(input) + eqx_output = eqx.filter_vmap(eqx_conv)(input.array) + + assert hax_output.array.shape == eqx_output.shape + assert jnp.all(hax_output.array == eqx_output) + + # test multibatch + input = hax.random.normal( + jax.random.PRNGKey(1), + (hax.Axis("Batch", 2), hax.Axis("Batch2", 3), In, hax.Axis("Height", 5), hax.Axis("Width", 6)), + ) + hax_output = hax_conv(input) + eqx_output = eqx.filter_vmap(eqx.filter_vmap(eqx_conv))(input.array) + + assert hax_output.array.shape == eqx_output.shape + assert jnp.allclose(hax_output.array, eqx_output) + + +def test_conv_grouped_equiv_to_eqx(): + key = jax.random.PRNGKey(0) + In = hax.Axis("In", 4) + Out = hax.Axis("Out", 6) + hax_conv = Conv.init(("Height", "Width"), In, Out, kernel_size=3, groups=2, key=key) + eqx_conv = eqx.nn.Conv(2, 4, 6, kernel_size=3, groups=2, key=key) + + assert hax_conv.weight.array.shape == eqx_conv.weight.shape + assert hax_conv.bias.array.shape == eqx_conv.bias.shape[0:1] + assert jnp.all(hax_conv.weight.array == eqx_conv.weight) + + input = hax.random.normal(jax.random.PRNGKey(1), (In, hax.Axis("Height", 5), hax.Axis("Width", 6))) + eqx_output = eqx_conv(input.array) + hax_output = hax_conv(input) + + assert hax_output.array.shape == eqx_output.shape + assert jnp.all(hax_output.array == eqx_output) + + # test batched + input = hax.random.normal( + jax.random.PRNGKey(1), (hax.Axis("Batch", 2), In, hax.Axis("Height", 5), hax.Axis("Width", 6)) + ) + hax_output = hax_conv(input) + eqx_output = eqx.filter_vmap(eqx_conv)(input.array) + + assert hax_output.array.shape == eqx_output.shape + assert jnp.all(hax_output.array == eqx_output) + + # test multibatch + input = hax.random.normal( + jax.random.PRNGKey(1), + (hax.Axis("Batch", 2), hax.Axis("Batch2", 3), In, hax.Axis("Height", 5), hax.Axis("Width", 6)), + ) + hax_output = hax_conv(input) + eqx_output = eqx.filter_vmap(eqx.filter_vmap(eqx_conv))(input.array) + + assert hax_output.array.shape == eqx_output.shape + assert jnp.allclose(hax_output.array, eqx_output) + + +def test_conv_weird_order(): + key = jax.random.PRNGKey(0) + In = hax.Axis("In", 3) + Out = hax.Axis("Out", 4) + hax_conv = Conv.init(("Height", "Width"), In, Out, kernel_size=3, key=key) + eqx_conv = eqx.nn.Conv(2, 3, 4, kernel_size=3, key=key) + + assert hax_conv.weight.array.shape == eqx_conv.weight.shape + assert hax_conv.bias.array.shape == eqx_conv.bias.shape[0:1] + assert jnp.all(hax_conv.weight.array == eqx_conv.weight) + + input = hax.random.normal( + jax.random.PRNGKey(1), (hax.Axis("Batch", 2), In, hax.Axis("Height", 5), hax.Axis("Width", 6)) + ) + hax_output = hax_conv(input) + + # test weird orders + input = input.rearrange(("In", "Height", "Width", "Batch")) + hax_output2 = hax_conv(input).rearrange(("Batch", "Out", "Height", "Width")) + + assert jnp.allclose(hax_output.array, hax_output2.array) + + +def test_conv_transpose_basic_equiv_to_eqx(): + key = jax.random.PRNGKey(0) + In = hax.Axis("In", 3) + Out = hax.Axis("Out", 4) + hax_conv = ConvTranspose.init( + ("Height", "Width"), In, Out, kernel_size=3, dilation=2, output_padding=1, stride=2, key=key + ) + eqx_conv = eqx.nn.ConvTranspose(2, 3, 4, kernel_size=3, dilation=2, output_padding=1, stride=2, key=key) + + assert hax_conv.weight.array.shape == eqx_conv.weight.shape + assert hax_conv.bias.array.shape == eqx_conv.bias.shape[0:1] + assert jnp.all(hax_conv.weight.array == eqx_conv.weight) + + input = hax.random.normal(jax.random.PRNGKey(1), (In, hax.Axis("Height", 5), hax.Axis("Width", 6))) + hax_output = hax_conv(input) + eqx_output = eqx_conv(input.array) + + assert hax_output.array.shape == eqx_output.shape + assert jnp.all(hax_output.array == eqx_output) + + # test batched + input = hax.random.normal( + jax.random.PRNGKey(1), (hax.Axis("Batch", 2), In, hax.Axis("Height", 5), hax.Axis("Width", 6)) + ) + hax_output = hax_conv(input) + eqx_output = eqx.filter_vmap(eqx_conv)(input.array) + + assert hax_output.array.shape == eqx_output.shape + assert jnp.all(hax_output.array == eqx_output) + + # test multibatch + input = hax.random.normal( + jax.random.PRNGKey(1), + (hax.Axis("Batch", 2), hax.Axis("Batch2", 3), In, hax.Axis("Height", 5), hax.Axis("Width", 6)), + ) + hax_output = hax_conv(input) + eqx_output = eqx.filter_vmap(eqx.filter_vmap(eqx_conv))(input.array) + + assert hax_output.array.shape == eqx_output.shape + assert jnp.allclose(hax_output.array, eqx_output) + + +def test_weird_orders_conv_transpose(): + key = jax.random.PRNGKey(0) + In = hax.Axis("In", 3) + Out = hax.Axis("Out", 4) + hax_conv = ConvTranspose.init( + ("Height", "Width"), In, Out, kernel_size=3, dilation=2, output_padding=1, stride=2, key=key + ) + + input = hax.random.normal( + jax.random.PRNGKey(1), (hax.Axis("Batch", 2), In, hax.Axis("Height", 5), hax.Axis("Width", 6)) + ) + hax_output = hax_conv(input) + + # test weird orders + input = input.rearrange(("In", "Height", "Width", "Batch")) + hax_output2 = hax_conv(input).rearrange(("Batch", "Out", "Height", "Width")) + + assert jnp.allclose(hax_output.array, hax_output2.array) commit 8f06bb07e43adab719c9779ccfe060c79161664f Date: 2023-10-13T19:47:23-07:00 dumb diff --git a/src/haliax/nn/conv.py b/src/haliax/nn/conv.py index 0a2f675..88e70ce 100644 --- a/src/haliax/nn/conv.py +++ b/src/haliax/nn/conv.py @@ -27,8 +27,8 @@ class _ConvBase(eqx.Module): Spatial: tuple[str | Axis, ...] = eqx.field(static=True) In: Axis = eqx.field(static=True) Out: Axis = eqx.field(static=True) - weight: NamedArray = eqx.field(static=True) - bias: Optional[NamedArray] = eqx.field(static=True) + weight: NamedArray = eqx.field() + bias: Optional[NamedArray] = eqx.field() def _lhs_dim_spec(self, batch_index, inputs): # the dim spec are single letters, for things like NCHW commit 4f69fe58e82900d391ffe87a13b909d28ac8fd89 Date: 2023-10-15T23:21:04-07:00 Add einops-style `rearrange` (#44) * wip * wip * (ordered) rearrange seems to work pretty well! * unordered tests just work too * cleanup and more tests * cleanup and more tests * cleanup and more tests * cleanup and more tests * cleanup and more tests * expose the combined rearrange * documentation for rearrange * add string alias example * tweak * fix ci * fixup docs diff --git a/docs/rearrange.md b/docs/rearrange.md new file mode 100644 index 0000000..7c68738 --- /dev/null +++ b/docs/rearrange.md @@ -0,0 +1,186 @@ +# Rearrange + +## Introduction + +Haliax strives to be "order independent": the order of axes should not impact the correctness of the program. However, +when interfacing with non-named APIs (e.g. the JAX Numpy API or Equinox), you have to be able to know exactly what the +order of axes is. In addition, the order of axes can impact performance. To that end, Haliax provides a `rearrange` +function that allows you to specify the order of axes in a tensor. + +In addition, it is sometimes necessary to split and merge axes: turning images into patches, +or turning a batch of images into a single image. Without `rearrange`, this is a bit clunky. + +`rearrange` comes in two flavors: sequence syntax and einops-style syntax. Sequence +syntax is just for transposing axes, while [einops-style](https://einops.rocks/) syntax is more +powerful and can also split and merge axes. + +## Sequence Syntax + +The sequence syntax is very simple: you just provide a sequence of axis names, and the tensor +will be rearranged to match that sequence. For example: + +```python +import haliax as hax +import jax.random as jrandom + +N = hax.Axis("N", 32) +C = hax.Axis("C", 3) +H = hax.Axis("H", 64) +W = hax.Axis("W", 64) + +x = hax.random.normal(jrandom.PRNGKey(0), (N, C, H, W)) + +y = hax.rearrange(x, (N, H, W, C)) + +# at most one ellipsis is allowed +z = hax.rearrange(x, (N, ..., C)) + +# you can use strings instead of axis objects +z = hax.rearrange(x, ("N", ..., "C")) +``` + +As we said before, almost all Haliax operations are order-agnostic, so (this version of) `rearrange` only impacts +performance and allows you to interface with other libraries that need you to specify the order of axes +for an unnamed tensor. + +## Einops-style Syntax + +[einops](https://einops.rocks/) is a powerful library for manipulating tensor shapes, generalizing +`reshape`, `transpose`, and other shape-manipulation operations. Haliax provides a subset of its functionality +(specifically `rearrange` and not `repeat` or `reduce`, which are less useful in named code). The syntax has been generalized to named +tensors. + +If you're used to einops, the syntax should be familiar, with the main differences being specifying names +and the additional "unordered" syntax for selecting dimensions by name. + +!!! warning + This syntax is fairly new. It is pretty well-tested, but it is possible that there are bugs. + +### Examples + +Examples are probably the best way to get a feel for the syntax: + +```python +import haliax as hax +import jax.random as jrandom + +N = hax.Axis("N", 32) +C = hax.Axis("C", 3) +H = hax.Axis("H", 64) +W = hax.Axis("W", 64) + +x = hax.random.normal(jrandom.PRNGKey(0), (N, C, H, W)) + +# transpose/permute axes +y = hax.rearrange(x, "N C H W -> N H W C") +# names don't have to match with positional syntax +z = hax.rearrange(x, "num ch h w -> num h w ch") +# ellipsis can be used to specify the rest of the dimensions +z = hax.rearrange(x, "N C ... -> N ... C") + +# unordered patterns allow you to match a subset of dimensions by name, rather than using positional matching +# transpose last two dimensions using the unordered syntax +y = hax.rearrange(x, "{H W} -> ... W H") + +# don't know the order? use an unordered pattern +y = hax.rearrange(x, "{W C H N} -> N H W C") + +# split dims as in einops +y = hax.rearrange(x, "(step microbatch) ... -> step microbatch ...", step=4) +# splitting dims can be done using unordered syntax, similar to positional syntax +y = hax.rearrange(x, "{(N: step microbatch) ...} -> step microbatch ...", step=4) + +# merging dims requires a name +x = hax.rearrange(y, "step microbatch ... -> (N: step microbatch) ...") + +# some fancier examples + +# split into patches +y = hax.rearrange(x, "N C (patch_h H) (patch_w W) -> N (P: patch_h patch_w) C H W", H=4, W=4) +# unordered version +y = hax.rearrange(x, "{(H: patch_h H) (W: patch_w W) C } -> ... (P: patch_h patch_w) C H W", H=4, W=4) + +# split into patches, then merge patches and channels +y = hax.rearrange(x, "N C (patch_h H) (patch_w W) -> N (P: patch_h patch_w) (C: C H W)", H=4, W=4) +# unordered version +y = hax.rearrange(x, "{(H: patch_h H) (W: patch_w W) C } -> ... (P: patch_h patch_w) (C: C H W)", H=4, W=4) +``` + +### Bindings: Aliasing and Sizing + +In the above examples we used keyword arguments to give sizes to split axes, which is the same +as in einops. However, we can also use bindings to alias axes. For example: + +```python +# this produces the same result as the previous example +y2 = hax.rearrange(x, "N C (patch_h foo) (patch_w bar) -> N (P: patch_h patch_w) (C: C foo bar)", foo=hax.Axis("H", 4), bar=hax.Axis("W", 4)) +assert y.axes == y2.axes +``` + +This example is a bit contrived, but the point is that this syntax lets us use shorter or different names in the string, +which is occasionally useful. + +You can actually pass in a string alias instead of an axis object, and it will be converted to an axis object for you: +For instance, if we wanted "P" to actually be called "patch", but wanted to keep the short syntax, we could do: + +```python +y3 = hax.rearrange(x, "N C (nh ph) (nw pw) -> N (P: nh nw) (C: C ph pw)", P="patch", pw=4, ph=4) +``` + + +### Differences from einops + +As you may have noticed, there are some differences from einops: + +* Merged axes must have a name: `(C: C H W)` instead of `(C H W)`. +* The unordered syntax with `{ }` is new: you select dimensions by name instead of by position. +* As discussed immediately above, you can use bindings to specify axis objects for names as well as sizes. + +### Syntax + +Semiformally, the syntax is an `lhs -> rhs` pair, where the `lhs` is either ordered or unordered, and the `rhs` is always ordered. +For the `lhs`: + +* An *ordered lhs* is a sequence of axis variables (e.g. `x`) or (named or anonymous) split axes (e.g. `(x y)`), separated by spaces or commas, and up to one ellipsis +* An *unordered lhs* is a sequence of axis names (e.g. `x`, where `x` is an axis name in the input array) or named split axes (e.g. `(x: y z)`), surrounded by `{}`, separated by spaces or commas. + +* An *axis variable* is an identifier (that need not correspond to an axis name in the input or output.) +* An *axis name* is an identifier that corresponds to an axis name in the input or output. +* An *anonymous split axis* is a parenthesized expression of the form `(ident*)`, e.g. `(N C)`. +* A *named split axis* is a parenthesized expression of the form `(name: ident*)`, where `name` is the name of an axis and the `ident` are axis variable names, e.g. `(N: s mb)` + +A note on "axis variable" vs "axis name": the former is an identifier that can refer to any axis and is matched +by **position** in the input, while the latter is an identifier that refers to a specific axis and is matched by **name** in the input +(or used to name an axis in the output). + +The `rhs` is always ordered. Its syntax is similar to an ordered `lhs`, except that merged axes must always be named. + +* *rhs* is a sequence of axis variable names or named merged axes, separated by spaces or commas, and up to one ellipsis. + +* *Named merged axes* are parenthesized expressions of the form `(name: ident ident ...)`, where `name` is an axis name and `ident` is an identifier. +The name is used to name the merged axis in the output, and the `ident` are axis variable names that are merged from the input. + +Identifiers in the `rhs` must be "bound" by an identifier in the `lhs`, that is, they must appear in the `lhs` as an *axis variable name*. + +As in einops: split and merged axes are processed in "C-order": the first dimension is the most significant, and the +last dimension is the least significant. + + +## Error Handling + +`rearrange` attempts to be as helpful as possible when it encounters errors. For example: + +```python +y = hax.rearrange(x, "N C H W Z -> N H W C") +# ValueError: Error while parsing: +# N C H W Z -> N H W C +# ^ +# Too many axes in lhs +``` + +In general, it will try to give you a helpful error message that points to the problem in the string. + + +## API Documentation + +See [haliax.rearrange][]. diff --git a/mkdocs.yml b/mkdocs.yml index 53d98fa..a3608ea 100644 --- a/mkdocs.yml +++ b/mkdocs.yml @@ -81,6 +81,7 @@ nav: - Named Arrays: - Broadcasting: 'broadcasting.md' - Indexing and Slicing: 'indexing.md' + - Rearrange: 'rearrange.md' - Neural Networks: 'nn.md' - Partitioning: 'partitioning.md' - Higher Order Functions: 'hof.md' diff --git a/src/haliax/__init__.py b/src/haliax/__init__.py index 7010adc..ab738b4 100644 --- a/src/haliax/__init__.py +++ b/src/haliax/__init__.py @@ -10,6 +10,7 @@ import haliax.nn as nn import haliax.random as random import haliax.tree_util as tree_util +from ._src.rearrange import rearrange from .axis import Axis, AxisSelection, AxisSelector, AxisSpec, axis_name, concat_axes, eliminate_axes, selects_axis from .core import ( NamedArray, @@ -25,7 +26,6 @@ from .core import ( index, named, ravel, - rearrange, rename, roll, slice, @@ -834,7 +834,7 @@ __all__ = [ "take", "unbind", "rename", - "rearrange", + "einops_rearrange", "zeros", "ones", "full", diff --git a/src/haliax/_src/rearrange.py b/src/haliax/_src/rearrange.py new file mode 100644 index 0000000..4b3356e --- /dev/null +++ b/src/haliax/_src/rearrange.py @@ -0,0 +1,748 @@ +# Support for einops-style rearrangement strings, but supporting named axes and unordered matching +import dataclasses +import typing +from types import EllipsisType +from typing import Mapping, NoReturn, Optional, Sequence + +import jax.lax +import jax.numpy as jnp + +from ..axis import Axis, AxisSelector, axis_name +from ..core import NamedArray +from ..partitioning import auto_sharded + + +@dataclasses.dataclass +class _AxisCapture: + binding: Optional[str] = None + axes: tuple[str, ...] = () + char_range: Optional[tuple[int, int]] = None + + def __post_init__(self): + if len(self.axes) == 0: + raise ValueError("Empty axes not allowed") + + +@dataclasses.dataclass +class Expression: + captures: Sequence[_AxisCapture | EllipsisType] + is_ordered: bool + + +def _raise_error(message: str, expression: str, pos: Optional[int | tuple[int, int]]) -> NoReturn: + """Raise a ValueError with a message and the position in the expression.""" + fmt = f"Error while parsing:\n {expression}" + if pos is not None: + if isinstance(pos, int): + fmt += f'\n {" " * pos}^' + else: + fmt += f"\n {' ' * pos[0]}{'^' * max(1, pos[1] - pos[0])}" + + fmt += f"\n{message}" + + raise ValueError(fmt) + + +def _parse_quoted_string(expression: str, pos: int) -> tuple[str, int]: + """Parse a quoted string from an einops-style haliax rearrangement string.""" + + if expression[pos] not in "'\"": + _raise_error(f"Expected \" or ' at position {pos}", expression, pos) + quote = expression[pos] + pos += 1 + ident = "" + while pos < len(expression): + if expression[pos] == quote: + pos += 1 + break + elif expression[pos] == "\\": + pos += 1 + if pos >= len(expression): + _raise_error(f"Unexpected end of string at position {pos}", expression, pos) + ident += expression[pos] + pos += 1 + continue + else: + ident += expression[pos] + pos += 1 + continue + if len(ident) == 0: + _raise_error("Empty strings are not valid identifiers", expression, pos) + + return ident, pos + + +def _parse_ident(expression: str, pos: int) -> tuple[str, int]: + """parses an identifier or string literal from an einops-style haliax rearrangement string.""" + if expression[pos] in "'\"": + return _parse_quoted_string(expression, pos) + else: + ident = "" + while pos < len(expression): + if str.isalnum(expression[pos]) or expression[pos] == "_": + if len(ident) == 0 and str.isdigit(expression[pos]): + _raise_error("Identifiers cannot start with a number", expression, pos) + ident += expression[pos] + pos += 1 + continue + else: + break + if len(ident) == 0: + _raise_error("Identifier expected", expression, pos) + + return ident, pos + + +def _parse_group(expression, pos): + # parses a group of axes like (a b c) or (a: b c) + pos_in = pos + if expression[pos] != "(": + raise ValueError("Expected (") + pos += 1 + binding = None + axes = [] + current_ident = "" + while pos < len(expression): + if expression[pos] == ")": + pos += 1 + break + elif expression[pos] == ":": + if binding is not None: + _raise_error("Only one binding allowed per group", expression, pos) + if not current_ident: + _raise_error("Binding cannot be empty", expression, pos) + if len(axes) > 0: + _raise_error("Binding must come before axes", expression, pos) + binding = current_ident + current_ident = "" + pos += 1 + continue + elif str.isspace(expression[pos]) or expression[pos] == ",": + if current_ident: + axes.append(current_ident) + current_ident = "" + pos += 1 + continue + elif expression[pos] == "(": + _raise_error("Only one level of nesting is allowed", expression, pos) + elif expression[pos] == "}": + raise ValueError(f"Unexpected }} at {pos}") + elif str.isalnum(expression[pos]) or expression[pos] == "_": + # don't allow numbers at the start of an identifier + if len(current_ident) == 0 and str.isdigit(expression[pos]): + _raise_error("Identifiers cannot start with a number", expression, pos) + current_ident += expression[pos] + pos += 1 + continue + elif expression[pos] in "'\"": + # parse quoted string as identifier + if current_ident: + axes.append(current_ident) + + ident, pos = _parse_quoted_string(expression, pos) + current_ident = ident + continue + else: + _raise_error(f"Unexpected character {expression[pos]}", expression, pos) + + if current_ident: + axes.append(current_ident) + + if len(axes) == 0: + _raise_error("No axes found", expression, pos_in) + + # todo: should we allow anonymous/literal + char_range = (pos_in, pos) + return _AxisCapture(binding, tuple(axes), char_range), pos + + +def _parse_expression(expression: str, pos) -> tuple[Expression, int]: + """Parse one side of an einops-style haliax rearrangement string.""" + captures = [] + is_ordered = True + seen_char = False + finished = False + + while pos < len(expression): + if expression[pos] == "{": + if seen_char: + _raise_error("Unexpected {", expression, pos) + seen_char = True + is_ordered = False + pos += 1 + continue + elif expression[pos] == "}": + if is_ordered: + _raise_error("Unexpected }", expression, pos) + pos += 1 + finished = True + continue + elif expression[pos] == "(": + if finished: + _raise_error("Unexpected ( after }", expression, pos) + seen_char = True + capture, pos = _parse_group(expression, pos) + captures.append(capture) + continue + elif str.isspace(expression[pos]) or expression[pos] == ",": + pos += 1 + continue + elif expression[pos : pos + 3] == "...": + seen_char = True + if finished: + _raise_error("Unexpected ... after }", expression, pos) + captures.append(Ellipsis) + pos += 3 + continue + elif expression[pos] == "-": + if not seen_char: + _raise_error("Unexpected -", expression, pos) + if pos + 1 >= len(expression): + _raise_error("Unexpected end of string", expression, pos) + if expression[pos + 1] != ">": + _raise_error("Expected >", expression, pos) + break + else: + if finished: + _raise_error("Unexpected character after }", expression, pos) + ident, new_pos = _parse_ident(expression, pos) + captures.append(_AxisCapture(binding=ident, axes=(ident,), char_range=(pos, new_pos))) + seen_char = True + pos = new_pos + continue + + if not finished and not is_ordered: + _raise_error("Expected }", expression, pos) + + return Expression(captures, is_ordered), pos + + +def parse_rearrangement(expression: str) -> tuple[Expression, Expression]: + """Parse an einops-style haliax rearrangement string.""" + pos = 0 + lhs, pos = _parse_expression(expression, pos) + + # consume the -> + if pos + 2 >= len(expression): + _raise_error("Unexpected end of string", expression, pos) + if expression[pos : pos + 2] != "->": + _raise_error("Expected ->", expression, pos) + + pos += 2 + rhs, pos = _parse_expression(expression, pos) + + # make sure we consumed the whole string + if pos != len(expression): + _raise_error("Unexpected character", expression, pos) + + return lhs, rhs + + +@dataclasses.dataclass +class _Plan: + intermediate_axes: tuple[Axis, ...] + transpose: Optional[tuple[int, ...]] + needs_final_reshape: bool + + final_axes: tuple[Axis, ...] + + +@typing.overload +def rearrange(array: NamedArray, axes: Sequence[AxisSelector | EllipsisType]) -> NamedArray: + pass + + +@typing.overload +def rearrange(array: NamedArray, expression: str, **bindings: AxisSelector | int) -> NamedArray: + pass + + +def rearrange(array: NamedArray, *args, **kwargs) -> NamedArray: + """ + Rearrange a tensor according to an einops-style haliax rearrangement string or a sequence of axes. + See full documentation here: [Rearrange](https://haliax.readthedocs.io/en/latest/rearrange/) + + The sequence form of `rearrange` rearranges an array so that its underlying storage conforms to axes. + axes may include up to 1 ellipsis, indicating that the remaining axes should be + permuted in the same order as the array's axes. + + For example, if array has axes (a, b, c, d, e, f) and axes is (e, f, a, ..., c), + then the output array will have axes (e, f, a, b, c, d). + + The string form of `rearrange` works similarly to einops.rearrange, but also supports named axes and unordered matching. + The string form of `rearrange` comes in two forms: + + * **Ordered strings** are like einops strings, with the only significant difference that flattened axes are named with + a colon, e.g. `B H W C -> B (E: H W C)`. + * **Unordered strings** match axes by name and are marked with the addition of curly braces, + e.g. `{H W C} -> ... C H W` or `{H W C} -> ... (E: H W C)` + + As with einops, you can provide axis sizes to unflatten axes. For instance, to turn an image patches, + `hax.rearrange(x, '{ B (H: w1 H) (W: w1 W)} -> (B: B h1 w1) H W ...', H=32, W=32) + will turn a batch of images into a batch of image patches. Bindings can also be [haliax.Axis][] objects, + or strings that will be used as the actual name of the resulting axis. + + Examples: + >>> import haliax as hax + >>> import jax.random as jrandom + >>> B, H, W, C = hax.Axis("B", 8), hax.Axis("H", 32), hax.Axis("W", 32), hax.Axis("C", 3) + >>> x = hax.random.normal( (B, H, W, C)) + >>> # Sequence-based rearrange + >>> hax.rearrange(x, (C, B, H, W)) + >>> hax.rearrange(x, (C, ...)) # ellipsis means "keep the rest of the axes in the same order" + >>> # String-based rearrange + >>> # permute the axes + >>> hax.rearrange(x, "B H W C -> C B H W") + >>> # flatten the image (note the assignment of a new name to the flattened axis) + >>> hax.rearrange(x, "B H W C -> B (E: H W C)") + >>> # turn the image into patches + >>> hax.rearrange(x, "{ B (H: h1 H) (W: w1 W) C } -> (B: B h1 w1) (E: H W C) ...", H=2, W=2) + >>> # names can be longer than one character + >>> hax.rearrange(x, "{ B (H: h1 H) (W: w1 W) C } -> (B: B h1 w1) (embed: H W C) ...", H=2, W=2) + """ + + if len(args) == 1: + axes = args[0] + if isinstance(axes, str): + return einops_rearrange(array, axes, **kwargs) + else: + return axis_spec_rearrange(array, axes) + elif len(args) > 1: + raise TypeError("Only one positional argument allowed") + + kwargs = dict(kwargs) + expression = kwargs.pop("expression", None) + if expression is not None: + return einops_rearrange(array, expression, **kwargs) + else: + axes = kwargs.pop("axes", None) + if axes is None: + raise TypeError("Must specify either axes or expression") + return axis_spec_rearrange(array, axes) + + +def axis_spec_rearrange(array: NamedArray, axes: Sequence[AxisSelector | EllipsisType]) -> NamedArray: + if len(axes) == 0 and len(array.axes) != 0: + raise ValueError("No axes specified") + + # various fast paths + if len(axes) == 1 and axes[0] is Ellipsis: + return array + + if axes == array.axes: + return array + + if axes[-1] is Ellipsis and array.axes[0 : len(axes) - 1] == axes[0 : len(axes) - 1]: + return array + + if axes[0] is Ellipsis and array.axes[len(axes) - 1 :] == axes[1:]: + return array + + if axes.count(Ellipsis) > 1: + raise ValueError("Only one ellipsis allowed") + + used_indices = [False] * len(array.axes) + permute_spec: list[int | EllipsisType] = [] + ellipsis_pos = None + for ax in axes: + if ax is Ellipsis: + permute_spec.append(Ellipsis) # will revisit + ellipsis_pos = len(permute_spec) - 1 + else: + assert isinstance(ax, Axis) or isinstance(ax, str) # please mypy + index = array._lookup_indices(ax) + if index is None: + raise ValueError(f"Axis {ax} not found in {array}") + if used_indices[index]: + raise ValueError(f"Axis {ax} specified more than once") + used_indices[index] = True + permute_spec.append(index) + + if not all(used_indices): + # find the ellipsis position, replace it with all the unused indices + if ellipsis_pos is None: + missing_axes = [ax for i, ax in enumerate(array.axes) if not used_indices[i]] + raise ValueError(f"Axes {missing_axes} not found and no ... specified. Array axes: {array.axes}") from None + + permute_spec[ellipsis_pos : ellipsis_pos + 1] = tuple(i for i in range(len(array.axes)) if not used_indices[i]) + elif ellipsis_pos is not None: + permute_spec.remove(Ellipsis) + + out_axes = tuple(array.axes[i] for i in typing.cast(list[int], permute_spec)) + return NamedArray(jnp.transpose(array.array, permute_spec), out_axes) + + +def einops_rearrange(array: NamedArray, expression: str, **bindings: AxisSelector | int) -> NamedArray: + lhs, rhs = parse_rearrangement(expression) + + # the fundamental xla op for rearranging is reshape, which combines both transpose and reshape + # all rearranges are fundamentally a reshape, followed by a transpose, followed by a reshape + # as an example of an op that needs both, consider: + # '(a b) c d -> (c a) (b d)' + # where a = 2, b = 3, c = 4, d = 5 + # which is equivalent to: + # x.reshape((2, 3, 4, 5)).transpose((2, 0, 1, 3)).reshape((4 * 2, 3 * 5)) + plan = _plan_rearrange(expression, lhs, rhs, array, bindings) + + raw_array = array.array + + if plan.intermediate_axes != array.axes: + raw_array = raw_array.reshape([ax.size for ax in plan.intermediate_axes]) + array = NamedArray(raw_array, plan.intermediate_axes) + array = auto_sharded(array) + raw_array = array.array + + final_shape = tuple(ax.size for ax in plan.final_axes) + + if plan.needs_final_reshape: + finished_array = jax.lax.reshape(raw_array, new_sizes=final_shape, dimensions=plan.transpose) + elif plan.transpose is not None: + finished_array = jax.lax.transpose(raw_array, permutation=plan.transpose) + else: + finished_array = raw_array + + return auto_sharded(NamedArray(finished_array, plan.final_axes)) + + +def _plan_rearrange( + original_str, lhs: Expression, rhs: Expression, array: NamedArray, input_bindings: Mapping[str, AxisSelector | int] +) -> _Plan: + aliases = _resolve_bindings(array, input_bindings) + grouped_new_shapes = _determine_initial_reshape(original_str, lhs, array, aliases) + intermediate_axes = tuple(ax for split_axes in grouped_new_shapes for ax in split_axes) + + transpose: Optional[tuple[int, ...]] + transpose, final_axes = _determine_final_transpose_and_reshape(original_str, rhs, aliases, intermediate_axes) + + transposed_intermediate_axes = tuple(intermediate_axes[i] for i in transpose) + if transposed_intermediate_axes == final_axes: + needs_final_reshape = False + else: + needs_final_reshape = True + + if transpose == tuple(range(len(transpose))): + transpose = None + + return _Plan(intermediate_axes, transpose, needs_final_reshape, final_axes) + + +class AliasTable: + bindings: dict[str, AxisSelector] # names in the string to either axes or + + def __init__(self, bindings): + self.bindings = bindings + + def dealias_binding(self, binding: str) -> Optional[AxisSelector]: + return self.bindings.get(binding, None) + + def bind_alias(self, alias: str, axis: Axis, expr, char_range): + if axis.name in self.bindings: + if self.bindings[alias] != axis: + _raise_error(f"Alias {alias} is assigned to more than one axis", expr, char_range) + else: + self.bindings[alias] = axis + + +def _resolve_bindings(array, bindings: Mapping[str, Axis | str | int]) -> AliasTable: + b: dict[str, AxisSelector] = {} + for name, selector in bindings.items(): + if isinstance(selector, str): + try: + selector = array.resolve_axis(selector) + except ValueError: + pass + elif isinstance(selector, int): + selector = Axis(name, selector) + assert not isinstance(selector, int) + b[name] = selector + return AliasTable(b) + + +def _determine_final_transpose_and_reshape( + expression, rhs: Expression, aliases: "AliasTable", intermediate_axes: tuple[Axis, ...] +) -> tuple[tuple[int, ...], tuple[Axis, ...]]: + # The rhs tells us two things: + # 1. how to reorder the intermediate axes + # 2. how to merge the intermediate axes into the final axes + + transposition_order: list[int | EllipsisType] = [] + + final_axes: list[Axis | EllipsisType] = [] + used_axes = set() # axes must be used exactly once + + position_of_ellipsis = None # If there's an ellipsis, we want to put any remaining axes there + position_of_ellipsis_in_transposition = None # if there's an ellipsis, we want to put any remaining axes there + + # each capture, except for ellipsis results in one final axis + for cpos, capture in enumerate(rhs.captures): + if capture == Ellipsis: + if position_of_ellipsis is not None: + previous_capture = rhs.captures[cpos - 1] + _raise_error("Only one ellipsis allowed", expression, previous_capture.char_range) + position_of_ellipsis = cpos + final_axes.append(Ellipsis) + transposition_order.append(Ellipsis) + position_of_ellipsis_in_transposition = len(transposition_order) - 1 + continue + + assert not isinstance(capture, EllipsisType) + + binding = capture.binding + if binding is None: + _raise_error("All rhs axes must have a name. Use (name: bindings)", expression, capture.char_range) + + # now look at the captured axes. these are the axes that we're going to merge into one final axis + # we're also going to move them around to match the order of the intermediate axes + sz = 1 + for ax_name in capture.axes: + axis = aliases.dealias_binding(ax_name) + if not isinstance(axis, Axis): + _raise_error(f"Axis {ax_name} is not bound on the lhs", expression, capture.char_range) + + if axis in used_axes: + _raise_error(f"Axis {axis} is used more than once", expression, capture.char_range) + used_axes.add(axis) + + sz *= axis.size + # now find the position of this axis in the intermediate axes + try: + index_in_intermediate = intermediate_axes.index(axis) + transposition_order.append(index_in_intermediate) + except ValueError: + _raise_error(f"Axis {ax_name} is not in the lhs", expression, capture.char_range) + + # figure out the name of the final axis + axis = aliases.dealias_binding(binding) + if axis is None: + new_axis = Axis(binding, sz) + else: + new_axis = Axis(axis_name(axis), sz) + + # Do not bind here because axis names can be reused + + final_axes.append(new_axis) + + if position_of_ellipsis is not None: + unused_intermediate_axes = [ax for ax in intermediate_axes if ax not in used_axes] + if len(unused_intermediate_axes) > 0: + # we need to put the unused axes in the ellipsis + final_axes = ( + final_axes[:position_of_ellipsis] + unused_intermediate_axes + final_axes[position_of_ellipsis + 1 :] + ) + + unused_indices = [i for i in range(len(intermediate_axes)) if intermediate_axes[i] not in used_axes] + + assert position_of_ellipsis_in_transposition is not None + + transposition_order = ( + transposition_order[:position_of_ellipsis_in_transposition] + + unused_indices + + transposition_order[position_of_ellipsis_in_transposition + 1 :] + ) + + else: + # make sure we used all the axes + if len(used_axes) < len(intermediate_axes): + # figure out their binding names as possible: + inverse_bindings = {v: k for k, v in aliases.bindings.items()} + unused_intermediate_axis_names = [ + inverse_bindings.get(ax, ax.name) for ax in intermediate_axes if ax not in used_axes + ] + _raise_error( + f"Not all intermediate axes are used: {','.join(unused_intermediate_axis_names) }", + expression, + len(expression) - 1, + ) + + return tuple(transposition_order), tuple(final_axes) # type: ignore + + +def _determine_initial_reshape( + expression, + lhs: Expression, + array: NamedArray, + aliases: AliasTable, +) -> list[list[Axis]]: + # MUTATES `aliases` + # the lhs all need to be bound to axes in the array, or synthesized as parts of axes. + # In the lhs, bindings look like either a name, or a name and a list of (new) axes. + # bindings can either be done by name, or by position, depending on if lhs.is_ordered + new_shapes: list[Optional[list[Axis]]] = [None] * len(array.axes) + used_new_names: set[str] = set() # names can only be used once on a side + + # one subtle difference between the lhs and the rhs is the handling of binding in expressions like (a: b c) + # in the lhs, this means that a is bound to an axis, and b and c are split out from a + # in the rhs, this means that b and c must already be bound to axes, and a is a new axis name + # this makes sense in the same way that pattern matching works + + if lhs.is_ordered: + # if we start with an ellipsis, we bind from the right + # if we end with an ellipsis, we bind from the left + ellipsis_pos = None + axis_index_for_capture: list[Optional[int]] = [None] * len(lhs.captures) + covered_axes = set() + # bind from the left + axis_pos = 0 + for cpos, capture in enumerate(lhs.captures): + if capture == Ellipsis: + if ellipsis_pos is not None: + assert False, "should not be here" # pragma: no cover + ellipsis_pos = cpos + break + + assert not isinstance(capture, EllipsisType) + + if axis_pos >= len(array.axes): + _raise_error("Too many axes in lhs", expression, capture.char_range) + + axis_index_for_capture[cpos] = axis_pos + covered_axes.add(axis_pos) + axis_pos += 1 + + # bind from the right, take care to check second ellipsis + if ellipsis_pos is not None: + axis_pos = len(array.axes) - 1 + for cpos in range(len(lhs.captures) - 1, ellipsis_pos, -1): + capture = lhs.captures[cpos] + if capture == Ellipsis: + _raise_error("Only one ellipsis allowed", expression, None) + + assert not isinstance(capture, EllipsisType) + + axis_index_for_capture[cpos] = axis_pos + if axis_pos in covered_axes: + _raise_error( + f"Axis {array.axes[axis_pos]} is bound more than once", + expression, + capture.char_range, + ) + covered_axes.add(axis_pos) + axis_pos -= 1 + else: + # no ellipsis, so we need to check that we covered all axes + if len(covered_axes) < len(array.axes): + _raise_error( + "Not all axes are bound, use ... to skip missing axes", expression, len(expression) - 1 + ) # type: ignore + elif len(covered_axes) > len(array.axes): + _raise_error("Too many axes are bound", expression, lhs.captures[-1].char_range) # type: ignore + + # now that we have the bindings, we can figure out the new shapes + for cpos, capture in enumerate(lhs.captures): + if capture == Ellipsis: + continue + assert not isinstance(capture, EllipsisType) + + axis_index = axis_index_for_capture[cpos] + if axis_index is None: + _raise_error("Internal error", expression, capture.char_range) + + axis = array.axes[axis_index] + if new_shapes[axis_index] is not None: + _raise_error(f"Axis {axis} is bound more than once", expression, capture.char_range) + + new_axes = _solve_split_axes(axis, capture, aliases, used_new_names, expression) + new_shapes[axis_index] = new_axes # type: ignore + + else: + # we just need to bind the axes in the lhs to the axes in the array + for capture in lhs.captures: + # ellipses are ignored in unordered rearrangements + if capture == Ellipsis: + continue + + assert not isinstance(capture, EllipsisType) + + if capture.binding is None: + _raise_error( + "Unordered axes must be bound by name, e.g. (a: b) or just a", expression, capture.char_range + ) + + # let's see if we're aliasing it in the bindings + maybe_alias = aliases.dealias_binding(capture.binding) + if maybe_alias is None: + maybe_alias = capture.binding + else: + maybe_alias = axis_name(maybe_alias) + + try: + axis = array.resolve_axis(maybe_alias) + # aliases.bind_alias(capture.binding, axis, expression, capture.char_range) + except ValueError: + _raise_error(f"Could not resolve axis {maybe_alias}", expression, capture.char_range) + + try: + axis_index = array.axes.index(axis) + except ValueError: + _raise_error(f"Axis {axis} is not in the array", expression, capture.char_range) + if new_shapes[axis_index] is not None: + _raise_error(f"Axis {axis} is bound more than once", expression, capture.char_range) + + new_axes = _solve_split_axes(axis, capture, aliases, used_new_names, expression) + new_shapes[axis_index] = new_axes # type: ignore + + for i in range(len(array.axes)): + if new_shapes[i] is None: + new_shapes[i] = [array.axes[i]] + + return new_shapes # type: ignore + + +def _solve_split_axes(axis, capture, aliases, used_new_names, expression): + """ + Given an axis and a capture of the form (a: b c) or (b c) on the lhs, solve for the new axes. + """ + new_axes: list[Optional[Axis]] = [] + unsolved_axis_index: Optional[int] = None + + # easy case: 1 axis in capture + if len(capture.axes) == 1: + new_axis_name = capture.axes[0] + if new_axis_name in used_new_names: + _raise_error(f"Capture {new_axis_name} is assigned more than once", expression, capture.char_range) + used_new_names.add(new_axis_name) + + new_axes.append(axis) + aliases.bind_alias(new_axis_name, axis, expression, capture.char_range) + + return new_axes + + remaining_size = axis.size + + for new_axis_name in capture.axes: + if new_axis_name in used_new_names: + _raise_error(f"Capture {new_axis_name} is assigned more than once in lhs", expression, capture.char_range) + + used_new_names.add(new_axis_name) + + new_axis = aliases.dealias_binding(new_axis_name) + if new_axis is None: + new_axis = new_axis_name + + if isinstance(new_axis, Axis): + new_axes.append(new_axis) + if remaining_size % new_axis.size: + _raise_error(f"Axes do not divide evenly into axis {axis}", expression, capture.char_range) + remaining_size //= new_axis.size + else: + if unsolved_axis_index is not None: + _raise_error( + "Sizes for this split axis are ambiguous. You must provide a size as a kwarg.", + expression, + capture.char_range, + ) + unsolved_axis_index = len(new_axes) + new_axes.append(None) + + if unsolved_axis_index is not None: + # we need to solve for this axis + unsolved_alias = aliases.dealias_binding(capture.axes[unsolved_axis_index]) + assert not isinstance(unsolved_alias, Axis) + if unsolved_alias is None: + unsolved_alias = capture.axes[unsolved_axis_index] + assert isinstance(unsolved_alias, str) + + new_axis = Axis(unsolved_alias, remaining_size) + new_axes[unsolved_axis_index] = new_axis + aliases.bind_alias(capture.axes[unsolved_axis_index], new_axis, expression, capture.char_range) + return new_axes diff --git a/src/haliax/core.py b/src/haliax/core.py index 360d7c2..e187dc1 100644 --- a/src/haliax/core.py +++ b/src/haliax/core.py @@ -5,7 +5,7 @@ import warnings from dataclasses import dataclass from math import prod from types import EllipsisType -from typing import Any, Dict, List, Mapping, Optional, Sequence, Tuple, Union, cast, overload +from typing import Any, Dict, List, Mapping, Optional, Sequence, Tuple, Union, overload import jax import jax.numpy as jnp @@ -212,7 +212,7 @@ class NamedArray: # Axis rearrangement def rearrange(self, axis: Sequence[Union[AxisSelector, EllipsisType]]) -> "NamedArray": - return rearrange(self, axis) + return haliax.rearrange(self, axis) def broadcast_to(self, axes: AxisSpec) -> "NamedArray": axes = ensure_tuple(axes) @@ -1001,73 +1001,6 @@ def split(a: NamedArray, axis: AxisSelector, new_axes: Sequence[Axis]) -> Sequen return [NamedArray(x, ax) for x, ax in zip(new_arrays, ret_axes)] -# TODO: can we add einops-style combined split/merge here? -# e.g. we'd like something like rearrange(array, (..., new_axis), merge_axes={new_axis: (old_axis1, old_axis2)}) -# or rearrange(array, (new_axis1, ..., new_axis2), split_axes={old_axis: (new_axis1, new_axis2)}) -# or even rearrange(array, (x, ..., b, a), map_axes={old_axis: (a, b), x: (old1, old2)}) -def rearrange(array: NamedArray, axes: Sequence[Union[AxisSelector, EllipsisType]]) -> NamedArray: - """ - Rearrange an array so that its underlying storage conforms to axes. - axes may include up to 1 ellipsis, indicating that the remaining axes should be - permuted in the same order as the array's axes. - - For example, if array has axes (a, b, c, d, e, f) and axes is (e, f, a, ..., c), - then the output array will have axes (e, f, a, b, c, d). - - Args: - array (NamedArray): The array to rearrange. - axes (Sequence[Union[AxisSelector, EllipsisType]]): The axes to rearrange to. - """ - if len(axes) == 0 and len(array.axes) != 0: - raise ValueError("No axes specified") - - # various fast paths - if len(axes) == 1 and axes[0] is Ellipsis: - return array - - if axes == array.axes: - return array - - if axes[-1] is Ellipsis and array.axes[0 : len(axes) - 1] == axes[0 : len(axes) - 1]: - return array - - if axes[0] is Ellipsis and array.axes[len(axes) - 1 :] == axes[1:]: - return array - - if axes.count(Ellipsis) > 1: - raise ValueError("Only one ellipsis allowed") - - used_indices = [False] * len(array.axes) - permute_spec: List[Union[int, EllipsisType]] = [] - ellipsis_pos = None - for ax in axes: - if ax is Ellipsis: - permute_spec.append(Ellipsis) # will revisit - ellipsis_pos = len(permute_spec) - 1 - else: - assert isinstance(ax, Axis) or isinstance(ax, str) # please mypy - index = array._lookup_indices(ax) - if index is None: - raise ValueError(f"Axis {ax} not found in {array}") - if used_indices[index]: - raise ValueError(f"Axis {ax} specified more than once") - used_indices[index] = True - permute_spec.append(index) - - if not all(used_indices): - # find the ellipsis position, replace it with all the unused indices - if ellipsis_pos is None: - missing_axes = [ax for i, ax in enumerate(array.axes) if not used_indices[i]] - raise ValueError(f"Axes {missing_axes} not found and no ... specified. Array axes: {array.axes}") from None - - permute_spec[ellipsis_pos : ellipsis_pos + 1] = tuple(i for i in range(len(array.axes)) if not used_indices[i]) - elif ellipsis_pos is not None: - permute_spec.remove(Ellipsis) - - out_axes = tuple(array.axes[i] for i in cast(List[int], permute_spec)) - return NamedArray(jnp.transpose(array.array, permute_spec), out_axes) - - def unbind(array: NamedArray, axis: AxisSelector) -> List[NamedArray]: """ Unbind an array along an axis, returning a list of NamedArrays, one for each position on that axis. @@ -1481,7 +1414,6 @@ __all__ = [ "NamedArray", "dot", "named", - "rearrange", "slice", "updated_slice", "index", diff --git a/tests/test_rearrange.py b/tests/test_rearrange.py new file mode 100644 index 0000000..0b58251 --- /dev/null +++ b/tests/test_rearrange.py @@ -0,0 +1,395 @@ +import pytest +from jax.random import PRNGKey + +import haliax as hax +from haliax import Axis +from haliax._src.rearrange import einops_rearrange, parse_rearrangement + + +def _simplify_captures(expr): + def simplify_capture(capture): + if capture == Ellipsis: + return Ellipsis + elif (capture.binding == capture.axes[0] or capture.binding is None) and len(capture.axes) == 1: + return capture.axes[0] + elif capture.binding is None: + return capture.axes + else: + return {capture.binding: capture.axes} + + return [simplify_capture(capture) for capture in expr.captures] + + +def test_parse_rearrangement_simple(): + lhs, rhs = parse_rearrangement("a b c d -> b, c, a, d") + assert lhs.is_ordered + assert _simplify_captures(lhs) == ["a", "b", "c", "d"] + assert rhs.is_ordered + assert _simplify_captures(rhs) == ["b", "c", "a", "d"] + + lhs, rhs = parse_rearrangement("a ... c d -> b c a d") + assert lhs.is_ordered + assert _simplify_captures(lhs) == ["a", Ellipsis, "c", "d"] + assert rhs.is_ordered + assert _simplify_captures(rhs) == ["b", "c", "a", "d"] + + # longer identifiers + lhs, rhs = parse_rearrangement("a_longer b123 c d -> b123 c a_longer d") + assert lhs.is_ordered + assert _simplify_captures(lhs) == ["a_longer", "b123", "c", "d"] + assert rhs.is_ordered + assert _simplify_captures(rhs) == ["b123", "c", "a_longer", "d"] + + +def test_parse_paren_groups(): + lhs, rhs = parse_rearrangement("a (b c) d -> b c a d") + assert lhs.is_ordered + assert _simplify_captures(lhs) == ["a", ("b", "c"), "d"] + assert rhs.is_ordered + assert _simplify_captures(rhs) == ["b", "c", "a", "d"] + + lhs, rhs = parse_rearrangement("a (b: c) (d: e f) -> b c a d") + assert lhs.is_ordered + assert _simplify_captures(lhs) == ["a", {"b": ("c",)}, {"d": ("e", "f")}] + + +def test_parse_unordered(): + lhs, rhs = parse_rearrangement("{a b c d} -> {b c a d}") + assert not lhs.is_ordered + assert _simplify_captures(lhs) == ["a", "b", "c", "d"] + assert not rhs.is_ordered + assert _simplify_captures(rhs) == ["b", "c", "a", "d"] + + lhs, rhs = parse_rearrangement("{(c: a b), d e,} -> (q: a d e) b") + assert not lhs.is_ordered + assert _simplify_captures(lhs) == [{"c": ("a", "b")}, "d", "e"] + assert rhs.is_ordered + assert _simplify_captures(rhs) == [{"q": ("a", "d", "e")}, "b"] + + +def test_parse_quoted_identifiers(): + lhs, rhs = parse_rearrangement("a \"b c\" d -> 'b c' a d") + assert lhs.is_ordered + assert _simplify_captures(lhs) == ["a", "b c", "d"] + assert rhs.is_ordered + assert _simplify_captures(rhs) == ["b c", "a", "d"] + + lhs, rhs = parse_rearrangement("{a \"b c\" (d: 'hello')} -> b c a d") + assert not lhs.is_ordered + assert _simplify_captures(lhs) == ["a", "b c", {"d": ("hello",)}] + assert rhs.is_ordered + assert _simplify_captures(rhs) == ["b", "c", "a", "d"] + + +def test_parse_errors(): + with pytest.raises(ValueError, match="Unexpected end of string"): + parse_rearrangement("a b") + + with pytest.raises(ValueError, match="Expected }"): + parse_rearrangement("{ a -> c") + + with pytest.raises(ValueError, match="Unexpected }"): + parse_rearrangement("a } -> c") + + with pytest.raises(ValueError, match="Unexpected }"): + parse_rearrangement("(a: b } -> c") + + with pytest.raises(ValueError, match="Unexpected character"): + parse_rearrangement("(a b ! -> c d e") + + with pytest.raises(ValueError, match="Identifier expected"): + parse_rearrangement("a b ! -> c d e") + + +# some axes +W = Axis("W", 4) +H = Axis("H", 6) +C = Axis("C", 3) +D = Axis("D", 2) +B = Axis("B", 5) +Q = hax.Axis("Q", B.size * H.size) + +z = hax.random.randint(PRNGKey(0), (B, D, H, W, C), 0, 255) +zq = hax.random.randint(PRNGKey(0), (Q, D, W, C), 0, 255) + + +def test_basic_identity(): + assert einops_rearrange(z, "b d h w c -> b d h w c").axes == (B, D, H, W, C) + assert (einops_rearrange(z, "b d h w c -> b d h w c").array == z.array).all() + + +def test_basic_rearrange_transpose(): + assert einops_rearrange(z, "b d h w c -> b h w d c").axes == (B, H, W, D, C) + # make sure the values are right too + z_t = z.array.transpose((0, 2, 3, 1, 4)) + assert (einops_rearrange(z, "b d h w c -> b h w d c").array == z_t).all() + + +def test_basic_rearrange_unordered(): + assert einops_rearrange(z, "{B D H W C} -> B H W D C").axes == (B, H, W, D, C) + z_t = z.array.transpose((0, 2, 3, 1, 4)) + assert (einops_rearrange(z, "{B D H W C} -> B H W D C").array == z_t).all() + + assert einops_rearrange(z, "{C W H D B} -> B H W D C").axes == (B, H, W, D, C) + assert (einops_rearrange(z, "{C W H D B} -> B H W D C").array == z_t).all() + + +def test_rearrange_with_ellipsis(): + assert einops_rearrange(z, "... w c -> ... c w").axes == (B, D, H, C, W) + assert einops_rearrange(z, "b d ... -> d ... b").axes == (D, H, W, C, B) + + assert einops_rearrange(z, "b ... c -> b c ...").axes == (B, C, D, H, W) + # make sure the values are right too + z_t = z.array.transpose((0, 4, 1, 2, 3)) + assert (einops_rearrange(z, "b ... c -> b c ...").array == z_t).all() + + +def test_rearrange_with_ellipsis_unordered(): + assert einops_rearrange(z, "{W C} -> ... C W").axes == (B, D, H, C, W) + assert einops_rearrange(z, "{B D} -> D ... B").axes == (D, H, W, C, B) + + assert einops_rearrange(z, "{B C} -> B C ...").axes == (B, C, D, H, W) + # make sure the values are right too + z_t = z.array.transpose((0, 4, 1, 2, 3)) + assert (einops_rearrange(z, "{B C} -> B C ...").array == z_t).all() + assert (einops_rearrange(z, "{qqq C} -> qqq C ...", qqq=B).array == z_t).all() + + +def test_rearrange_with_flattening(): + assert einops_rearrange(z, "b d h w c -> d (Q: b h) w c").axes == (D, Q, W, C) + # make sure the values are right too + z_t = z.array.transpose((1, 0, 2, 3, 4)).reshape((D.size, Q.size, W.size, C.size)) + assert (einops_rearrange(z, "b d h w c -> d (Q: b h) w c").array == z_t).all() + + # test with ellipsis + assert einops_rearrange(z, "b d h ... c -> d (Q: b h) ... c").axes == (D, Q, W, C) + # make sure the values are right too + z_t = z.array.transpose((1, 0, 2, 3, 4)).reshape((D.size, Q.size, W.size, C.size)) + assert (einops_rearrange(z, "b d h ... c -> d (Q: b h) ... c").array == z_t).all() + + +def test_rearrange_with_flattening_unordered(): + assert einops_rearrange(z, "{B D H} -> D (Q: B H) ...").axes == (D, Q, W, C) + # make sure the values are right too + z_t = z.array.transpose((1, 0, 2, 3, 4)).reshape((D.size, Q.size, W.size, C.size)) + assert (einops_rearrange(z, "{B D H} -> D (Q: B H) ...").array == z_t).all() + + # test with ellipsis + assert einops_rearrange(z, "{B D H ... C} -> D (Q: B H) ... C").axes == (D, Q, W, C) + # make sure the values are right too + z_t = z.array.transpose((1, 0, 2, 3, 4)).reshape((D.size, Q.size, W.size, C.size)) + assert (einops_rearrange(z, "{B D H ... C} -> D (Q: B H) ... C").array == z_t).all() + + +def test_rearrange_with_unflatten(): + assert einops_rearrange(zq, "(Q: B H) d, w c -> B d H w c", B=5).axes == (B, D, H, W, C) + # make sure the values are right too + z_t = zq.array.reshape((B.size, H.size, D.size, W.size, C.size)).transpose((0, 2, 1, 3, 4)) + assert (einops_rearrange(zq, "(Q: B H) d, w c -> B d H w c", B=5).array == z_t).all() + + # test with explicit axis arg + assert einops_rearrange(zq, "(Q: b H) d, w c -> b d H w c", b=B).axes == (B, D, H, W, C) + # make sure the values are right too + z_t = zq.array.reshape((B.size, H.size, D.size, W.size, C.size)).transpose((0, 2, 1, 3, 4)) + assert (einops_rearrange(zq, "(Q: b H) d, w c -> b d H w c", b=B).array == z_t).all() + + +def test_rearrange_with_unflatten_unordered(): + assert einops_rearrange(zq, "{ (Q: B H) D } -> B D H ... ", B=5).axes == (B, D, H, W, C) + # make sure the values are right too + z_t = zq.array.reshape((B.size, H.size, D.size, W.size, C.size)).transpose((0, 2, 1, 3, 4)) + assert (einops_rearrange(zq, "{ (Q: B H) D } -> B D H ... ", B=5).array == z_t).all() + + # test with explicit axis arg + assert einops_rearrange(zq, "{ (Q: b H) D } -> b D H ... ", b=B).axes == (B, D, H, W, C) + # make sure the values are right too + z_t = zq.array.reshape((B.size, H.size, D.size, W.size, C.size)).transpose((0, 2, 1, 3, 4)) + assert (einops_rearrange(zq, "{ (Q: b H) D } -> b D H ... ", b=B).array == z_t).all() + + +def test_with_unflatten_flatten(): + Z = Axis("Z", B.size * C.size) + assert einops_rearrange(zq, "(Q: B H) d w c -> d (Z: B c) w H", H=H).axes == (D, Z, W, H) + # make sure the values are right too + z_t = ( + zq.array.reshape((B.size, H.size, D.size, W.size, C.size)) + .transpose((2, 0, 4, 3, 1)) + .reshape((D.size, Z.size, W.size, H.size)) + ) + assert (einops_rearrange(zq, "(Q: B H) d w c -> d (Z: B c) w H", H=H).array == z_t).all() + + +def test_with_unflatten_flatten_unordered(): + Z = Axis("Z", B.size * C.size) + assert einops_rearrange(zq, "{ W D C (Q: B H)} -> D (Z: B C) W H", H=H).axes == (D, Z, W, H) + # make sure the values are right too + z_t = ( + zq.array.reshape((B.size, H.size, D.size, W.size, C.size)) + .transpose((2, 0, 4, 3, 1)) + .reshape((D.size, Z.size, W.size, H.size)) + ) + assert (einops_rearrange(zq, "{ W D C (Q: B H)} -> D (Z: B C) W H", H=H).array == z_t).all() + + +def test_semantic_errors(): + with pytest.raises(ValueError, match="Too many axes in lhs"): + einops_rearrange(z, "b d h w c q -> b d h w c q") + + with pytest.raises(ValueError, match="Not all axes are bound"): + einops_rearrange(z, "b d h w -> b d h w c q") + + with pytest.raises(ValueError, match="Too many axes in lhs"): + einops_rearrange(z, "b d h w x y z -> b d h w c q") + + with pytest.raises(ValueError, match="Axis q is not bound on the lhs"): + einops_rearrange(z, "b d h w c -> b d h w c q") + + with pytest.raises(ValueError, match="Only one ellipsis allowed"): + einops_rearrange(z, "b d ... h w c ... -> b d h w c ...") + + with pytest.raises(ValueError, match="Only one ellipsis allowed"): + einops_rearrange(z, "b d ... h w c -> ... b d h w c ...") + + with pytest.raises(ValueError, match="Capture q is assigned more than once"): + einops_rearrange(z, "b d c q q -> b d h w c q") + + with pytest.raises(ValueError, match="is used more than once"): + einops_rearrange(z, "b d c q t -> b d c t q q") + + with pytest.raises(ValueError, match="Capture q is assigned more than once"): + einops_rearrange(z, "b d c (q q) z -> b d h w c q", q=4) + + with pytest.raises(ValueError, match="Not all intermediate axes are used"): + einops_rearrange(z, "b d c q z -> b d c z") + + with pytest.raises(ValueError, match="is bound more than once"): + einops_rearrange(z, "b d c q z ... d e f -> b d c q d e f") + + with pytest.raises(ValueError, match="Axis q is not bound on the lhs"): + einops_rearrange(z, "b d h w c -> b d h w c q") + + with pytest.raises(ValueError, match="Only one ellipsis allowed"): + einops_rearrange(z, "b d ... h w c ... -> b d h w c ...") + + with pytest.raises(ValueError, match="Capture q is assigned more than once"): + einops_rearrange(z, "b d c q q -> b d h w c q") + + with pytest.raises(ValueError, match="Capture q is assigned more than once"): + einops_rearrange(z, "b d c (q q) z -> b d h w c q", q=4) + + with pytest.raises(ValueError, match="Capture q is assigned more than once"): + einops_rearrange(z, "b d c q q -> b d h w c q") + + with pytest.raises(ValueError, match="Not all intermediate axes are used"): + einops_rearrange(z, "b d c q z -> b d c z") + + with pytest.raises(ValueError, match="is bound more than once"): + einops_rearrange(z, "b d c q z ... d e f -> b d c q d e f") + + with pytest.raises(ValueError, match="not divide"): + einops_rearrange(z, "(x y) d c q z -> d c q x y z", x=13, y=17) + + with pytest.raises(ValueError, match="not divide"): + einops_rearrange(z, "(x y) d c q z -> d c q x y z", x=13) + + with pytest.raises(ValueError, match="must have a name"): + einops_rearrange(z, "b d ... h w c -> (b d h w c) ...") + + with pytest.raises(ValueError, match="not bound on the lhs"): + einops_rearrange(z, "b d ... h w c -> (z: w r) ...") + + with pytest.raises(ValueError, match="are ambiguous"): + einops_rearrange(z, "(b q) d ... h w c -> (z: w r) ...") + + with pytest.raises(ValueError, match="more than once"): + einops_rearrange(z, "{B B} -> Z Z") + + with pytest.raises(ValueError, match="must be bound by name"): + einops_rearrange(z, "{(q) } -> (Z: Z Z)") + + with pytest.raises(ValueError, match="Could not resolve"): + einops_rearrange(z, "{(Z: q) } -> (Z: Z Z)") + + +def test_examples(): + # Cases to support: + # identity + # * 'a b c d -> a b c d' or 'a, b, c, d -> a, b, c, d' + assert einops_rearrange(z, "a b c d e -> a b c d e").axes == (B, D, H, W, C) + # merge a and b into m + # * 'a b c d -> (m: a b) c d' + assert einops_rearrange(z, "a b c d e -> (M: a b) c d e").axes == (Axis("M", B.size * D.size), H, W, C) + # > without rearrange or names: x.reshape((a * b, c, d)) + # split a into b and c + # * '(a: b c) d -> b c d' + assert einops_rearrange(zq, "(q: b h) d, w, c -> b h d w c", b=B, h="H").axes == (B, H, D, W, C) + # > without rearrange or names: x.reshape((b, c, d)) + # reorder a and b + # * 'a b ... -> b a ...' + assert einops_rearrange(z, "a b ... -> b a ...").axes == (D, B, H, W, C) + assert einops_rearrange(z, "a b ... -> b ... a").axes == (D, H, W, C, B) + # > without rearrange or names: x.transpose((1, 0, ...)) + # split into 2 groups, rename to x and y + # * 'a b c d -> (x: a b) (y: c d)' # split into two groups, rename to x and y + assert einops_rearrange(z, "a b c d ... -> (x: a b) (y: c d) ...").axes == ( + Axis("x", B.size * D.size), + Axis("y", H.size * W.size), + C, + ) + # > without rearrange or names: x.reshape((a * b, c * d)) + # unordered match of a, b, c by name, move to end + # * `{c b a} -> ... a b c` + assert einops_rearrange(z, "{B C W} -> ... B C W").axes == (D, H, B, C, W) + # > without rearrange or names: x.transpose((2, 1, 0, ...)) + # unordered match of a and d by name, split a into b and c, reorder + # * `{(a: b c) d} -> ... b d c` + assert einops_rearrange(zq, "{(Q: b h) C} -> ... b C h", b=B, h=H).axes == (D, W, B, C, H) + # > without rearrange or names: x.reshape(..., b, c, d).transpose((..., -3, -1, -2)) + # unordered match of a and d by name, split a into b and c, d into e and f, reorder + # * `{(a: b c) (d: e f)} -> ... b e c f` + assert einops_rearrange(zq, "{(Q: b h) (W: e f)} -> ... b e h f", b=B, h=H, e=2).axes == ( + D, + C, + B, + Axis("e", 2), + H, + Axis("f", 2), + ) + # flatten each image into a vector + # * `{h w c} -> (c: c h w)` + assert einops_rearrange(z, "{H W C} -> ... (C: C H W)").axes == (B, D, Axis("C", C.size * H.size * W.size)) + # split each image into 4 smaller (top-left, top-right, bottom-left, bottom-right), 128 = 32 * 2 * 2: + # * `{b (h: h1 h) (w: w1 w)} -> (b: b h1 w1) h w ...` + sH = Axis("H", H.size // 2) + sW = Axis("W", W.size // 2) + # this works right now, would be good to support the below + r = einops_rearrange(z, "{B (H: h1 h) (W: w1 w)} -> (B: B h1 w1) (H: h) (W: w) ...", h1=2, w1=2) + assert r.axes == (Axis("B", B.size * 2 * 2), sH, sW, D, C) + + r = einops_rearrange(z, "{B (H: h1 H) (W: w1 W)} -> (B: B h1 w1) H W ...", h1=2, w1=2) + assert r.axes == (Axis("B", B.size * 2 * 2), sH, sW, D, C) + # sequence of flattened patches: + # * `{b (h: h1 h) (w: w1 w) c} -> (b: b h1 w1) (c: c h w) ...` + r = einops_rearrange(z, "{B (H: h1 h) (W: w1 w) C} -> (B: B h1 w1) ... (C: C h w) ", h1=2, w1=2) + assert r.axes == (Axis("B", B.size * 2 * 2), D, Axis("C", C.size * sH.size * sW.size)) + # unet attention reordering: + # postional: (qkv heads c) h w -> qkv heads c (h w) + # named: { (embed: qkv heads c) h w } -> qkv heads c (pos: h w) + Embed = Axis("embed", 3 * 4 * C.size) + attn = hax.random.randint(PRNGKey(0), (Embed, H, W), 0, 255) + r = einops_rearrange(attn, "{(embed: qkv heads C) H W} -> qkv heads C (pos: H W)", qkv=3, heads=4) + assert r.axes == (Axis("qkv", 3), Axis("heads", 4), C, (Axis("pos", H.size * W.size))) + # space to depth + # * {b (h: h1 h) (w: w1 w) c} -> ... b h w (c: c h1 w1) + r = einops_rearrange(z, "{B (H: h1 h) (W: w1 w) C} -> ... B (H: h) (W: w) (C: C h1 w1)", h1=2, w1=2) + assert r.axes == (D, B, sH, sW, Axis("C", C.size * 2 * 2)) + + r = einops_rearrange(z, "{B (H: h1 H) (W: w1 W) C} -> B ... H W (C: C h1 w1)", h1=2, w1=2) + assert r.axes == (B, D, sH, sW, Axis("C", C.size * 2 * 2)) + + # image patches specifying H and W + q = hax.rearrange(z, "{ B (H: h1 H) (W: w1 W)} -> (B: B h1 w1) H W ...", H=2, W=2) + assert q.axes == (Axis("B", B.size * sH.size * sW.size), H.resize(2), W.resize(2), D, C) + + q = hax.rearrange(z, "{ B (H: h1 H) (W: w1 W) D} -> (B: B h1 w1) (E: H W D)...", H=2, W=2) + assert q.axes == (Axis("B", B.size * sH.size * sW.size), Axis("E", 2 * 2 * D.size), C) commit d60049b97166942b006b03c5af0dede57dedc079 Date: 2023-10-16T10:00:28-07:00 fix badges diff --git a/README.md b/README.md index d7aacc3..e35d149 100644 --- a/README.md +++ b/README.md @@ -7,7 +7,9 @@ <a href="https://haliax.readthedocs.io/en/latest/?badge=latest"> <img alt="Documentation Status" src="https://readthedocs.org/projects/haliax/badge/?version=latest"> </a> +<a href=""> <img alt="License" src="https://img.shields.io/github/license/stanford-crfm/haliax?color=blue" /> +</a> <a href="https://https://pypi.org/project/haliax/"> <img alt="PyPI" src="https://img.shields.io/pypi/v/haliax?color=blue" /> </a> commit dae8f5f1e7e8708f7c93c0d59d4093e10b74e88c Date: 2023-10-16T10:01:16-07:00 Add `dslice` for dynamic slices, patterned off pallas (#45) * add dslice, inspired by pallas to indexing * add docs for dslice * add docs for dslice diff --git a/docs/api.md b/docs/api.md index e18708f..8937c1a 100644 --- a/docs/api.md +++ b/docs/api.md @@ -77,6 +77,12 @@ See also the section on [Indexing and Slicing](indexing.md). ::: haliax.take ::: haliax.updated_slice +#### Dynamic Slicing + +::: haliax.dslice +::: haliax.dblock +::: haliax.ds + ### Shape Manipulation ::: haliax.flatten diff --git a/docs/cheatsheet.md b/docs/cheatsheet.md index 3c4c68c..2523f5e 100644 --- a/docs/cheatsheet.md +++ b/docs/cheatsheet.md @@ -16,6 +16,9 @@ import haliax as hax Batch = hax.Axis("batch", 32) Embed = hax.Axis("embed", 64) +H = hax.Axis("h", 16) +W = hax.Axis("w", 16) + Step = hax.axis("step", 2) Mini = hax.axis("mini", 16) @@ -26,6 +29,7 @@ y = jnp.zeros((32, 64)) z = jnp.zeros((32,)) w = jnp.zeros((64,)) ind = jnp.arange((8,), dtype=jnp.int32) +im = jnp.zeros((32, 16, 16)) # for haliax x = hax.zeros((Batch, Embed)) @@ -33,6 +37,7 @@ y = hax.zeros((Batch, Embed)) z = hax.zeros((Batch,)) w = hax.zeros((Embed,)) ind = hax.arange(Axis("Index", 8), dtype=jnp.int32) +im = hax.zeros((Batch, H, W)) ``` @@ -63,47 +68,60 @@ ind = hax.arange(Axis("Index", 8), dtype=jnp.int32) | JAX | Haliax | |--------------------------------------------------|-------------------------------------------------------------------------| -| [`jnp.ravel(x)`][jax.numpy.ravel] | [`hax.ravel(x, "Embed")`][haliax.flatten] | -| [`jnp.ravel(x)`][jax.numpy.ravel] | [`hax.flatten(x, "Embed")`][haliax.flatten] | | [`jnp.reshape(x, (2, 16, 64))`][jax.numpy.reshape] | [`hax.unflatten_axis(x, "batch", (Step, Mini)`][haliax.unflatten_axis] | | [`jnp.reshape(x, (-1,))`][jax.numpy.reshape] | [`hax.flatten_axes(x, ("batch", "embed"), "foo")`][haliax.flatten_axes] | | [`jnp.transpose(x, (1, 0))`][jax.numpy.transpose] | [`hax.rearrange(x, ("embed", "batch"))`][haliax.rearrange] | +### Shape Manipulation + +| JAX | Haliax | +|-----------------------------------------------|-------------------------------------------------------------------------------------| +| [`x.transpose((1, 0))`][jax.numpy.transpose] | [`x.rearrange("embed", "batch")`][haliax.rearrange] | +| [`x.reshape((2, 16, 64))`][jax.numpy.reshape] | [`x.unflatten_axis("batch", (Axis("a", 2), Axis("b", 16)))`][haliax.unflatten_axis] | +| [`x.reshape((-1,))`][jax.numpy.reshape] | [`x.flatten_axes(("batch", "embed"), "foo")`][haliax.flatten_axes] | +| [`jnp.ravel(x)`][jax.numpy.ravel] | [`hax.ravel(x, "Embed")`][haliax.flatten] | +| [`jnp.ravel(x)`][jax.numpy.ravel] | [`hax.flatten(x, "Embed")`][haliax.flatten] | + +### Einops-style Rearrange + +See also the section on [Rearrange](rearrange.md). + +| JAX (with einops) | Haliax | +|-------------------------------------------------------------------------|--------------------------------------------------------------------------| +| [`einops.rearrange(x, "batch embed -> embed batch")`](https://einops.rocks/api/rearrange/) | [`hax.rearrange(x, ("embed", "batch"))`][haliax.rearrange] | +| [`einops.rearrange(x, "batch embed -> embed batch")`](https://einops.rocks/api/rearrange/) | [`hax.rearrange(x, "b e -> e b")`][haliax.rearrange] | +| [`einops.rearrange(im, "... h w -> ... (h w)")`](https://einops.rocks/api/rearrange/) | [`hax.flatten_axes(im, ("h", "w"), "hw")`][haliax.flatten_axes] | +| [`einops.rearrange(im, "... h w -> ... (h w)")`](https://einops.rocks/api/rearrange/) | [`hax.rearrange(im, "{h w} -> ... (embed: h w)")`][haliax.rearrange] | +| [`einops.rearrange(x, "b (h w) -> b h w", h=8)`](https://einops.rocks/api/rearrange/) | [`hax.rearrange(x, "b (h w) -> b h w", h=8)`][haliax.rearrange] | +| [`einops.rearrange(x, "b (h w) -> b h w", h=8)`](https://einops.rocks/api/rearrange/) | [`hax.rearrange(x, "{(embed: h w)} -> ... h w", h=8)`][haliax.rearrange] | ### Broadcasting See also the section on [Broadcasting](broadcasting.md). -| JAX | Haliax | -|--------------------------------------------------------------------------|-------------------------------------------------------| +| JAX | Haliax | +|--------------------------------------------------------------------------|---------------------------------------------------------| | [`jnp.broadcast_to(z.reshape(-1, 1), (32, 64))`][jax.numpy.broadcast_to] | [`hax.broadcast_axis(z, Embed)`][haliax.broadcast_axis] | -| Outer product: `z.reshape(-1, 1) * w.reshape(1, -1)` | `z * w.broadcast_axis(Batch)` | +| Outer product: `z.reshape(-1, 1) * w.reshape(1, -1)` | `z * w.broadcast_axis(Batch)` | ### Indexing and Slicing See also the section on [Indexing and Slicing](indexing.md). -| JAX | Haliax | -|-------------------------------------------------------------------|-------------------------------------------------------------| -| `x[0]` | [`x["batch", 0]`][haliax.index] | -| `x[:, 0]` | [`x["embed", 0]`][haliax.index] | -| `x[0, 1]` | [`x["batch", 0, "embed", 1]`][haliax.index] | -| `x[0:10]` | [`x["batch", 0:10]`][haliax.index] | -| `x[0:10:2]` | [`x["batch", 0:10:2]`][haliax.index] | -| `x[0, 1:10:2]` | [`x["batch", 0, "embed", 1:10:2]`][haliax.index] | -| `x[0, [1, 2, 3]]` | [`x["batch", 0, "embed", [1, 2, 3]]`][haliax.index] | -| `x[0, ind]` | [`x["batch", 0, "embed", ind]`][haliax.index] | -| `jnp.take_along_axis(x, ind, axis=1)`][jax.numpy.take_along_axis] | [`hax.take(x, "embed", ind)`][haliax.take] | -| `jax.lax.dynamic_slice(x, [4], [10])`][jax.lax.dynamic_slice] | [`hax.slice(x, "batch", start=4, length=10)`][haliax.slice] | - -### Shape Manipulation - -| JAX | Haliax | -|-----------------------------------------------|-------------------------------------------------------------------------------------| -| [`x.transpose((1, 0))`][jax.numpy.transpose] | [`x.rearrange("embed", "batch")`][haliax.rearrange] | -| [`x.reshape((2, 16, 64))`][jax.numpy.reshape] | [`x.unflatten_axis("batch", (Axis("a", 2), Axis("b", 16)))`][haliax.unflatten_axis] | -| [`x.reshape((-1,))`][jax.numpy.reshape] | [`x.flatten_axes(("batch", "embed"), "foo")`][haliax.flatten_axes] | +| JAX | Haliax | +|--------------------------------------------------------------------------|-------------------------------------------------------------| +| `x[0]` | [`x["batch", 0]`][haliax.index] | +| `x[:, 0]` | [`x["embed", 0]`][haliax.index] | +| `x[0, 1]` | [`x["batch", 0, "embed", 1]`][haliax.index] | +| `x[0:10]` | [`x["batch", 0:10]`][haliax.index] | +| `x[0:10:2]` | [`x["batch", 0:10:2]`][haliax.index] | +| `x[0, 1:10:2]` | [`x["batch", 0, "embed", 1:10:2]`][haliax.index] | +| `x[0, [1, 2, 3]]` | [`x["batch", 0, "embed", [1, 2, 3]]`][haliax.index] | +| `x[0, ind]` | [`x["batch", 0, "embed", ind]`][haliax.index] | +| `jnp.take_along_axis(x, ind, axis=1)`][jax.numpy.take_along_axis] | [`hax.take(x, "embed", ind)`][haliax.take] | +| [`jax.lax.dynamic_slice_in_dim(x, 4, 10)`][jax.lax.dynamic_slice_in_dim] | [`hax.slice(x, "batch", start=4, length=10)`][haliax.slice] | +| [`jax.lax.dynamic_slice_in_dim(x, 4, 10)`][jax.lax.dynamic_slice_in_dim] | [`x["batch", hax.ds(4, 10)]`][haliax.dslice] | ## Operations diff --git a/docs/indexing.md b/docs/indexing.md index a32d620..47fbe4a 100644 --- a/docs/indexing.md +++ b/docs/indexing.md @@ -37,7 +37,6 @@ Otherwise, the idea is pretty straightforward: any unspecified axes are treated slices are kept in reduced dimensions, and integers eliminate dimensions. If all dimensions are eliminated, a scalar JAX ndarray is returned. -## Dynamic Slices ### Shapes in JAX @@ -54,7 +53,9 @@ import jax @jax.jit def f(x, slice_size: int): num_blocks = x.shape[0] // slice_size - jax.lax.fori_loop(0, num_blocks, lambda i, x: x[i * slice_size : (i + 1) * slice_size], x) + def body(i, m): + return i + jnp.mean(x[i * slice_size : (i + 1) * slice_size]) + jax.lax.fori_loop(0, num_blocks, lambda i, m: m + body(i, m), 0.0) f(jnp.arange(10), 2) @@ -66,16 +67,65 @@ f(jnp.arange(10), 2) ``` This is a not-uncommon pattern in situations where you want to process a large array in chunks. In Haliax, we provide -two solutions: [haliax.slice][] +two solutions: [haliax.slice][] as well as dynamic slices ([haliax.dslice][] a.k.a. [haliax.ds][]). + +## Dynamic Slices + +In light of the requirement that all array sizes be known at compile time, Haliax provides both a simple [haliax.slice][] +function, as well as [haliax.dynamic_slice][], which can be used with `[]`. The simple slice function is just a wrapper +around [jax.lax.dynamic_slice][]] and not worth discussing here. + +`dslice` is a trick borrowed from the new experimental [jax.experimental.pallas][] module. It's essentially a slice, +except that instead of a start and an end (and maybe a stride), it takes a start and a size. The size must be +statically known, but the start can be dynamic. This allows us to write the above example as follows: + +```python +import jax +import haliax as hax + +N = hax.Axis("N", 10) +q = hax.arange(N) + +@hax.named_jit +def f(x, slice_size: int): + num_blocks = N.size // slice_size + def body(i, m): + return i + hax.mean(x["N", hax.dslice(i * slice_size, slice_size)]).scalar() + jax.lax.fori_loop(0, num_blocks, body, 0.0) + +f(q, 2) +``` + +For convenience/brevity, `dslice` is aliased as `ds`. In addition, we also expose `dblock`, which is a convenience +function for computing the start and size of a slice given a block index and the size of the slice. Thus, the above +example can be written as follows: + +```python +import jax +import haliax as hax + +N = hax.Axis("N", 10) +q = hax.arange(N) + +@hax.named_jit +def f(x, slice_size: int): + num_blocks = N.size // slice_size + def body(i, m): + return i + hax.mean(x["N", hax.ds.block(i, slice_size)]).scalar() + jax.lax.fori_loop(0, num_blocks, body, 0.0) + +f(q, 2) +``` +It's not a huge improvement, but it's a bit more convenient. ## Advanced Indexing -NumPy's [Advanced Indexing](https://numpy.org/doc/stable/user/basics.indexing.html#advanced-indexing) is supported, -though we use named arrays for the indices instead of normal arrays. In NumPy, the indexed arrays much be -broadcastable to the same shape. Advanced indexing in Haliax is similar, except that they follow Haliax's broadcasting rules, -meaning that the axis names determine broadcasting. Axes with the same name must have the same size. +NumPy's [Advanced Indexing](https://numpy.org/doc/stable/user/basics.indexing.html#advanced-indexing) is supported, though we use named arrays for the indices instead of normal arrays. +In NumPy, the indexed arrays much be broadcastable to the same shape.Advanced indexing in Haliax is similar, except that +they follow Haliax's broadcasting rules, meaning that the axis names determine broadcasting.Axes with the same name must +have the same size. ```python import haliax as hax diff --git a/mkdocs.yml b/mkdocs.yml index a3608ea..c0ee415 100644 --- a/mkdocs.yml +++ b/mkdocs.yml @@ -42,6 +42,7 @@ plugins: - https://docs.python.org/3/objects.inv - https://jax.readthedocs.io/en/latest/objects.inv - https://docs.kidger.site/equinox/objects.inv + - https://einops.rocks/objects.inv options: docstring_options: ignore_init_summary: true diff --git a/src/haliax/__init__.py b/src/haliax/__init__.py index ab738b4..2ea5b08 100644 --- a/src/haliax/__init__.py +++ b/src/haliax/__init__.py @@ -11,7 +11,19 @@ import haliax.random as random import haliax.tree_util as tree_util from ._src.rearrange import rearrange -from .axis import Axis, AxisSelection, AxisSelector, AxisSpec, axis_name, concat_axes, eliminate_axes, selects_axis +from .axis import ( + Axis, + AxisSelection, + AxisSelector, + AxisSpec, + axis_name, + concat_axes, + dblock, + ds, + dslice, + eliminate_axes, + selects_axis, +) from .core import ( NamedArray, NamedOrNumeric, @@ -830,11 +842,14 @@ __all__ = [ "flatten_axes", "slice", "updated_slice", + "ds", + "dslice", + "dblock", "index", "take", "unbind", "rename", - "einops_rearrange", + "rearrange", "zeros", "ones", "full", diff --git a/src/haliax/_src/util.py b/src/haliax/_src/util.py index 79a10ad..ac5824a 100644 --- a/src/haliax/_src/util.py +++ b/src/haliax/_src/util.py @@ -1,9 +1,9 @@ -from typing import Callable, MutableMapping, Sequence, Type, TypeVar +from typing import Callable, MutableMapping, Sequence, TypeAlias, TypeVar T = TypeVar("T") py_slice = slice -slice_t = Type[slice] +slice_t: TypeAlias = slice def index_where(pred: Callable[[T], bool], xs: Sequence[T]) -> int: diff --git a/src/haliax/axis.py b/src/haliax/axis.py index 1d3d00b..21c6966 100644 --- a/src/haliax/axis.py +++ b/src/haliax/axis.py @@ -2,6 +2,8 @@ import typing from dataclasses import dataclass from typing import Dict, List, Mapping, Optional, Sequence, Tuple, Union, overload +import equinox as eqx + from haliax.util import ensure_tuple from ._src.util import index_where @@ -284,3 +286,75 @@ def axis_name(ax: AxisSelector) -> str: return ax.name else: return ax + + +class dslice(eqx.Module): + """ + Dynamic slice, comprising a (start, length) pair. Also aliased as ds. + + Normal numpy-isms like a[i:i+16] don't work in Jax inside jit, because slice doesn't like tracers and JAX + can't see that the slice is constant. This is a workaround that lets you do a[dslice(i, 16)] or even a[ds(i, 16)] + instead. + + This class's name is taken from [jax.experimental.pallas.dslice][]. + """ + + start: int + size: int + + def to_slice(self) -> slice: + return slice(self.start, self.start + self.size) + + def __init__(self, start: int, length: Union[int, Axis]): + """ + As a convenience, if length is an Axis, it will be converted to `length.size` + Args: + start: + length: + """ + self.start = start + if isinstance(length, Axis): + self.size = length.size + else: + self.size = length + + +ds: typing.TypeAlias = dslice + + +def dblock(idx: int, size: int) -> dslice: + """ + Returns a dslice that selects a single block of size `size` starting at `idx` + """ + return dslice(idx * size, size) + + +def is_pallas_dslice(x: object) -> bool: + try: + from jax.experimental.pallas import dslice as pdslice + except ImportError: + return False + + _PALLAS_DSLICE_TYPE = type(pdslice(0, 1)) + return isinstance(x, _PALLAS_DSLICE_TYPE) + + +__all__ = [ + "Axis", + "AxisSelector", + "AxisSelection", + "AxisSpec", + "axis_name", + "concat_axes", + "union_axes", + "ds", + "dslice", + "eliminate_axes", + "is_axis_compatible", + "overlapping_axes", + "replace_axis", + "selects_axis", + "union_axes", + "without_axes", + "is_pallas_dslice", +] diff --git a/src/haliax/core.py b/src/haliax/core.py index e187dc1..8bd5969 100644 --- a/src/haliax/core.py +++ b/src/haliax/core.py @@ -17,11 +17,23 @@ from haliax.jax_utils import is_jax_array_like from haliax.util import ensure_tuple from ._src.util import index_where, py_slice, slice_t -from .axis import Axis, AxisSelection, AxisSelector, AxisSpec, axis_name, eliminate_axes, selects_axis, union_axes +from .axis import ( + Axis, + AxisSelection, + AxisSelector, + AxisSpec, + axis_name, + dslice, + eliminate_axes, + is_pallas_dslice, + selects_axis, + union_axes, +) from .types import IntScalar, PrecisionLike, Scalar NamedOrNumeric = Union[Scalar, "NamedArray"] +NamedIndex = Union[int, slice_t, "NamedArray", dslice] _ENABLE_SHAPE_CHECKS = True @@ -265,17 +277,15 @@ class NamedArray: return haliax.take(self, axis=axis, index=index) @overload - def __getitem__(self, item: Tuple[str, Union[int, slice_t, "NamedArray"]]) -> Union["NamedArray", Scalar]: + def __getitem__(self, item: Tuple[str, NamedIndex]) -> Union["NamedArray", Scalar]: ... # pragma: no cover @overload - def __getitem__( - self, item: Tuple[str, Union[int, slice_t, "NamedArray"], str, Union[int, slice_t, "NamedArray"]] - ) -> Union["NamedArray", jnp.ndarray]: + def __getitem__(self, item: Tuple[str, NamedIndex, str, NamedIndex]) -> Union["NamedArray", jnp.ndarray]: ... @overload - def __getitem__(self, item: Mapping[str, Union[int, slice_t, "NamedArray"]]) -> Union["NamedArray", jnp.ndarray]: + def __getitem__(self, item: Mapping[str, NamedIndex]) -> Union["NamedArray", jnp.ndarray]: ... def __getitem__(self, idx) -> Union["NamedArray", jnp.ndarray]: @@ -834,9 +844,7 @@ def updated_slice( return NamedArray(updated, array.axes) -def index( - array: NamedArray, slices: Mapping[AxisSelector, Union[int, slice_t, NamedArray]] -) -> Union[NamedArray, Scalar]: +def index(array: NamedArray, slices: Mapping[AxisSelector, NamedIndex]) -> Union[NamedArray, Scalar]: """ Selects elements from an array along an axis via index or another named array. @@ -850,6 +858,7 @@ def index( """ # indices where we have array args array_slice_indices = [] + dslice_indices = [] ordered_slices: list = [py_slice(None, None, None)] * len(array.axes) # type: ignore kept_axes = [True] * len(array.axes) for axis, slice_ in slices.items(): @@ -857,10 +866,15 @@ def index( if axis_index is None: raise ValueError(f"axis {axis} not found in {array}") ordered_slices[axis_index] = slice_ - kept_axes[axis_index] = isinstance(slice_, py_slice) + + kept_axes[axis_index] = isinstance(slice_, py_slice) or isinstance(slice_, dslice) or is_pallas_dslice(slice_) + if isinstance(slice_, NamedArray): array_slice_indices.append(axis_index) + if isinstance(slice_, dslice) or is_pallas_dslice(slice_): + dslice_indices.append(axis_index) + # advanced indexing if len(array_slice_indices) > 0: # this requires broadcasting @@ -912,7 +926,20 @@ def index( else: new_axes = tuple(axis.name for axis, keep in zip(array.axes, kept_axes) if keep) - sliced = array.array[tuple(ordered_slices)] + sliced = array.array + + if len(dslice_indices) > 0: + # dynamic slice out the dslices + indices = [0] * len(array.axes) + lengths = [ax.size for ax in array.axes] + for i in dslice_indices: + indices[i] = ordered_slices[i].start + lengths[i] = ordered_slices[i].size + sliced = jax.lax.dynamic_slice(sliced, indices, lengths) + for i in dslice_indices: + ordered_slices[i] = py_slice(None, None, None) + + sliced = sliced[tuple(ordered_slices)] if len(new_axes) == 0: # this is a scalar diff --git a/tests/core_test.py b/tests/core_test.py index db5c954..eb116d3 100644 --- a/tests/core_test.py +++ b/tests/core_test.py @@ -579,6 +579,21 @@ def test_slice_nd_shorthand_syntax(): assert jnp.all(jnp.equal(named1["H", 0:10, "D", 0:10].array, named1.array[0:10, :, 0:10])) +def test_slice_nd_dslice(): + H = Axis("H", 10) + W = Axis("W", 20) + D = Axis("D", 30) + + named1 = hax.random.uniform(PRNGKey(0), (H, W, D)) + from haliax import ds + + assert jnp.all(jnp.equal(named1["H", ds(0, 5), "D", ds(3, 7)].array, named1.array[0:5, :, 3:10])) + # test mixed normal and dslice + assert jnp.all(jnp.equal(named1["H", ds(1, 5), "D", 3:7].array, named1.array[1:6, :, 3:7])) + assert jnp.all(jnp.equal(named1["H", ds(2, 5), "D", 3].array, named1.array[2:7, :, 3])) + assert jnp.all(jnp.equal(named1["H", ds(3, 5), "D", 3:10:2].array, named1.array[3:8, :, 3:10:2])) + + def test_slice_nd_array_present_dims(): # tests slicing with arrays that are already present in the named array, which is sometimes ok H = Axis("H", 10) commit 2888ffd7efdd7f9e39f8b33446bc2098ff925b61 Date: 2023-10-16T14:21:17-07:00 expose `block` method since i like that better diff --git a/src/haliax/axis.py b/src/haliax/axis.py index 21c6966..cc52445 100644 --- a/src/haliax/axis.py +++ b/src/haliax/axis.py @@ -318,6 +318,13 @@ class dslice(eqx.Module): else: self.size = length + @staticmethod + def block(idx: int, size: int) -> "dslice": + """ + Returns a dslice that selects a single block of size `size` starting at `idx` + """ + return dslice(idx * size, size) + ds: typing.TypeAlias = dslice commit 037450d3bbdd2275ed0ba77c8010203256da5099 Date: 2023-10-16T14:23:46-07:00 refactor docs for nn a bit diff --git a/docs/nn.md b/docs/nn.md index f3a5031..e48b117 100644 --- a/docs/nn.md +++ b/docs/nn.md @@ -1,39 +1,5 @@ # Neural Networks -## Functions - -These functions wrap the equivalent in [jax.nn][]: - -::: haliax.nn.relu -::: haliax.nn.relu6 -::: haliax.nn.sigmoid -::: haliax.nn.softplus -::: haliax.nn.soft_sign -::: haliax.nn.silu -::: haliax.nn.swish -::: haliax.nn.log_sigmoid -::: haliax.nn.leaky_relu -::: haliax.nn.hard_sigmoid -::: haliax.nn.hard_silu -::: haliax.nn.hard_swish -::: haliax.nn.hard_tanh -::: haliax.nn.elu -::: haliax.nn.celu -::: haliax.nn.selu -::: haliax.nn.gelu -::: haliax.nn.quick_gelu -::: haliax.nn.glu -::: haliax.nn.logsumexp -::: haliax.nn.log_softmax -::: haliax.nn.softmax -::: haliax.nn.standardize -::: haliax.nn.one_hot - -### Loss Functions - -::: haliax.nn.cross_entropy_loss -::: haliax.nn.cross_entropy_loss_and_log_normalizers - ## Modules @@ -42,13 +8,22 @@ they naturally all use [haliax.NamedArray][]. (We welcome PRs for more modules! The most interesting of these modules is [haliax.nn.Stacked][], which allows you to create homogenous "stacks" of the same module (e.g. transformer blocks), which is a common pattern in deep learning. +### Linear + ::: haliax.nn.Embedding ::: haliax.nn.Linear + +### Dropout ::: haliax.nn.Dropout + +### Normalization ::: haliax.nn.LayerNorm + +### Meta + ::: haliax.nn.Stacked -### Convolutional Layers +### Convolution Unlike other frameworks, Haliax doesn't distinguish between 1D, 2D, and 3D, and general convolutions. Instead, we have a single [haliax.nn.Conv][] module that can be used for all of these, depending on the number of axes @@ -76,7 +51,36 @@ We don't provide an explicit attention module, but we do provide an attention fu ::: haliax.nn.attention.mask_to_bias ::: haliax.nn.attention.alibi_attention_bias +## Functions -## API Reference +These functions wrap the equivalent in [jax.nn][]: -::: haliax.nn +::: haliax.nn.relu +::: haliax.nn.relu6 +::: haliax.nn.sigmoid +::: haliax.nn.softplus +::: haliax.nn.soft_sign +::: haliax.nn.silu +::: haliax.nn.swish +::: haliax.nn.log_sigmoid +::: haliax.nn.leaky_relu +::: haliax.nn.hard_sigmoid +::: haliax.nn.hard_silu +::: haliax.nn.hard_swish +::: haliax.nn.hard_tanh +::: haliax.nn.elu +::: haliax.nn.celu +::: haliax.nn.selu +::: haliax.nn.gelu +::: haliax.nn.quick_gelu +::: haliax.nn.glu +::: haliax.nn.logsumexp +::: haliax.nn.log_softmax +::: haliax.nn.softmax +::: haliax.nn.standardize +::: haliax.nn.one_hot + +### Loss Functions + +::: haliax.nn.cross_entropy_loss +::: haliax.nn.cross_entropy_loss_and_log_normalizers diff --git a/src/haliax/nn/scan.py b/src/haliax/nn/scan.py index 7d5f7bb..e183cfe 100644 --- a/src/haliax/nn/scan.py +++ b/src/haliax/nn/scan.py @@ -39,6 +39,7 @@ class Stacked(eqx.Module, Generic[M]): Stacked also supports gradient checkpointing, which is useful for very large models that don't fit in memory. Example: + ```python >>> import equinox as eqx >>> import haliax as hax >>> import haliax.nn as hnn @@ -54,6 +55,7 @@ class Stacked(eqx.Module, Generic[M]): >>> Hidden = hax.Axis("hidden", 10) >>> mod = MyModule(5, Hidden) >>> mod(hax.ones(Hidden)) + ``` """ # TODO: we can probably make this module support pipeline parallelism, but that's a whole project in itself commit 45fc8e4d2208148f361064810096a9b230c9b0c8 Date: 2023-10-16T14:24:16-07:00 make mask combination broadcast axes by default diff --git a/src/haliax/nn/attention.py b/src/haliax/nn/attention.py index 45f08b8..9ad0c47 100644 --- a/src/haliax/nn/attention.py +++ b/src/haliax/nn/attention.py @@ -122,7 +122,7 @@ def combine_masks_and(mask1: Optional[NamedArray], mask2: Optional[NamedArray]) return mask2 if mask2 is None: return mask1 - return mask1 & mask2 + return mask1 & mask2.broadcast_axis(mask1.axes) def combine_masks_or(mask1: Optional[NamedArray], mask2: Optional[NamedArray]) -> Optional[NamedArray]: @@ -130,7 +130,7 @@ def combine_masks_or(mask1: Optional[NamedArray], mask2: Optional[NamedArray]) - return mask2 if mask2 is None: return mask1 - return mask1 | mask2 + return mask1 | mask2.broadcast_axis(mask1.axes) def causal_mask(QPos: Axis, KPos: Axis, q_start: int = 0, k_start: int = 0) -> NamedArray: commit 20fcadcfc74cd49229a72c43bed3ec17dd23107d Date: 2023-10-16T14:25:16-07:00 expose AxisSelector as an option for getitem on NamedArray diff --git a/src/haliax/core.py b/src/haliax/core.py index 8bd5969..37eb5d5 100644 --- a/src/haliax/core.py +++ b/src/haliax/core.py @@ -277,15 +277,17 @@ class NamedArray: return haliax.take(self, axis=axis, index=index) @overload - def __getitem__(self, item: Tuple[str, NamedIndex]) -> Union["NamedArray", Scalar]: + def __getitem__(self, item: Tuple[AxisSelector, NamedIndex]) -> Union["NamedArray", Scalar]: ... # pragma: no cover @overload - def __getitem__(self, item: Tuple[str, NamedIndex, str, NamedIndex]) -> Union["NamedArray", jnp.ndarray]: + def __getitem__( + self, item: Tuple[AxisSelector, NamedIndex, AxisSelector, NamedIndex] + ) -> Union["NamedArray", jnp.ndarray]: ... @overload - def __getitem__(self, item: Mapping[str, NamedIndex]) -> Union["NamedArray", jnp.ndarray]: + def __getitem__(self, item: Mapping[AxisSelector, NamedIndex]) -> Union["NamedArray", jnp.ndarray]: ... def __getitem__(self, idx) -> Union["NamedArray", jnp.ndarray]: commit 81425fcb21e8abbc01cdf9a644cf7cd392366d2f Date: 2023-10-16T15:30:00-07:00 add typing.overload annotations to named_call diff --git a/src/haliax/jax_utils.py b/src/haliax/jax_utils.py index cb6fdee..e065839 100644 --- a/src/haliax/jax_utils.py +++ b/src/haliax/jax_utils.py @@ -1,4 +1,5 @@ import functools as ft +import typing from typing import Any, Callable, List, Optional, Sequence, Union import equinox as eqx @@ -9,6 +10,9 @@ from jax import random as jrandom from jaxtyping import PRNGKeyArray +F = typing.TypeVar("F", bound=Callable[..., Any]) + + class Static(eqx.Module): value: Any = eqx.field(static=True) @@ -97,6 +101,16 @@ def _UNSPECIFIED(): raise ValueError("unspecified") +@typing.overload +def named_call(f: F, name: Optional[str] = None) -> F: + ... + + +@typing.overload +def named_call(*, name: Optional[str] = None) -> Callable[[F], F]: + ... + + def named_call(f=_UNSPECIFIED, name: Optional[str] = None): if f is _UNSPECIFIED: return lambda f: named_call(f, name) # type: ignore commit 44570b2c7ea6a4ac0b8168991da287809e97e4e5 Date: 2023-10-16T15:30:23-07:00 minor flexification of attention signature diff --git a/src/haliax/nn/attention.py b/src/haliax/nn/attention.py index 9ad0c47..5739d1b 100644 --- a/src/haliax/nn/attention.py +++ b/src/haliax/nn/attention.py @@ -8,7 +8,7 @@ from jaxtyping import PRNGKeyArray import haliax import haliax.random as hrandom -from haliax.axis import Axis, AxisSelection, AxisSpec +from haliax.axis import Axis, AxisSelection, AxisSelector, AxisSpec from haliax.core import NamedArray from haliax.types import PrecisionLike @@ -24,7 +24,7 @@ from haliax.types import PrecisionLike def dot_product_attention_weights( - Head: Axis, + Head: AxisSelector, KPos: AxisSelection, query: NamedArray, key: NamedArray, commit a46e99afb9569082aa10094fb174f05aab55b522 Date: 2023-10-16T16:57:03-07:00 swap order of transposed binary op axes diff --git a/src/haliax/core.py b/src/haliax/core.py index 37eb5d5..ce13085 100644 --- a/src/haliax/core.py +++ b/src/haliax/core.py @@ -1217,10 +1217,10 @@ def _broadcast_axes( if require_subset: # check if one is a subset of the other - if set(a_axes).issubset(set(b_axes)): - return b_axes - elif set(b_axes).issubset(set(a_axes)): + if set(b_axes).issubset(set(a_axes)): return a_axes + elif set(a_axes).issubset(set(b_axes)): + return b_axes else: return None diff --git a/tests/core_test.py b/tests/core_test.py index eb116d3..33e4013 100644 --- a/tests/core_test.py +++ b/tests/core_test.py @@ -760,3 +760,14 @@ def test_updated_slice_extra_update_axis_errors(): with pytest.raises(ValueError): named3 = hax.random.randint(PRNGKey(0), (H, W), minval=10, maxval=30) named3.updated_slice({"H": 0, "W": 0}, named2) + + +def test_order_of_transpose_add(): + H = Axis("H", 10) + W = Axis("W", 20) + + named1 = hax.random.randint(PRNGKey(0), (H, W), minval=0, maxval=10) + named2 = hax.random.randint(PRNGKey(0), (W, H), minval=10, maxval=30) + + assert (named1 + named2).axes == (H, W) + assert jnp.all((named1 + named2).array == named1.array + named2.array.T) commit c3fdf639c990194e9ed6e6bbe7e832c891cb1e8c Date: 2023-10-23T16:40:30-07:00 add a nicer tostring for NamedArray and Axis diff --git a/src/haliax/axis.py b/src/haliax/axis.py index cc52445..e50e8d5 100644 --- a/src/haliax/axis.py +++ b/src/haliax/axis.py @@ -22,6 +22,9 @@ class Axis: def resize(self, size) -> "Axis": return Axis(self.name, size) + def __str__(self): + return f"{self.name}({self.size})" + AxisSelector = Union[Axis, str] """AxisSelector is a type that can be used to select a single axis from an array. str or Axis""" diff --git a/src/haliax/core.py b/src/haliax/core.py index ce13085..fd8b9af 100644 --- a/src/haliax/core.py +++ b/src/haliax/core.py @@ -9,6 +9,7 @@ from typing import Any, Dict, List, Mapping, Optional, Sequence, Tuple, Union, o import jax import jax.numpy as jnp +import numpy import numpy as np import haliax @@ -109,7 +110,10 @@ class NamedArray: raise ValueError(f"Expected scalar, got {self.array.ndim}-dimensional array") return self.array - # shape = property(lambda self: self.array.shape) + @ft.cached_property + def shape(self) -> Dict[str, int]: + return {axis.name: axis.size for axis in self.axes} + dtype = property(lambda self: self.array.dtype) """The dtype of the underlying array""" ndim = property(lambda self: self.array.ndim) @@ -182,6 +186,27 @@ class NamedArray: result.append(self.axes[i]) return tuple(result) + def __str__(self): + # we consider the following cases: + # * array is a tracer, in which case we want just the named shape (and an indication that it's a tracer) + # * array is a jnp.ndarray, in which case we want the named shape and the array + + if isinstance(self.array, jax.core.Tracer): + return f"NamedArray(Tracer<{self.dtype}{self.shape}>)" + elif self.ndim <= 1: + return f"NamedArray({self.dtype}{self.shape}, {self.array})" + else: + return f"NamedArray({self.dtype}{self.shape},\n{self.array})" + + def __tree_pp__(self, **kwargs): + # For Equinox's tree pretty printer + import jax._src.pretty_printer as pp + + if kwargs.get("short_arrays", True): + return pp.text(f"Named({self.dtype}{self.shape})") + else: + return str(self) + @overload def _lookup_indices(self, axis: AxisSelector) -> Optional[int]: # type: ignore ... diff --git a/tests/core_test.py b/tests/core_test.py index 33e4013..eac2958 100644 --- a/tests/core_test.py +++ b/tests/core_test.py @@ -1,3 +1,4 @@ +import equinox as eqx import jax import jax.numpy as jnp import pytest @@ -771,3 +772,26 @@ def test_order_of_transpose_add(): assert (named1 + named2).axes == (H, W) assert jnp.all((named1 + named2).array == named1.array + named2.array.T) + + +def test_nice_short_string_in_named_array(): + H = Axis("H", 10) + W = Axis("W", 20) + + named1 = hax.random.randint(PRNGKey(0), (H, W), minval=0, maxval=10) + + assert str(named1).startswith("NamedArray(int32{'H': 10, 'W': 20}") + + +def test_nice_short_string_in_named_array_in_eqx_module(): + H = Axis("H", 10) + W = Axis("W", 20) + + named1 = hax.random.randint(PRNGKey(0), (H, W), minval=0, maxval=10) + + class TestModule(eqx.Module): + named1: NamedArray + + mod = TestModule(named1) + + assert str(mod).startswith("TestModule(named1=Named(int32{'H': 10, 'W': 20}))") commit 2ba3cda0630c13e80b32c2cf2e255794a7f6c549 Date: 2023-10-23T16:41:04-07:00 add a paranoid test that reductions respect where diff --git a/tests/test_ops.py b/tests/test_ops.py index 80a7860..5563d65 100644 --- a/tests/test_ops.py +++ b/tests/test_ops.py @@ -188,3 +188,21 @@ def test_tril_triu(): named5 = hax_fn(named1, Height, Depth) expected5 = jnp_fn(named1.array.transpose([1, 0, 2])) assert jnp.all(jnp.isclose(named5.array, expected5)) + + +def test_mean_respects_where(): + Height = Axis("Height", 10) + Width = Axis("Width", 3) + + named1 = hax.random.uniform(PRNGKey(0), (Height, Width)) + where = hax.random.uniform(PRNGKey(1), (Height, Width)) > 0.5 + + assert not jnp.all(jnp.isclose(hax.mean(named1).array, hax.mean(named1, where=where).array)) + assert jnp.all(jnp.isclose(hax.mean(named1, where=where).array, jnp.mean(named1.array, where=where.array))) + + # check broadcasting + where = hax.random.uniform(PRNGKey(2), (Height,)) > 0.5 + assert not jnp.all(jnp.isclose(hax.mean(named1).array, hax.mean(named1, where=where).array)) + assert jnp.all( + jnp.isclose(hax.mean(named1, where=where).array, jnp.mean(named1.array, where=where.array.reshape((-1, 1)))) + ) commit c097dd69bfd78a1fc1781f517b9ba6509939def3 Date: 2023-10-23T23:17:04-07:00 tweaks diff --git a/README.md b/README.md index e35d149..f0588b7 100644 --- a/README.md +++ b/README.md @@ -93,7 +93,6 @@ can support FSDP and Tensor Parallelism with just a few lines of code. Haliax's our companion library for training large language models and other foundation models, with scale proven up to 20B parameters and up to a TPU v3-256 pod slice. - Haliax was created by [Stanford's Center for Research on Foundation Models (CRFM)](https://crfm.stanford.edu/)'s research engineering team. You can find us in the #levanter channel on the unofficial [Jax LLM Discord](https://discord.gg/FkRGNX3ND). @@ -105,7 +104,7 @@ Haliax's API documentation is available at [haliax.readthedocs.io](https://halia ### Tutorials -Currently, we have four tutorials for Haliax : +These are some tutorials to get you started with Haliax. They are available as Colab notebooks: <!--haliax-tutorials-start--> commit d4ef73cdb6dd09d7464213d51518b132687430dc Date: 2023-10-24T10:08:43-07:00 improve readme diff --git a/README.md b/README.md index f0588b7..9942da9 100644 --- a/README.md +++ b/README.md @@ -18,9 +18,21 @@ > — Patrick Rothfuss, *The Name of the Wind* Haliax is a [JAX](https:://github.com/google/jax) library for building neural networks with named tensors, in the tradition of Alexander Rush's [Tensor Considered Harmful](https://nlp.seas.harvard.edu/NamedTensor). -Named tensors improve the legibility and compositionality of tensor programs by using named axes instead of positional indices -as in NumPy, PyTorch, etc. Here's a minimal attention module implementation in Haliax. For a more detailed introduction, +Named tensors improve the **legibility** and **compositionality** of tensor programs by using named axes instead of positional indices +as typically used in NumPy, PyTorch, etc. + +Despite the focus on legibility, Haliax +is also **fast**, typically about as fast as "pure" JAX code. +Haliax is also built to be **scalable**: it +can support [Fully-Sharded Data Parallelism (FSDP)](https://engineering.fb.com/2021/07/15/open-source/fsdp/) and Tensor Parallelism with [just a few lines of code](https://colab.research.google.com/drive/1QX4yH3zRFF3Xiibf1aahETcSQ5nbcUMz). Haliax powers [Levanter](https://gihub.com/stanford-crfm/levanter), +our companion library for training large language models and other foundation models, with scale proven up to 20B parameters +and up to a TPU v3-256 pod slice. + +## Example: Attention + +Here's a minimal attention module implementation in Haliax. For a more detailed introduction, please see the [Haliax tutorial](https://colab.research.google.com/drive/1TiTcQQ4V5mopbgCu1SVl-oqJtXn7rFnC). +(We use the excellent [Equinox](https://github.com/patrick-kidger/equinox) library for its module system and tree transformations.) ```python import equinox as eqx @@ -60,25 +72,25 @@ causal_mask = hax.arange(Pos).broadcast_axis(KPos) >= hax.arange(KPos) class Attention(eqx.Module): - proj_qkv: hnn.Linear # input projection from [Embed] -> [(q, k, v), Head, Key] + proj_q: hnn.Linear # [Embed] -> [Head, Key] + proj_k: hnn.Linear # [Embed] -> [Head, Key] + proj_v: hnn.Linear # [Embed] -> [Head, Key] proj_answer: hnn.Linear # output projection from [Head, Key] -> [Embed] @staticmethod def init(Embed, Head, Key, *, key): - Qkv = hax.Axis("qkv", 3) # create all three at once - - k_qkv, k_ans = jax.random.split(key, 2) - proj_qkv = hnn.Linear.init(In=Embed, Out=(Qkv, Head, Key), key=k_qkv) + k_q, k_k, k_v, k_ans = jax.random.split(key, 4) + proj_q = hnn.Linear.init(In=Embed, Out=(Head, Key), key=k_q) + proj_k = hnn.Linear.init(In=Embed, Out=(Head, Key), key=k_k) + proj_v = hnn.Linear.init(In=Embed, Out=(Head, Key), key=k_v) proj_answer = hnn.Linear.init(In=(Head, Key), Out=Embed, key=k_ans) - return Attention(proj_qkv, proj_answer) + return Attention(proj_q, proj_k, proj_v, proj_answer) def __call__(self, x, mask=None): - qkv_out = self.proj_qkv(x) - q, k, v = qkv_out.unbind("qkv") - - # Rename k and v's Pos as haliax doesn't support unnamed axes or duplicate axes - k = k.rename({"position": "key_position"}) - v = v.rename({"position": "key_position"}) + q = self.proj_q(x) + # Rename "position" to "key_position" for self attention + k = self.proj_k(x).rename({"position": "key_position"}) + v = self.proj_v(x).rename({"position": "key_position"}) answers = attention(Key, KPos, q, k, v, causal_mask) @@ -86,13 +98,6 @@ class Attention(eqx.Module): return x ``` -(We use the excellent [Equinox](https://github.com/patrick-kidger/equinox) library for its module system and tree transformations.) - -Haliax is built to be fast: the generated code (using JAX/XLA) should be as fast as handwritten JAX code. Haliax is also built to be scalable: it -can support FSDP and Tensor Parallelism with just a few lines of code. Haliax's powers [Levanter](https://gihub.com/stanford-crfm/levanter), -our companion library for training large language models and other foundation models, with scale proven up to 20B parameters -and up to a TPU v3-256 pod slice. - Haliax was created by [Stanford's Center for Research on Foundation Models (CRFM)](https://crfm.stanford.edu/)'s research engineering team. You can find us in the #levanter channel on the unofficial [Jax LLM Discord](https://discord.gg/FkRGNX3ND). @@ -100,8 +105,6 @@ You can find us in the #levanter channel on the unofficial [Jax LLM Discord](htt ## Documentation -Haliax's API documentation is available at [haliax.readthedocs.io](https://haliax.readthedocs.io/en/latest/). - ### Tutorials These are some tutorials to get you started with Haliax. They are available as Colab notebooks: @@ -114,10 +117,15 @@ These are some tutorials to get you started with Haliax. They are available as C * [Mixed Precision with `jmp`](https://colab.research.google.com/drive/1_4cikwt-UhSH7yRzNRK8ze9msM9r2mEl?usp=sharing) (This one is really a tutorial for [jmp](https://github.com/deepmind/jmp) but it's how to use it with Haliax...) <!--haliax-tutorials-end--> +### API Reference + +Haliax's API documentation is available at [haliax.readthedocs.io](https://haliax.readthedocs.io/en/latest/). ## Contributing We welcome contributions! Please see [CONTRIBUTING.md](CONTRIBUTING.md) for more information. +We also have a list of [good first issues](https://github.com/stanford-crfm/haliax/issues?q=is%3Aissue+is%3Aopen+label%3A%22good+first+issue%22) +to help you get started. (If those don't appeal, don't hesitate to reach out to us on Discord!) ## License commit 2b040c5246231b1dc7504120fc0ce2ea3ec9db2f Date: 2023-10-24T10:09:55-07:00 1.2 diff --git a/pyproject.toml b/pyproject.toml index 4ce5634..fd1fd9f 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta" [project] name = "haliax" -version = "1.1" +version = "1.2" authors = [ { name="David Hall", email="dlwh@cs.stanford.edu" }, ] @@ -20,8 +20,8 @@ classifiers = [ "Intended Audience :: Science/Research", ] dependencies = [ - # we'll require that you install jax yourself, since the extras vary by system. - # jax = {version = ">=0.4.10,<0.5.0"} + # we require that you install jax yourself, since the extras vary by system. + # jax = {version = ">=0.4.19,<0.5.0"} "equinox>=0.10.6", "jaxtyping>=0.2.20", "safetensors[numpy]", commit 694df958d707c0c0f1f3e752f96a24be598a4c88 Date: 2023-11-01T16:32:40-07:00 Update README.md (#47) diff --git a/README.md b/README.md index 9942da9..40bcd6a 100644 --- a/README.md +++ b/README.md @@ -24,7 +24,7 @@ as typically used in NumPy, PyTorch, etc. Despite the focus on legibility, Haliax is also **fast**, typically about as fast as "pure" JAX code. Haliax is also built to be **scalable**: it -can support [Fully-Sharded Data Parallelism (FSDP)](https://engineering.fb.com/2021/07/15/open-source/fsdp/) and Tensor Parallelism with [just a few lines of code](https://colab.research.google.com/drive/1QX4yH3zRFF3Xiibf1aahETcSQ5nbcUMz). Haliax powers [Levanter](https://gihub.com/stanford-crfm/levanter), +can support [Fully-Sharded Data Parallelism (FSDP)](https://engineering.fb.com/2021/07/15/open-source/fsdp/) and Tensor Parallelism with [just a few lines of code](https://colab.research.google.com/drive/1QX4yH3zRFF3Xiibf1aahETcSQ5nbcUMz). Haliax powers [Levanter](https://github.com/stanford-crfm/levanter), our companion library for training large language models and other foundation models, with scale proven up to 20B parameters and up to a TPU v3-256 pod slice. commit 08b8852f9fb7023ec91bc47c5bc779568ca40d50 Date: 2023-11-01T16:52:45-07:00 Add a simple MLP module (#48) * add our own MLP class * fix imports * remove old unnused mlp class * actually fix imports, add test * actually fix imports, add test diff --git a/README.md b/README.md index 40bcd6a..070791f 100644 --- a/README.md +++ b/README.md @@ -35,6 +35,8 @@ please see the [Haliax tutorial](https://colab.research.google.com/drive/1TiTcQQ (We use the excellent [Equinox](https://github.com/patrick-kidger/equinox) library for its module system and tree transformations.) ```python +import haliax.nn.normalization +import haliax.nn.activations import equinox as eqx import jax import jax.numpy as jnp @@ -56,7 +58,7 @@ def attention_scores(Key, KPos, query, key, mask): scores -= 1E9 * (1.0 - mask) # convert to probabilities - scores = hax.nn.softmax(scores, KPos) + scores = haliax.nn.normalization.softmax(scores, KPos) return scores @@ -72,9 +74,9 @@ causal_mask = hax.arange(Pos).broadcast_axis(KPos) >= hax.arange(KPos) class Attention(eqx.Module): - proj_q: hnn.Linear # [Embed] -> [Head, Key] - proj_k: hnn.Linear # [Embed] -> [Head, Key] - proj_v: hnn.Linear # [Embed] -> [Head, Key] + proj_q: hnn.Linear # [Embed] -> [Head, Key] + proj_k: hnn.Linear # [Embed] -> [Head, Key] + proj_v: hnn.Linear # [Embed] -> [Head, Key] proj_answer: hnn.Linear # output projection from [Head, Key] -> [Embed] @staticmethod diff --git a/docs/cheatsheet.md b/docs/cheatsheet.md index 2523f5e..622fdf2 100644 --- a/docs/cheatsheet.md +++ b/docs/cheatsheet.md @@ -131,7 +131,7 @@ See also the section on [Indexing and Slicing](indexing.md). Almost all elementwise operations are the same as JAX, except that they work on either [haliax.NamedArray][] or [jax.numpy.ndarray][] objects. -Any elementwise operation in [jax.nn][] should be in [haliax.nn][]. +Any elementwise operation in [jax.nn][] should be in [haliax.nn](nn.md). ### Binary Operations diff --git a/docs/indexing.md b/docs/indexing.md index 47fbe4a..dd31f7d 100644 --- a/docs/indexing.md +++ b/docs/indexing.md @@ -72,7 +72,7 @@ two solutions: [haliax.slice][] as well as dynamic slices ([haliax.dslice][] a.k ## Dynamic Slices In light of the requirement that all array sizes be known at compile time, Haliax provides both a simple [haliax.slice][] -function, as well as [haliax.dynamic_slice][], which can be used with `[]`. The simple slice function is just a wrapper +function, as well as [haliax.dslice][], which can be used with `[]`. The simple slice function is just a wrapper around [jax.lax.dynamic_slice][]] and not worth discussing here. `dslice` is a trick borrowed from the new experimental [jax.experimental.pallas][] module. It's essentially a slice, diff --git a/docs/nn.md b/docs/nn.md index e48b117..e2d530f 100644 --- a/docs/nn.md +++ b/docs/nn.md @@ -22,6 +22,7 @@ of the same module (e.g. transformer blocks), which is a common pattern in deep ### Meta ::: haliax.nn.Stacked +::: haliax.nn.MLP ### Convolution diff --git a/docs/rearrange.ipynb b/docs/rearrange.ipynb new file mode 100644 index 0000000..138247e --- /dev/null +++ b/docs/rearrange.ipynb @@ -0,0 +1,87 @@ +{ + "cells": [ + { + "cell_type": "code", + "execution_count": 1, + "id": "initial_id", + "metadata": { + "collapsed": true, + "ExecuteTime": { + "end_time": "2023-10-24T19:27:47.968939Z", + "start_time": "2023-10-24T19:27:47.349182Z" + } + }, + "outputs": [ + { + "name": "stderr", + "output_type": "stream", + "text": [ + "WARNING: All log messages before absl::InitializeLog() is called are written to STDERR\n", + "I0000 00:00:1698175667.814623 1 tfrt_cpu_pjrt_client.cc:349] TfrtCpuClient created.\n" + ] + } + ], + "source": [ + "import haliax as hax\n", + "from jax.random import PRNGKey\n", + "\n", + "N = hax.Axis(\"N\", 8)\n", + "C = hax.Axis(\"C\", 3)\n", + "H = hax.Axis(\"H\", 64)\n", + "W = hax.Axis(\"W\", 64)\n", + "\n", + "x = hax.random.uniform(PRNGKey(0), (N, C, H, W))\n", + "\n" + ] + }, + { + "cell_type": "code", + "execution_count": 9, + "outputs": [ + { + "data": { + "text/plain": "{'N': 8, 'C': 3, 'P': 64, 'H': 8, 'W': 8}" + }, + "execution_count": 9, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "# split into patches\n", + "hax.rearrange(x, \"N C (ph H) (pw W) -> N C (P: ph pw) H W\", ph=8, pw=8)\n", + "# order agnostic\n", + "hax.rearrange(x, \"{(H: ph H) (W: pw W)} -> ... (P: ph pw) H W\", ph=8, pw=8)" + ], + "metadata": { + "collapsed": false, + "ExecuteTime": { + "end_time": "2023-10-24T19:30:14.757668Z", + "start_time": "2023-10-24T19:30:14.753994Z" + } + }, + "id": "f0178b7a92a41783" + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "language": "python", + "name": "python3" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 2 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython2", + "version": "2.7.6" + } + }, + "nbformat": 4, + "nbformat_minor": 5 +} diff --git a/src/haliax/nn/__init__.py b/src/haliax/nn/__init__.py index 2f25003..df2edcd 100644 --- a/src/haliax/nn/__init__.py +++ b/src/haliax/nn/__init__.py @@ -1,5 +1,4 @@ import functools -import typing import warnings from typing import Optional, Tuple, Union @@ -8,127 +7,45 @@ import jax.numpy as jnp import haliax import haliax as hax +import haliax.nn.activations import haliax.nn.attention as attention +import haliax.nn.normalization -from ..axis import Axis, AxisSelection, AxisSelector, AxisSpec +from ..axis import Axis, AxisSelector from ..core import NamedArray -from ..types import Scalar from ..util import UNSPECIFIED, Unspecified -from ..wrap import ReductionFunction, unwrap_namedarrays, wrap_axiswise_call, wrap_elemwise_unary, wrap_reduction_call +from ..wrap import ReductionFunction +from .activations import ( + celu, + elu, + gelu, + glu, + hard_sigmoid, + hard_silu, + hard_swish, + hard_tanh, + leaky_relu, + log_sigmoid, + quick_gelu, + relu, + relu6, + selu, + sigmoid, + silu, + soft_sign, + softplus, + swish, +) from .conv import Conv, ConvTranspose from .dropout import Dropout, dropout from .embedding import Embedding from .linear import Linear -from .normalization import LayerNorm +from .mlp import MLP +from .normalization import LayerNorm, log_softmax, logsumexp, softmax, standardize from .scan import Stacked -A = typing.TypeVar("A", Scalar, NamedArray, jnp.ndarray) - - -def relu(a: A) -> A: - return wrap_elemwise_unary(jnn.relu, a) - - -def relu6(a: A) -> A: - return wrap_elemwise_unary(jnn.relu6, a) - - -def sigmoid(a: A) -> A: - return wrap_elemwise_unary(jnn.sigmoid, a) - - -def softplus(a: A) -> A: - return wrap_elemwise_unary(jnn.softplus, a) - - -def soft_sign(a: A) -> A: - return wrap_elemwise_unary(jnn.soft_sign, a) - - -def silu(a: A) -> A: - return wrap_elemwise_unary(jnn.silu, a) - - -def swish(a: A) -> A: - return wrap_elemwise_unary(jnn.swish, a) - - -def log_sigmoid(a: A) -> A: - return wrap_elemwise_unary(jnn.log_sigmoid, a) - - -def leaky_relu(a: A) -> A: - return wrap_elemwise_unary(jnn.leaky_relu, a) - - -def hard_sigmoid(a: A) -> A: - return wrap_elemwise_unary(jnn.hard_sigmoid, a) - - -def hard_silu(a: A) -> A: - return wrap_elemwise_unary(jnn.hard_silu, a) - - -def hard_swish(a: A) -> A: - return wrap_elemwise_unary(jnn.hard_swish, a) - - -def hard_tanh(a: A) -> A: - return wrap_elemwise_unary(jnn.hard_tanh, a) - - -def elu(a: A) -> A: - return wrap_elemwise_unary(jnn.elu, a) - - -def celu(a: A) -> A: - return wrap_elemwise_unary(jnn.celu, a) - - -def selu(a: A) -> A: - return wrap_elemwise_unary(jnn.selu, a) - - -def gelu(a: A, approximate: bool = True) -> A: - return wrap_elemwise_unary(jnn.gelu, a, approximate=approximate) - - -def glu(x: NamedArray, axis: Axis) -> NamedArray: - axis_index = x.axes.index(axis) - return jnn.glu(x.array, axis_index) - - -def logsumexp(a: A, axis: Optional[AxisSelection] = None) -> A: - # TODO: logsumexp indirectly supports where via `b`. we should support it directly - return wrap_reduction_call(jnn.logsumexp, a, axis=axis, single_axis_only=False, supports_where=False) - - # TODO: support where in softmax, etc -def softmax(a: A, axis: Optional[AxisSelection] = None) -> A: - return wrap_axiswise_call(jnn.softmax, a, axis=axis, single_axis_only=False) - - -def log_softmax(a: A, axis: Optional[AxisSelection] = None) -> A: - return wrap_axiswise_call(jnn.log_softmax, a, axis=axis, single_axis_only=False) - - -def standardize( - x: NamedArray, - axis: AxisSpec, - *, - mean: Optional[NamedArray] = None, - variance: Optional[NamedArray] = None, - epsilon: float = 1e-5, - where: Optional[NamedArray] = None, -) -> NamedArray: - """Analogous to [jax.nn.standardize][], but with support for NamedArrays.""" - x, mean, variance, where = haliax.broadcast_arrays(x, mean, variance, where) # type: ignore - raw_x, mean, variance, where = unwrap_namedarrays(x, mean, variance, where) - axis_indices = x._lookup_indices(axis) - - plain = jnn.standardize(raw_x, axis_indices, mean=mean, variance=variance, epsilon=epsilon, where=where) - return NamedArray(plain, x.axes) @functools.wraps(jnn.one_hot) @@ -183,7 +100,7 @@ def cross_entropy_loss_and_log_normalizers( :return: tuple of two named arrays, with "per position" losses and log normalizers """ - log_normalizers = hax.nn.logsumexp(pred_y, Label) + log_normalizers = haliax.nn.normalization.logsumexp(pred_y, Label) neg_log_normalized = log_normalizers - pred_y loss = hax.dot(Label, target_y, neg_log_normalized) @@ -191,42 +108,40 @@ def cross_entropy_loss_and_log_normalizers( return loss, log_normalizers -def quick_gelu(x): - return x * sigmoid(1.702 * x) - - __all__ = [ "attention", + "one_hot", + "cross_entropy_loss", + "cross_entropy_loss_and_log_normalizers", + "Conv", + "ConvTranspose", + "Dropout", + "dropout", + "LayerNorm", + "Linear", + "Embedding", + "Stacked", "relu", + "gelu", + "quick_gelu", + "glu", "relu6", "sigmoid", - "softplus", "soft_sign", - "silu", + "softplus", "swish", + "silu", "log_sigmoid", "leaky_relu", "hard_sigmoid", "hard_silu", "hard_swish", "hard_tanh", - "elu", - "celu", - "selu", - "gelu", "logsumexp", "softmax", "log_softmax", - "one_hot", - "cross_entropy_loss", - "cross_entropy_loss_and_log_normalizers", - "quick_gelu", - "Conv", - "ConvTranspose", - "Dropout", - "dropout", - "LayerNorm", - "Linear", - "Embedding", - "Stacked", + "standardize", + "elu", + "celu", + "selu", ] diff --git a/src/haliax/nn/activations.py b/src/haliax/nn/activations.py new file mode 100644 index 0000000..2cb2ec1 --- /dev/null +++ b/src/haliax/nn/activations.py @@ -0,0 +1,89 @@ +import typing + +from jax import nn as jnn +from jax import numpy as jnp + +from ..axis import Axis +from ..core import NamedArray +from ..types import Scalar +from ..wrap import wrap_elemwise_unary + + +A = typing.TypeVar("A", Scalar, NamedArray, jnp.ndarray) + + +def relu(a: A) -> A: + return wrap_elemwise_unary(jnn.relu, a) + + +def relu6(a: A) -> A: + return wrap_elemwise_unary(jnn.relu6, a) + + +def sigmoid(a: A) -> A: + return wrap_elemwise_unary(jnn.sigmoid, a) + + +def softplus(a: A) -> A: + return wrap_elemwise_unary(jnn.softplus, a) + + +def soft_sign(a: A) -> A: + return wrap_elemwise_unary(jnn.soft_sign, a) + + +def silu(a: A) -> A: + return wrap_elemwise_unary(jnn.silu, a) + + +def swish(a: A) -> A: + return wrap_elemwise_unary(jnn.swish, a) + + +def log_sigmoid(a: A) -> A: + return wrap_elemwise_unary(jnn.log_sigmoid, a) + + +def leaky_relu(a: A) -> A: + return wrap_elemwise_unary(jnn.leaky_relu, a) + + +def hard_sigmoid(a: A) -> A: + return wrap_elemwise_unary(jnn.hard_sigmoid, a) + + +def hard_silu(a: A) -> A: + return wrap_elemwise_unary(jnn.hard_silu, a) + + +def hard_swish(a: A) -> A: + return wrap_elemwise_unary(jnn.hard_swish, a) + + +def hard_tanh(a: A) -> A: + return wrap_elemwise_unary(jnn.hard_tanh, a) + + +def elu(a: A) -> A: + return wrap_elemwise_unary(jnn.elu, a) + + +def celu(a: A) -> A: + return wrap_elemwise_unary(jnn.celu, a) + + +def selu(a: A) -> A: + return wrap_elemwise_unary(jnn.selu, a) + + +def gelu(a: A, approximate: bool = True) -> A: + return wrap_elemwise_unary(jnn.gelu, a, approximate=approximate) + + +def glu(x: NamedArray, axis: Axis) -> NamedArray: + axis_index = x.axes.index(axis) + return jnn.glu(x.array, axis_index) + + +def quick_gelu(x): + return x * sigmoid(1.702 * x) diff --git a/src/haliax/nn/attention.py b/src/haliax/nn/attention.py index 5739d1b..705e252 100644 --- a/src/haliax/nn/attention.py +++ b/src/haliax/nn/attention.py @@ -7,6 +7,8 @@ import numpy as np from jaxtyping import PRNGKeyArray import haliax +import haliax.nn.activations +import haliax.nn.normalization import haliax.random as hrandom from haliax.axis import Axis, AxisSelection, AxisSelector, AxisSpec from haliax.core import NamedArray @@ -48,7 +50,6 @@ def dot_product_attention_weights( :return: NamedArray of shape (QPos, KPos) """ # cf https://github.com/google/flax/blob/509bf97ea272e130d932920f45307ac98947d994/flax/linen/attention.py#L40 - import haliax.nn as hnn orig_dtype = query.dtype query = query / jnp.sqrt(query.axis_size(Head)) @@ -64,7 +65,7 @@ def dot_product_attention_weights( if mask is not None: weights = haliax.where(mask, weights, -1e9) - weights = hnn.softmax(weights, axis=KPos) + weights = haliax.nn.normalization.softmax(weights, axis=KPos) return weights.astype(orig_dtype) diff --git a/src/haliax/nn/mlp.py b/src/haliax/nn/mlp.py new file mode 100644 index 0000000..06c7504 --- /dev/null +++ b/src/haliax/nn/mlp.py @@ -0,0 +1,96 @@ +from typing import Callable, Sequence + +import equinox as eqx +import jax +from jaxtyping import PRNGKeyArray + +from ..axis import Axis, AxisSpec +from ..core import NamedArray +from ..jax_utils import maybe_rng_split +from .activations import relu +from .linear import Linear + + +DEFAULT_WIDTH_NAME = "mlp" + + +class MLP(eqx.Module): + """ + A multilayer perceptron (MLP) / feed-forward neural network (FFNN). + + MLPs, with their stacked linear layers often with non-semantic axes for hidden + dims, are not a particular strength of Haliax's design philosophy. Nonetheless, they are a useful tool for + many tasks, and so we provide this module. + + In Haliax, all axes must have names, and names must be unique within an array. We considered a few strategies + for naming the axes of an MLP, and settled on the following: By default, we alternate hidden names between "mlp" + and "mlp2". Input and output names must be specified, and are not repeated. This naming scheme is not perfect, + but does mean that model parallelism works reasonably well. + + NB: unlike Equinox's MLP, this MLP uses a static field for activation. If you want a learnable activation, you + likely want a unique activation per layer, which neither version provides. Instead, you should use a + [haliax.nn.Stacked][] with a suitable block. + """ + + activation: Callable = eqx.field(static=True) + layers: Sequence[Linear] + + @staticmethod + def init( + Input: AxisSpec, + Output: AxisSpec, + width: int | Axis, + depth: int, + activation: Callable = relu, + *, + use_bias: bool = True, + use_final_bias: bool = True, + key: PRNGKeyArray, + ): + Width = _get_width(width) + Width2 = Width.alias(Width.name + "2") + + keys = jax.random.split(key, depth + 1) + + layers = [] + + if depth == 0: + # special case: no hidden layers + layers.append(Linear.init(Input, Output, use_bias=use_final_bias, key=keys[0])) + else: + # first hidden layer + layers.append(Linear.init(Input, Width, use_bias=use_bias, key=keys[0])) + # middle hidden layers + cur = Width + next = Width2 + for i in range(1, depth): + layers.append(Linear.init(cur, next, use_bias=use_bias, key=keys[i])) + cur, next = next, cur + # final hidden layer + layers.append(Linear.init(cur, Output, use_bias=use_final_bias, key=keys[-1])) + + return MLP( + layers=tuple(layers), + activation=activation, + ) + + @property + def In(self) -> AxisSpec: + return self.layers[0].In + + @property + def Out(self) -> AxisSpec: + return self.layers[-1].Out + + def __call__(self, x: NamedArray, *, key=None) -> NamedArray: + keys = maybe_rng_split(key, len(self.layers)) + for layer, k in zip(self.layers[:-1], keys): + x = self.activation(layer(x, key=k)) + return self.layers[-1](x, key=keys[-1]) + + +def _get_width(Width: int | Axis) -> Axis: + if isinstance(Width, int): + return Axis(DEFAULT_WIDTH_NAME, Width) + else: + return Width diff --git a/src/haliax/nn/normalization.py b/src/haliax/nn/normalization.py index 4214b22..ba19894 100644 --- a/src/haliax/nn/normalization.py +++ b/src/haliax/nn/normalization.py @@ -1,11 +1,19 @@ -from typing import Optional +from typing import Optional, TypeVar import equinox as eqx +from jax import nn as jnn +from jax import numpy as jnp +import haliax import haliax as hax -from ..axis import AxisSpec +from ..axis import AxisSelection, AxisSpec from ..core import NamedArray +from ..types import Scalar +from ..wrap import unwrap_namedarrays, wrap_axiswise_call, wrap_reduction_call + + +A = TypeVar("A", Scalar, NamedArray, jnp.ndarray) class LayerNorm(eqx.Module): @@ -43,3 +51,34 @@ class LayerNorm(eqx.Module): if self.bias is not None: out = out + self.bias return out + + +def logsumexp(a: A, axis: Optional[AxisSelection] = None) -> A: + # TODO: logsumexp indirectly supports where via `b`. we should support it directly + return wrap_reduction_call(jnn.logsumexp, a, axis=axis, single_axis_only=False, supports_where=False) + + +def softmax(a: A, axis: Optional[AxisSelection] = None) -> A: + return wrap_axiswise_call(jnn.softmax, a, axis=axis, single_axis_only=False) + + +def log_softmax(a: A, axis: Optional[AxisSelection] = None) -> A: + return wrap_axiswise_call(jnn.log_softmax, a, axis=axis, single_axis_only=False) + + +def standardize( + x: NamedArray, + axis: AxisSpec, + *, + mean: Optional[NamedArray] = None, + variance: Optional[NamedArray] = None, + epsilon: float = 1e-5, + where: Optional[NamedArray] = None, +) -> NamedArray: + """Analogous to [jax.nn.standardize][], but with support for NamedArrays.""" + x, mean, variance, where = haliax.broadcast_arrays(x, mean, variance, where) # type: ignore + raw_x, mean, variance, where = unwrap_namedarrays(x, mean, variance, where) + axis_indices = x._lookup_indices(axis) + + plain = jnn.standardize(raw_x, axis_indices, mean=mean, variance=variance, epsilon=epsilon, where=where) + return NamedArray(plain, x.axes) diff --git a/src/haliax/util.py b/src/haliax/util.py index a4d75d9..7062bcb 100644 --- a/src/haliax/util.py +++ b/src/haliax/util.py @@ -33,13 +33,12 @@ class StringHolderEnum(type): # https://stackoverflow.com/questions/62881486/a-group-of-constants-in-python def __new__(cls, name, bases, members): - # this just iterates through the class dict and removes - # all the dunder methods cls.members = [v for k, v in members.items() if not k.startswith("__") and not callable(v)] return super().__new__(cls, name, bases, members) # giving your class an __iter__ method gives you membership checking # and the ability to easily convert to another iterable + @classmethod def __iter__(cls): yield from cls.members diff --git a/tests/test_nn.py b/tests/test_nn.py index 7a764e0..18a9b0c 100644 --- a/tests/test_nn.py +++ b/tests/test_nn.py @@ -1,6 +1,7 @@ import equinox as eqx import jax.nn import jax.random as jrandom +import pytest from jax import numpy as jnp import haliax as hax @@ -105,3 +106,42 @@ def test_standardize(): assert actual.axes == (b, c) assert jnp.all(jnp.isclose(actual.array, expected)) + + +@pytest.mark.parametrize("depth", [0, 1, 2, 3, 4, 5]) +def test_mlp(depth): + key = jrandom.PRNGKey(0) + H = Axis("H", 10) + C = Axis("C", 12) + W = Axis("W", 14) + + E = Axis("E", 16) + + hax_mlp = hax.nn.MLP.init((H, C, W), E, width=8, depth=depth, key=key) + x = hax.random.uniform(key, (H, C, W)) + assert hax_mlp(x).axes == (E,) + + hax_mlp = hax.nn.MLP.init((H, W), E, width=8, depth=depth, key=key) + assert hax_mlp(x).axes == (C, E) + + # with a named width + M = Axis("M", 18) + hax_mlp = hax.nn.MLP.init((H, W), E, width=M, depth=depth, key=key) + assert hax_mlp(x).axes == (C, E) + + # ensure that we actually use the name for the named width + if depth > 0: + assert hax_mlp.layers[0].Out == M + + if depth % 2 == 0: + assert hax_mlp.layers[-1].In == M.alias("M2") + else: + assert hax_mlp.layers[-1].In == M + + for i in range(1, depth): + if i % 2 == 0: + assert hax_mlp.layers[i].In == M.alias("M2") + assert hax_mlp.layers[i].Out == M + else: + assert hax_mlp.layers[i].In == M + assert hax_mlp.layers[i].Out == M.alias("M2") diff --git a/tests/test_utils.py b/tests/test_utils.py index f82c7f1..087b340 100644 --- a/tests/test_utils.py +++ b/tests/test_utils.py @@ -1,11 +1,7 @@ -from typing import Callable, List, Optional, TypeVar +from typing import TypeVar -import equinox as eqx import jax import pytest -from equinox import nn as nn -from equinox import static_field -from jaxtyping import PRNGKeyArray T = TypeVar("T") @@ -15,80 +11,6 @@ def skip_if_not_enough_devices(count: int): return pytest.mark.skipif(len(jax.devices()) < count, reason=f"Not enough devices ({len(jax.devices())})") -class MLP(eqx.Module): - """slightly less annoying MLP, used for testing purposes""" - - layers: List[nn.Linear] - activation: Callable = eqx.static_field() - final_activation: Callable = eqx.static_field() - in_size: int = static_field() - out_size: int = static_field() - width_size: int = static_field() - depth: int = static_field() - - def __init__( - self, - in_size: int, - out_size: int, - width_size: int, - depth: int, - activation: Callable = jax.nn.relu, - final_activation: Callable = lambda x: x, - *, - key: PRNGKeyArray, - **kwargs, - ): - """**Arguments**: - - - `in_size`: The size of the input layer. - - `out_size`: The size of the output layer. - - `width_size`: The size of each hidden layer. - - `depth`: The number of hidden layers. - - `activation`: The activation function after each hidden layer. Defaults to - ReLU. - - `final_activation`: The activation function after the output layer. Defaults - to the identity. - - `key`: A `jax.random.PRNGKey` used to provide randomness for parameter - initialisation. (Keyword only argument.) - """ - - super().__init__(**kwargs) - keys = jax.random.split(key, depth + 1) - layers = [] - if depth == 0: - layers.append(nn.Linear(in_size, out_size, key=keys[0])) - else: - layers.append(nn.Linear(in_size, width_size, key=keys[0])) - for i in range(depth - 1): - layers.append(nn.Linear(width_size, width_size, key=keys[i + 1])) - layers.append(nn.Linear(width_size, out_size, key=keys[-1])) - self.layers = layers - self.in_size = in_size - self.out_size = out_size - self.width_size = width_size - self.depth = depth - self.activation = activation # type: ignore - self.final_activation = final_activation # type: ignore - - def __call__(self, x, *, key: Optional[PRNGKeyArray] = None): - """**Arguments:** - - - `x`: A JAX array with shape `(in_size,)`. - - `key`: Ignored; provided for compatibility with the rest of the Equinox API. - (Keyword only argument.) - - **Returns:** - - A JAX array with shape `(out_size,)`. - """ - for layer in self.layers[:-1]: - x = layer(x) - x = self.activation(x) - x = self.layers[-1](x) - x = self.final_activation(x) - return x - - def has_torch(): try: import torch # noqa F401 commit 577d6658203070e89eed6ac948dacb68d8a0506d Date: 2023-11-03T17:19:50-07:00 refactor dot_product_attention to be more general but also check arguments better. add self_attention function (#49) diff --git a/docs/nn.md b/docs/nn.md index e2d530f..ab2d957 100644 --- a/docs/nn.md +++ b/docs/nn.md @@ -39,6 +39,7 @@ We don't provide an explicit attention module, but we do provide an attention fu :::haliax.nn.attention.dot_product_attention :::haliax.nn.attention.dot_product_attention_weights +:::haliax.nn.attention.self_attention ### Masks ::: haliax.nn.attention.causal_mask diff --git a/src/haliax/__init__.py b/src/haliax/__init__.py index 2ea5b08..d5d7b8f 100644 --- a/src/haliax/__init__.py +++ b/src/haliax/__init__.py @@ -191,6 +191,7 @@ def concatenate(axis: AxisSelector, arrays: Sequence[NamedArray]) -> NamedArray: # we want to use the axis name for `axis`, because it's not uncommon for those to be different lengths in the arrays axes = axes[:axis_index] + (aname,) + axes[axis_index + 1 :] arrays = [a.rearrange(axes) for a in arrays] + print([a.axes for a in arrays]) new_axes = arrays[0].axes[:axis_index] + (axis,) + arrays[0].axes[axis_index + 1 :] return NamedArray(jnp.concatenate([a.array for a in arrays], axis=axis_index), new_axes) diff --git a/src/haliax/axis.py b/src/haliax/axis.py index e50e8d5..e6904df 100644 --- a/src/haliax/axis.py +++ b/src/haliax/axis.py @@ -281,14 +281,31 @@ def overlapping_axes(ax1: AxisSelection, ax2: AxisSelection) -> Tuple[AxisSelect return tuple(out) -def axis_name(ax: AxisSelector) -> str: +@overload +def axis_name(ax: AxisSelector) -> str: # type: ignore + ... + + +@overload +def axis_name(ax: Sequence[AxisSelector]) -> Tuple[str, ...]: # type: ignore + ... + + +def axis_name(ax: AxisSelection) -> Union[str, Tuple[str, ...]]: """ Returns the name of the axis. If ax is a string, returns ax. If ax is an Axis, returns ax.name """ - if isinstance(ax, Axis): - return ax.name + + def _ax_name(ax: AxisSelector) -> str: + if isinstance(ax, Axis): + return ax.name + else: + return ax + + if isinstance(ax, (Axis, str)): + return _ax_name(ax) else: - return ax + return tuple(_ax_name(x) for x in ax) class dslice(eqx.Module): diff --git a/src/haliax/core.py b/src/haliax/core.py index fd8b9af..4c72a08 100644 --- a/src/haliax/core.py +++ b/src/haliax/core.py @@ -180,9 +180,10 @@ class NamedArray: raise ValueError(f"Axis {axes} not found") else: result = [] - for i in indices: + assert isinstance(axes, Sequence) + for i, ax in zip(indices, axes): if i is None: - raise ValueError(f"Axis {axes} not found") + raise ValueError(f"Axis {ax} not found in {self.shape}") result.append(self.axes[i]) return tuple(result) diff --git a/src/haliax/nn/attention.py b/src/haliax/nn/attention.py index 705e252..ccbe909 100644 --- a/src/haliax/nn/attention.py +++ b/src/haliax/nn/attention.py @@ -7,15 +7,14 @@ import numpy as np from jaxtyping import PRNGKeyArray import haliax -import haliax.nn.activations -import haliax.nn.normalization import haliax.random as hrandom -from haliax.axis import Axis, AxisSelection, AxisSelector, AxisSpec +from haliax.axis import Axis, AxisSelection, AxisSelector, AxisSpec, axis_name from haliax.core import NamedArray from haliax.types import PrecisionLike +from haliax.util import ensure_tuple -# With attention we usually distinguish between the mask and the bias, though the former is just a special case of the +# With attention, we usually distinguish between the mask and the bias, though the former is just a special case of the # latter. In practice, the mask is a boolean array that is applied using `where` to the logits, while the bias is a # float array that is added to the logits. The mask is usually used to prevent attention to certain positions, while # the bias is usually used to encourage or discourage attention to certain positions. @@ -26,7 +25,7 @@ from haliax.types import PrecisionLike def dot_product_attention_weights( - Head: AxisSelector, + Key: AxisSelector, KPos: AxisSelection, query: NamedArray, key: NamedArray, @@ -39,8 +38,8 @@ def dot_product_attention_weights( NamedArray version of dot product attention. Computes the logits for the attention weights. Note that the "Pos" axis in query must be distinct from the "Pos" axis in key. - :param Head: Axis of head dimension - :param KPos: Axis of key sequence length. Can be an AxisSpec to attend along more than one axis. + :param Key: Axis of head dimension + :param KPos: Axis or axes that are attended to :param query: NamedArray of shape (QPos, KeySize) :param key: NamedArray of shape (KPos, KeySize) :param mask: Optional[NamedArray] broadcast compatible with (KeySize, QPos, KPos). Should be boolean @@ -52,28 +51,27 @@ def dot_product_attention_weights( # cf https://github.com/google/flax/blob/509bf97ea272e130d932920f45307ac98947d994/flax/linen/attention.py#L40 orig_dtype = query.dtype - query = query / jnp.sqrt(query.axis_size(Head)) + query = query / jnp.sqrt(query.axis_size(Key)) if attention_dtype is not None: query = query.astype(attention_dtype) key = key.astype(attention_dtype) - weights = haliax.dot(Head, query, key, precision=precision) + weights = haliax.dot(Key, query, key, precision=precision) if bias is not None: weights = weights + bias if mask is not None: weights = haliax.where(mask, weights, -1e9) - weights = haliax.nn.normalization.softmax(weights, axis=KPos) + weights = haliax.nn.softmax(weights, axis=KPos) return weights.astype(orig_dtype) def dot_product_attention( - QPos: Axis, - KPos: Axis, - KeySize: Axis, + KPos: AxisSelection, + Key: AxisSelector, query: NamedArray, key: NamedArray, value: NamedArray, @@ -85,12 +83,11 @@ def dot_product_attention( """ NamedArray version of dot product attention. This can be multi-headed or not. - :param QPos: Axis of sequence length :param KPos: Axis of key sequence length - :param KeySize: Axis of head dimension - :param query: NamedArray of shape (QPos, KeySize) - :param key: NamedArray of shape (KPos, KeySize) - :param value: NamedArray of shape (KPos, KeySize) + :param Key: Axis of head dimension + :param query: NamedArray of shape {..., QPos, KeySize} + :param key: NamedArray of shape {..., KPos, KeySize} + :param value: NamedArray of shape {..., KPos, KeySize} :param mask: Optional[NamedArray] broadcast compatible with (KeySize, QPos, KPos). Should be boolean :param bias: Optional[NamedArray] broadcast compatible with (KeySize, QPos, KPos). Should be float :param attention_dtype: Optional dtype to use for attention @@ -101,17 +98,86 @@ def dot_product_attention( For example, mask is frequently just a boolean array of shape (QPos, KPos), while bias is frequently a float array of shape (KeySize, QPos, KPos) or (KeySize, KPos) """ - # cf https://github.com/google/flax/blob/509bf97ea272e130d932920f45307ac98947d994/flax/linen/attention.py#L125 + if not isinstance(query, NamedArray): + raise TypeError( + f"query must be a NamedArray, got {type(query)}. Probably you are still using the old signature" + "of dot_product_attention. It no longer takes a QPos argument." + ) + KPos = ensure_tuple(key.resolve_axis(KPos)) + # any axis in KPos that's in query is a problem + for axis in KPos: + if axis in query.axes: + raise ValueError( + f"Axis {axis} in KPos is also in query. Attended-to axes must be distinct from query axis" + ) + + weights = dot_product_attention_weights( + Key, KPos, query, key, mask=mask, bias=bias, attention_dtype=attention_dtype, precision=precision + ) - # rename key/value length axis if it's the same as the query length axis - if KPos == QPos: - KPos = QPos.alias(KPos.name + "_key") - key = key.rename({KPos: QPos}) - value = value.rename({KPos: QPos}) + return haliax.dot(KPos, weights, value) - weights = dot_product_attention_weights(KeySize, KPos, query, key, mask, bias, attention_dtype, precision) - return haliax.dot(KPos, weights, value) +def self_attention( + Pos: AxisSelection, + Key: AxisSelector, + query: NamedArray, + key: NamedArray, + value: NamedArray, + is_causal: bool, # make people be explicit about this + mask: Optional[NamedArray] = None, + bias: Optional[NamedArray] = None, + attention_dtype: Optional[jnp.dtype] = None, + precision: PrecisionLike = None, +) -> NamedArray: + """ + Convenience function for self attention. This is just a wrapper around dot_product_attention that makes sure + the query and key axes are distinct. This is a common mistake and it's better to catch it early. + + Note that mask and bias's Pos axis/axes should be key axes, not query axes. You can't use + query axes in a mask/bias with this method. Use dot_product_attention directly if you need to do that. + As an exception, if is_causal is True, then we create a causal mask for you. + + Args: + Pos: Axis of sequence length + Key: Axis of head dimension + query: NamedArray of shape {..., Pos, KeySize} + key: NamedArray of shape {..., Pos, KeySize} + value: NamedArray of shape {..., Pos, KeySize} + is_causal: whether to use a causal mask + mask: Optional[NamedArray] broadcast compatible with (KeySize, Pos, Pos). Should be boolean + bias: Optional[NamedArray] broadcast compatible with (KeySize, Pos, Pos). Should be float + attention_dtype: Optional dtype to use for attention + precision: PrecisionLike for dot product. See precision argument to jax.lax.dot_general + """ + Pos = ensure_tuple(key.resolve_axis(Pos)) + + # rename key/value length axes if necessary + QPos, renames = _get_query_pos_renames(Pos) + + query = query.rename(renames) + + if is_causal: + # require that QPos is a single axis + if len(Pos) != 1: + raise ValueError("QPos must be a single axis for causal self attention") + mask = causal_mask(QPos[0], Pos[0]) + + out = dot_product_attention(Pos, Key, query, key, value, mask, bias, attention_dtype, precision) + # now rename back + return out.rename({v: k for k, v in renames.items()}) + + +def _get_query_pos_renames(Pos): + new_Pos: list[Axis] = [] + renames: dict[str, str] = {} + for i, axis in enumerate(Pos): + ax_name = axis_name(axis) + axis = axis.alias(f"q_{ax_name}") + renames[ax_name] = axis.name + new_Pos.append(axis) + + return tuple(new_Pos), renames def mask_to_bias(mask: NamedArray, mask_value: float = -1e9) -> NamedArray: diff --git a/tests/test_attention.py b/tests/test_attention.py index fb58623..b8d267e 100644 --- a/tests/test_attention.py +++ b/tests/test_attention.py @@ -1,11 +1,74 @@ +import jax.numpy as jnp import numpy as np from jax.random import PRNGKey import haliax as hax -from haliax.nn.attention import alibi_attention_bias, dot_product_attention_weights, forgetful_causal_mask +from haliax.nn.attention import ( + alibi_attention_bias, + causal_mask, + dot_product_attention, + dot_product_attention_weights, + forgetful_causal_mask, + self_attention, +) from test_utils import skip_if_no_torch +def test_dot_product_attention_requires_axis_to_be_present(): + Pos = hax.Axis("Pos", 20) + KeyPos = hax.Axis("Pos_key", 20) + NumHeads = hax.Axis("NumHeads", 1) + Hid = hax.Axis("Hid", 8) + + query = hax.ones((NumHeads, KeyPos, Hid)) # NB: KeyPos not Pos + key = hax.ones((KeyPos, NumHeads, Hid)) + value = hax.ones((KeyPos, NumHeads, Hid)) + + try: + dot_product_attention(Pos, Hid, query, key, value) + except ValueError as e: + assert "not found" in str(e) + else: + raise AssertionError("Should have raised an error") + + +def test_attention_doesnt_allow_overlapping_axes(): + KeyPos = hax.Axis("Pos_key", 20) + NumHeads = hax.Axis("NumHeads", 1) + Hid = hax.Axis("Hid", 8) + + query = hax.ones((NumHeads, KeyPos, Hid)) # NB: KeyPos not Pos + key = hax.ones((KeyPos, NumHeads, Hid)) + value = hax.ones((KeyPos, NumHeads, Hid)) + + try: + dot_product_attention(KeyPos, Hid, query, key, value) + except ValueError as e: + assert "must be distinct" in str(e) + else: + raise AssertionError("Should have raised an error") + + +def test_self_attention_basically_works(): + Pos = hax.Axis("Pos", 20) + KeyPos = hax.Axis("Pos_key", 20) + NumHeads = hax.Axis("NumHeads", 1) + Hid = hax.Axis("Hid", 8) + + query = hax.ones((NumHeads, Pos, Hid)) + + result = self_attention(Pos, Hid, query, query, query, is_causal=True) + assert result.axes == (NumHeads, Pos, Hid) + + k = query.rename({Pos: KeyPos}) + cmask = causal_mask(Pos, KeyPos) + result2 = dot_product_attention(KeyPos, Hid, query, k, k, mask=cmask) + assert result2.axes == (NumHeads, Pos, Hid) + + # tight tolerances because it should be exactly the same computation + assert jnp.allclose(result.array, result2.array) + + def test_alibi_attention_bias(): KeyPos = hax.Axis("KeyPos", 20) NumHeads = hax.Axis("NumHeads", 1) commit f567ade6a7e07d157e61163b8cc61db29ea5c0f0 Date: 2023-11-03T17:31:41-07:00 remove dumb print diff --git a/src/haliax/__init__.py b/src/haliax/__init__.py index d5d7b8f..2ea5b08 100644 --- a/src/haliax/__init__.py +++ b/src/haliax/__init__.py @@ -191,7 +191,6 @@ def concatenate(axis: AxisSelector, arrays: Sequence[NamedArray]) -> NamedArray: # we want to use the axis name for `axis`, because it's not uncommon for those to be different lengths in the arrays axes = axes[:axis_index] + (aname,) + axes[axis_index + 1 :] arrays = [a.rearrange(axes) for a in arrays] - print([a.axes for a in arrays]) new_axes = arrays[0].axes[:axis_index] + (axis,) + arrays[0].axes[axis_index + 1 :] return NamedArray(jnp.concatenate([a.array for a in arrays], axis=axis_index), new_axes) commit 8702f6d8bb949bd74b185cc21aefa4e2d8544a4a Date: 2023-11-21T23:57:05-06:00 apply where mask even if no reduction diff --git a/src/haliax/nn/__init__.py b/src/haliax/nn/__init__.py index df2edcd..086a8ee 100644 --- a/src/haliax/nn/__init__.py +++ b/src/haliax/nn/__init__.py @@ -77,11 +77,12 @@ def cross_entropy_loss( f"target_y has dtype {target_y.dtype}, which is not a floating point type. This is probably a mistake." ) - if reduction is UNSPECIFIED: - reduction = haliax.mean - if reduction is not None: + if reduction is UNSPECIFIED: + reduction = haliax.mean loss = reduction(loss, where=where, axis=reduction_axis) + elif where is not None: + loss = hax.where(where, loss, 0) return loss commit 669e2c2e5a81f87c615cd41e979bcfd2339d07a0 Date: 2023-11-26T21:02:33-08:00 fix tostring when NamedArray doesn't have an array diff --git a/src/haliax/core.py b/src/haliax/core.py index 4c72a08..83a8e85 100644 --- a/src/haliax/core.py +++ b/src/haliax/core.py @@ -192,21 +192,24 @@ class NamedArray: # * array is a tracer, in which case we want just the named shape (and an indication that it's a tracer) # * array is a jnp.ndarray, in which case we want the named shape and the array - if isinstance(self.array, jax.core.Tracer): - return f"NamedArray(Tracer<{self.dtype}{self.shape}>)" - elif self.ndim <= 1: - return f"NamedArray({self.dtype}{self.shape}, {self.array})" + if is_jax_array_like(self.array): + if isinstance(self.array, jax.core.Tracer): + return f"NamedArray(Tracer<{self.dtype}{self.shape}>)" + elif self.ndim <= 1: + return f"NamedArray({self.dtype}{self.shape}, {self.array})" + else: + return f"NamedArray({self.dtype}{self.shape},\n{self.array})" else: - return f"NamedArray({self.dtype}{self.shape},\n{self.array})" + return f"NamedArray(???{self.shape}, {self.array})" def __tree_pp__(self, **kwargs): # For Equinox's tree pretty printer import jax._src.pretty_printer as pp - if kwargs.get("short_arrays", True): + if kwargs.get("short_arrays", True) and is_jax_array_like(self.array): return pp.text(f"Named({self.dtype}{self.shape})") else: - return str(self) + return pp.text(str(self)) @overload def _lookup_indices(self, axis: AxisSelector) -> Optional[int]: # type: ignore commit 81a48ffd557edad1931ffa7ba2176da23fc1a4bf Date: 2023-12-05T00:01:50-08:00 add an unstacked method to Stacked diff --git a/src/haliax/__init__.py b/src/haliax/__init__.py index 2ea5b08..a7cca9a 100644 --- a/src/haliax/__init__.py +++ b/src/haliax/__init__.py @@ -9,6 +9,7 @@ import haliax.debug as debug import haliax.nn as nn import haliax.random as random import haliax.tree_util as tree_util +import haliax.util as util from ._src.rearrange import rearrange from .axis import ( @@ -52,6 +53,7 @@ from .ops import clip, isclose, pad_left, trace, tril, triu, where from .partitioning import auto_sharded, axis_mapping, fsdp, named_jit, shard_with_axis_mapping from .specialized_fns import top_k from .types import Scalar +from .util import is_named_array from .wrap import ( ReductionFunction, SimpleReductionFunction, @@ -998,4 +1000,5 @@ __all__ = [ "top_k", "ravel", "flatten", + "is_named_array", ] diff --git a/src/haliax/nn/scan.py b/src/haliax/nn/scan.py index e183cfe..f9750c3 100644 --- a/src/haliax/nn/scan.py +++ b/src/haliax/nn/scan.py @@ -1,9 +1,11 @@ import functools -from typing import Dict, Generic, Optional, Protocol, Type, TypeVar +from typing import Dict, Generic, Optional, Protocol, Sequence, Type, TypeVar import equinox as eqx +import jax import haliax +import haliax.util from haliax.jax_utils import filter_checkpoint from ..axis import Axis @@ -109,3 +111,30 @@ class Stacked(eqx.Module, Generic[M]): # TODO: this is for logic that's in levanter. We should move that logic to haliax I guess? def _state_dict_key_map(self) -> Dict[str, Optional[str]]: return {"stacked": None} + + def unstacked(self) -> Sequence[M]: + """ + Returns the unstacked version of this module. This is useful for logging or saving checkpoints. + Returns: + A sequence of modules, one for each element of the stack + """ + + def unbatch_leaf(x): + if haliax.is_named_array(x): + if haliax.selects_axis(x.axes, self.Block): + return haliax.unbind(x, self.Block) + else: + return tuple(x for _ in range(self.Block.size)) + elif haliax.jax_utils.is_jax_array_like(x): + assert ( + x.shape[0] == self.Block.size + ), f"Expected first dimension to be {self.Block.size}, got {x.shape[0]}" + return tuple(x[i] for i in range(self.Block.size)) + else: + return tuple(x for _ in range(self.Block.size)) + + leaves, structure = jax.tree_util.tree_flatten(self.stacked, is_leaf=haliax.is_named_array) + unstacked_leaves = tuple(map(unbatch_leaf, leaves)) + # now we need to transpose the leaves + unstacked_leaves = tuple(zip(*unstacked_leaves)) + return tuple(map(lambda x: jax.tree_util.tree_unflatten(structure, x), unstacked_leaves)) diff --git a/tests/test_scan.py b/tests/test_scan.py new file mode 100644 index 0000000..0120c30 --- /dev/null +++ b/tests/test_scan.py @@ -0,0 +1,42 @@ +import equinox as eqx +import jax + +import haliax as hax +from haliax.nn.scan import Stacked + + +def test_unstacked(): + class Module(eqx.Module): + named: hax.NamedArray + array: jax.Array + static: int = eqx.static_field() + + def __call__(self, x): + return x + self.array + self.static + + @staticmethod + def init(named, array, static): + return Module(named=named, array=array, static=static) + + Block = hax.Axis("block", 4) + E = hax.Axis("E", 10) + + initial_named = hax.random.uniform(jax.random.PRNGKey(0), (Block, E)) + + m = Stacked.init(Block, Module)(named=initial_named, array=jax.numpy.ones(Block.size), static=1) + + assert m.stacked.named.axes == (Block, E) + assert m.stacked.array.shape == (Block.size,) + assert m.stacked.static == 1 + + unstacked = m.unstacked() + + assert len(unstacked) == Block.size + + for i, module in enumerate(unstacked): + assert module.named.axes == (E,) + assert module.array.shape == () + assert module.static == 1 + + assert hax.all(module.named == m.stacked.named["block", i]) + assert hax.all(module.array == m.stacked.array[i]) commit ce484b78d249bc4c88fdc97c4cd0ba8ab97a2d1a Date: 2023-12-18T14:27:29-08:00 delete from TODOs we won't do diff --git a/src/haliax/core.py b/src/haliax/core.py index 83a8e85..a1ad045 100644 --- a/src/haliax/core.py +++ b/src/haliax/core.py @@ -378,10 +378,6 @@ class NamedArray: def clip(self, a_min=None, a_max=None) -> Any: return haliax.clip(self, a_min=a_min, a_max=a_max) - # TODO - # def compress(self, condition, axis: Optional[int] = None) -> Any: - # ... - def conj(self) -> "NamedArray": return NamedArray(self.array.conj(), self.axes) @@ -450,10 +446,6 @@ class NamedArray: def real(self) -> "NamedArray": return NamedArray(self.array.real, self.axes) - # TODO: what should reshape look like? - # def reshape(self, *args, order='C') -> Any: - # ... - def round(self, decimals=0) -> "NamedArray": return haliax.round(self, decimals=decimals) commit a3b8e7ba26c3b71c1dbef178d802d51baf47488d Date: 2023-12-18T14:30:03-08:00 use _get_mesh in physical_axis_size diff --git a/src/haliax/partitioning.py b/src/haliax/partitioning.py index ded5054..455cc95 100644 --- a/src/haliax/partitioning.py +++ b/src/haliax/partitioning.py @@ -516,13 +516,12 @@ def physical_axis_name(axis: AxisSelector, mapping: Optional[ResourceMapping] = def physical_axis_size(axis: AxisSelector, mapping: Optional[ResourceMapping] = None) -> Optional[int]: """Get the physical axis size for a logical axis. This is the product of the size of all physical axes that this logical axis is mapped to.""" - # TODO: shouldn't be accessing this internal api, but... - from jax.experimental.maps import thread_resources + mesh = _get_mesh() - try: - mesh_shape = thread_resources.env.shape - except AttributeError: - raise ValueError("No resource mapping found") + if mesh is None: + raise ValueError("No mesh found") + + mesh_shape = mesh.shape name: Union[None, str, Sequence[str]] = physical_axis_name(axis, mapping) if name is None: commit 7073fcfd6a33638b97c104a44c5b50385b3e3eb5 Date: 2023-12-18T22:55:11-08:00 unify auto_sharded and shard_with_axis_mapping to just `shard` diff --git a/docs/api.md b/docs/api.md index 8937c1a..a3b9cdb 100644 --- a/docs/api.md +++ b/docs/api.md @@ -272,11 +272,17 @@ The exceptions are documented here: See also the section on [Partitioning](partitioning.md). ::: haliax.partitioning.axis_mapping -::: haliax.shard_with_axis_mapping -::: haliax.auto_sharded +::: haliax.shard ::: haliax.named_jit ::: haliax.fsdp ::: haliax.partitioning.round_axis_for_partitioning ::: haliax.partitioning.physical_axis_name ::: haliax.partitioning.physical_axis_size ::: haliax.partitioning.sharding_for_axis + +### Old API + +These functions are being deprecated and will be removed in a future release. + +::: haliax.shard_with_axis_mapping +::: haliax.auto_sharded diff --git a/docs/partitioning.md b/docs/partitioning.md index d0dae2f..ba56628 100644 --- a/docs/partitioning.md +++ b/docs/partitioning.md @@ -71,16 +71,16 @@ SeqLen = hax.Axis("seqlen", 512) axis_mapping = {"batch": "data", } batch = hax.zeros((Batch, SeqLen), dtype=jnp.float32) -batch = hax.shard_with_axis_mapping(batch, axis_mapping) +batch = hax.shard(batch, axis_mapping) # we also have "auto_sharded" and support context mappings for axis mappings: with hax.axis_mapping({"batch": "data"}): batch = hax.zeros((Batch, SeqLen), dtype=jnp.float32) - batch = hax.auto_sharded(batch) + batch = hax.shard(batch) ``` Unlike in JAX, which has separate APIs for partitioning arrays inside and outside of `jit`, Haliax has a single API: -both `hax.shard_with_axis_mapping` and `hax.auto_sharded` work inside and outside of `jit`. Haliax automatically +`hax.shard` work inside and outside of `jit`. Haliax automatically chooses which JAX function to use based on context. @@ -108,6 +108,11 @@ with hax.axis_mapping({"batch": "data"}): ### Sharding Arrays and PyTrees These functions are used to shard arrays and PyTrees of arrays, e.g. Modules. +This is the main function you will use to shard arrays: + +::: haliax.shard + +These are older functions that are being deprecated and will be removed in a future release: ::: haliax.shard_with_axis_mapping ::: haliax.auto_sharded diff --git a/src/haliax/__init__.py b/src/haliax/__init__.py index a7cca9a..a7efeac 100644 --- a/src/haliax/__init__.py +++ b/src/haliax/__init__.py @@ -50,7 +50,7 @@ from .core import ( ) from .hof import fold, map, scan, vmap from .ops import clip, isclose, pad_left, trace, tril, triu, where -from .partitioning import auto_sharded, axis_mapping, fsdp, named_jit, shard_with_axis_mapping +from .partitioning import auto_sharded, axis_mapping, fsdp, named_jit, shard, shard_with_axis_mapping from .specialized_fns import top_k from .types import Scalar from .util import is_named_array @@ -987,6 +987,7 @@ __all__ = [ "named_jit", "fsdp", "shard_with_axis_mapping", + "shard", "enable_shape_checks", "are_shape_checks_enabled", "isclose", diff --git a/src/haliax/_src/rearrange.py b/src/haliax/_src/rearrange.py index 4b3356e..7f02376 100644 --- a/src/haliax/_src/rearrange.py +++ b/src/haliax/_src/rearrange.py @@ -9,7 +9,7 @@ import jax.numpy as jnp from ..axis import Axis, AxisSelector, axis_name from ..core import NamedArray -from ..partitioning import auto_sharded +from ..partitioning import shard @dataclasses.dataclass @@ -389,7 +389,7 @@ def einops_rearrange(array: NamedArray, expression: str, **bindings: AxisSelecto if plan.intermediate_axes != array.axes: raw_array = raw_array.reshape([ax.size for ax in plan.intermediate_axes]) array = NamedArray(raw_array, plan.intermediate_axes) - array = auto_sharded(array) + array = shard(array) raw_array = array.array final_shape = tuple(ax.size for ax in plan.final_axes) @@ -401,7 +401,7 @@ def einops_rearrange(array: NamedArray, expression: str, **bindings: AxisSelecto else: finished_array = raw_array - return auto_sharded(NamedArray(finished_array, plan.final_axes)) + return shard(NamedArray(finished_array, plan.final_axes)) def _plan_rearrange( diff --git a/src/haliax/core.py b/src/haliax/core.py index a1ad045..e7f0bcf 100644 --- a/src/haliax/core.py +++ b/src/haliax/core.py @@ -1018,7 +1018,7 @@ def dot(axis: AxisSelection, *arrays: NamedArray, precision: PrecisionLike = Non ) out = NamedArray(output, output_axes) - return haliax.auto_sharded(out) + return haliax.shard(out) def split(a: NamedArray, axis: AxisSelector, new_axes: Sequence[Axis]) -> Sequence[NamedArray]: @@ -1065,9 +1065,8 @@ def unbind(array: NamedArray, axis: AxisSelector) -> List[NamedArray]: # instead we just loop over the axes pulling one out at a time axis_size = array.axes[axis_index].size arrays = [jnp.take(array.array, i, axis=axis_index) for i in range(axis_size)] - from haliax.partitioning import auto_sharded - return [auto_sharded(NamedArray(a, new_axes)) for a in arrays] + return [haliax.shard(NamedArray(a, new_axes)) for a in arrays] def roll(array: NamedArray, shift: Union[int, Tuple[int, ...]], axis: AxisSelection) -> NamedArray: diff --git a/src/haliax/jax_utils.py b/src/haliax/jax_utils.py index e065839..aacd19b 100644 --- a/src/haliax/jax_utils.py +++ b/src/haliax/jax_utils.py @@ -126,3 +126,7 @@ def named_call(f=_UNSPECIFIED, name: Optional[str] = None): name = f.__qualname__ return jax.named_scope(name)(f) + + +def is_in_jit(): + return isinstance(jnp.zeros((), dtype=jnp.float32), jax.core.Tracer) diff --git a/src/haliax/nn/linear.py b/src/haliax/nn/linear.py index 4f9a659..bbd924e 100644 --- a/src/haliax/nn/linear.py +++ b/src/haliax/nn/linear.py @@ -45,11 +45,11 @@ class Linear(eqx.Module): """ del key q = inputs.dot(self.In, self.weight) - q = hax.auto_sharded(q) + q = hax.shard(q) if self.bias is not None: q = q + self.bias - q = hax.auto_sharded(q) + q = hax.shard(q) return q diff --git a/src/haliax/partitioning.py b/src/haliax/partitioning.py index 455cc95..8e64627 100644 --- a/src/haliax/partitioning.py +++ b/src/haliax/partitioning.py @@ -2,6 +2,7 @@ import contextlib import functools import threading import typing +import warnings from math import prod from typing import Callable, Mapping, Optional, ParamSpec, Sequence, TypeVar, Union @@ -20,7 +21,7 @@ from jaxtyping import PyTree from .axis import Axis, AxisSelection, AxisSelector from .core import NamedArray -from .jax_utils import Static, is_jax_array_like +from .jax_utils import Static, is_in_jit, is_jax_array_like from .tree_util import hashable_combine, hashable_partition from .util import StringHolderEnum, ensure_tuple, is_named_array @@ -32,6 +33,7 @@ ResourceMapping = Mapping[(str), PhysicalAxisSpec] F = typing.TypeVar("F", bound=typing.Callable) Args = ParamSpec("Args") R = typing.TypeVar("R", covariant=True) +T = TypeVar("T", bound=PyTree) class ResourceAxis(StringHolderEnum): @@ -84,9 +86,6 @@ def current_thread_local_mapping(): return _mapping_holder.thread_data.resource_mapping -T = TypeVar("T", bound=PyTree) - - def auto_sharded(x: T, mesh: Optional[Mesh] = None) -> T: """ Shard a PyTree using the global axis mapping. NamedArrays in the PyTree are sharded using the axis mapping @@ -99,10 +98,10 @@ def auto_sharded(x: T, mesh: Optional[Mesh] = None) -> T: if mapping is None: return x - return shard_with_axis_mapping(x, mapping, mesh) + return shard(x, mapping, mesh) -def shard_with_axis_mapping(x: T, mapping: ResourceMapping, mesh: Optional[Mesh] = None) -> T: +def shard(x: T, mapping: Optional[ResourceMapping] = None, mesh: Optional[Mesh] = None) -> T: """ Shard a PyTree using the provided axis mapping. NamedArrays in the PyTree are sharded using the axis mapping. Other arrays are not sharded (unless they're already sharded). @@ -110,8 +109,19 @@ def shard_with_axis_mapping(x: T, mapping: ResourceMapping, mesh: Optional[Mesh] Inside of a jit context, this method grounds out in calls to `with_sharding_constraint`. Outside of a jit context, this method grounds out in either device_put or make_array_from_callback, depending on whether the resulting sharding spans more than one host. + + Outside of jit, this method will warn if there is no resource mapping found. """ + if mapping is None: + mapping = current_thread_local_mapping() + + if mapping is None: + if not is_in_jit(): + warnings.warn("No resource mapping found. Not sharding.", RuntimeWarning) + + return x + def _do_device_put(x): if not is_named_array(x): return x @@ -146,6 +156,12 @@ def shard_with_axis_mapping(x: T, mapping: ResourceMapping, mesh: Optional[Mesh] return jax.tree_util.tree_map(_do_device_put, x, is_leaf=is_named_array) +@functools.wraps(shard) +def shard_with_axis_mapping(x: T, mapping: ResourceMapping, mesh: Optional[Mesh] = None) -> T: + # warnings.warn("`shard_with_axis_mapping` is deprecated. Use `shard` instead", DeprecationWarning) + return shard(x, mapping, mesh) + + def infer_resource_partitions( tree: PyTree, resource_mapping: Optional[ResourceMapping] = None, @@ -351,10 +367,13 @@ def named_jit( Functionally this is very similar to something like: ```python - arg = hax.shard_with_axis_mapping(arg, in_axis_resources) + def wrapped_fn(arg): + result = fn(arg) + return hax.shard(result, out_axis_resources) + + arg = hax.shard(arg, in_axis_resources) with hax.axis_mapping(axis_resources): - result = jax.jit(fn, **pjit_args)(arg) - result = hax.shard_with_axis_mapping(result, out_axis_resources) + result = jax.jit(wrapped_fn, **pjit_args)(arg) return result ``` @@ -573,6 +592,8 @@ __all__ = [ "ResourceMapping", "axis_mapping", "auto_sharded", + "shard", + "shard_with_axis_mapping", "infer_resource_partitions", "named_jit", "fsdp", diff --git a/src/haliax/random.py b/src/haliax/random.py index b4893f5..a466ee2 100644 --- a/src/haliax/random.py +++ b/src/haliax/random.py @@ -13,7 +13,7 @@ from haliax.util import ensure_tuple from .axis import Axis, AxisSelector, AxisSpec, selects_axis from .jax_utils import named_call -from .partitioning import auto_sharded, physical_axis_name, physical_axis_size, pspec_for_axis +from .partitioning import physical_axis_name, physical_axis_size, pspec_for_axis @named_call @@ -25,7 +25,7 @@ def uniform( maxval = broadcast_to(maxval, shape).array jax_shape = _to_jax_shape(shape) jax_array = jrandom.uniform(key=key, shape=jax_shape, dtype=dtype, minval=minval, maxval=maxval) - return auto_sharded(NamedArray(jax_array, shape)) + return haliax.shard(NamedArray(jax_array, shape)) @named_call @@ -33,7 +33,7 @@ def normal(key, shape: AxisSpec, dtype=float): shape = ensure_tuple(shape) jax_shape = _to_jax_shape(shape) jax_array = jrandom.normal(key=key, shape=jax_shape, dtype=dtype) - return auto_sharded(NamedArray(jax_array, shape)) + return haliax.shard(NamedArray(jax_array, shape)) @named_call @@ -42,7 +42,7 @@ def bernoulli(key, shape: AxisSpec, p: NamedOrNumeric): p = broadcast_to(p, shape).array jax_shape = _to_jax_shape(shape) jax_array = jrandom.bernoulli(key=key, p=p, shape=jax_shape) - return auto_sharded(NamedArray(jax_array, shape)) + return haliax.shard(NamedArray(jax_array, shape)) @named_call @@ -52,7 +52,7 @@ def randint(key, shape: AxisSpec, minval: NamedOrNumeric, maxval: NamedOrNumeric maxval = broadcast_to(maxval, shape).array jax_shape = _to_jax_shape(shape) jax_array = jrandom.randint(key=key, shape=jax_shape, minval=minval, maxval=maxval, dtype=dtype) - return auto_sharded(NamedArray(jax_array, shape)) + return haliax.shard(NamedArray(jax_array, shape)) @named_call @@ -61,7 +61,7 @@ def poisson(key, shape: AxisSpec, lam: NamedOrNumeric, dtype=int): lam = broadcast_to(lam, shape).array jax_shape = _to_jax_shape(shape) jax_array = jrandom.poisson(key=key, lam=lam, shape=jax_shape, dtype=dtype) - return auto_sharded(NamedArray(jax_array, shape)) + return haliax.shard(NamedArray(jax_array, shape)) @named_call @@ -69,7 +69,7 @@ def exponential(key, shape: AxisSpec, dtype=float): shape = ensure_tuple(shape) jax_shape = _to_jax_shape(shape) jax_array = jrandom.exponential(key=key, shape=jax_shape, dtype=dtype) - return auto_sharded(NamedArray(jax_array, shape)) + return haliax.shard(NamedArray(jax_array, shape)) @named_call @@ -78,7 +78,7 @@ def gamma(key, shape: AxisSpec, a: NamedOrNumeric, dtype=float): a = broadcast_to(a, shape).array jax_shape = _to_jax_shape(shape) jax_array = jrandom.gamma(key=key, a=a, shape=jax_shape, dtype=dtype) - return auto_sharded(NamedArray(jax_array, shape)) + return haliax.shard(NamedArray(jax_array, shape)) @named_call @@ -88,7 +88,7 @@ def beta(key, shape: AxisSpec, a: NamedOrNumeric, b: NamedOrNumeric, dtype=float b = broadcast_to(b, shape).array jax_shape = _to_jax_shape(shape) jax_array = jrandom.beta(key=key, a=a, b=b, shape=jax_shape, dtype=dtype) - return auto_sharded(NamedArray(jax_array, shape)) + return haliax.shard(NamedArray(jax_array, shape)) @named_call @@ -96,7 +96,7 @@ def laplace(key, shape: AxisSpec, dtype=float): shape = ensure_tuple(shape) jax_shape = _to_jax_shape(shape) jax_array = jrandom.laplace(key=key, shape=jax_shape, dtype=dtype) - return auto_sharded(NamedArray(jax_array, shape)) + return haliax.shard(NamedArray(jax_array, shape)) @named_call @@ -104,7 +104,7 @@ def cauchy(key, shape: AxisSpec, dtype=float): shape = ensure_tuple(shape) jax_shape = _to_jax_shape(shape) jax_array = jrandom.cauchy(key=key, shape=jax_shape, dtype=dtype) - return auto_sharded(NamedArray(jax_array, shape)) + return haliax.shard(NamedArray(jax_array, shape)) @named_call @@ -112,7 +112,7 @@ def logistic(key, shape: AxisSpec, dtype=float): shape = ensure_tuple(shape) jax_shape = _to_jax_shape(shape) jax_array = jrandom.logistic(key=key, shape=jax_shape, dtype=dtype) - return auto_sharded(NamedArray(jax_array, shape)) + return haliax.shard(NamedArray(jax_array, shape)) @named_call @@ -122,7 +122,7 @@ def truncated_normal(key, shape: AxisSpec, lower: NamedOrNumeric, upper: NamedOr upper = broadcast_to(upper, shape).array jax_shape = _to_jax_shape(shape) jax_array = jrandom.truncated_normal(key=key, lower=lower, upper=upper, shape=jax_shape, dtype=dtype) - return auto_sharded(NamedArray(jax_array, shape)) + return haliax.shard(NamedArray(jax_array, shape)) _enforce_sharded_generate = False @@ -203,7 +203,7 @@ def ball(key, shape: AxisSpec, D: Axis, p: float = 2.0, dtype=float): shape = ensure_tuple(shape) jax_shape = _to_jax_shape(shape) jax_array = jrandom.ball(key=key, shape=jax_shape, d=D.size, p=p, dtype=dtype) - return auto_sharded(NamedArray(jax_array, shape + (D,))) + return haliax.shard(NamedArray(jax_array, shape + (D,))) @named_call @@ -232,7 +232,7 @@ def choice( expected_shape = shape + tuple(a.axes[:index] + a.axes[index + 1 :]) - return auto_sharded(NamedArray(jax_array, expected_shape)) + return haliax.shard(NamedArray(jax_array, expected_shape)) @named_call @@ -267,7 +267,7 @@ def categorical(key, logits: NamedArray, axis: AxisSelector, shape: Optional[Axi jax_shape = _to_jax_shape(shape) jax_array = jrandom.categorical(key, logits.array, axis=index, shape=jax_shape) - return auto_sharded(NamedArray(jax_array, shape)) + return haliax.shard(NamedArray(jax_array, shape)) @named_call @@ -275,14 +275,14 @@ def gumbel(key, shape: AxisSpec, dtype=float): shape = ensure_tuple(shape) jax_shape = _to_jax_shape(shape) jax_array = jrandom.gumbel(key, jax_shape, dtype=dtype) - return auto_sharded(NamedArray(jax_array, shape)) + return haliax.shard(NamedArray(jax_array, shape)) @named_call def permutation(key, x: NamedArray, axis: AxisSelector, independent: bool = False): axis_index = x._lookup_indices(axis) jax_array = jrandom.permutation(key, x.array, axis_index, independent=independent) - return auto_sharded(NamedArray(jax_array, x.axes)) + return haliax.shard(NamedArray(jax_array, x.axes)) @named_call @@ -290,7 +290,7 @@ def rademacher(key, shape: AxisSpec, dtype=float): shape = ensure_tuple(shape) jax_shape = _to_jax_shape(shape) jax_array = jrandom.rademacher(key, jax_shape, dtype=dtype) - return auto_sharded(NamedArray(jax_array, shape)) + return haliax.shard(NamedArray(jax_array, shape)) @named_call @@ -299,7 +299,7 @@ def t(key, shape: AxisSpec, df: NamedOrNumeric, dtype=float): df = broadcast_to(df, shape) jax_shape = _to_jax_shape(shape) jax_array = jrandom.t(key, df.array, jax_shape, dtype=dtype) - return auto_sharded(NamedArray(jax_array, shape)) + return haliax.shard(NamedArray(jax_array, shape)) @named_call @@ -309,7 +309,7 @@ def weibull_min(key, shape: AxisSpec, scale: NamedOrNumeric, concentration: Name concentration = broadcast_to(concentration, shape) jax_shape = _to_jax_shape(shape) jax_array = jrandom.weibull_min(key, scale.array, concentration.array, jax_shape, dtype=dtype) - return auto_sharded(NamedArray(jax_array, shape)) + return haliax.shard(NamedArray(jax_array, shape)) @named_call @@ -318,7 +318,7 @@ def pareto(key, shape: AxisSpec, b: NamedOrNumeric, dtype=float): b = broadcast_to(b, shape) jax_shape = _to_jax_shape(shape) jax_array = jrandom.pareto(key, b.array, jax_shape, dtype=dtype) - return auto_sharded(NamedArray(jax_array, shape)) + return haliax.shard(NamedArray(jax_array, shape)) @named_call @@ -327,7 +327,7 @@ def loggamma(key, shape: AxisSpec, a: NamedOrNumeric, dtype=float): a = broadcast_to(a, shape) jax_shape = _to_jax_shape(shape) jax_array = jrandom.loggamma(key, a.array, jax_shape, dtype=dtype) - return auto_sharded(NamedArray(jax_array, shape)) + return haliax.shard(NamedArray(jax_array, shape)) def _to_jax_shape(shape): diff --git a/tests/test_partitioning.py b/tests/test_partitioning.py index fe87c73..55b1fb5 100644 --- a/tests/test_partitioning.py +++ b/tests/test_partitioning.py @@ -137,10 +137,10 @@ def test_shard_with_axis_mapping_outside_pjit(): x = hax.ones((Dim1, Dim2)) y = hax.ones((Dim2, Dim3)) - x = hax.shard_with_axis_mapping(x, resource_map) + x = hax.shard(x, resource_map) assert x.array.sharding == NamedSharding(mesh, PartitionSpec(None, ResourceAxis.DATA)) - y = hax.shard_with_axis_mapping(y, resource_map) + y = hax.shard(y, resource_map) assert y.array.sharding == NamedSharding(mesh, PartitionSpec(ResourceAxis.DATA, ResourceAxis.MODEL)) @@ -157,7 +157,7 @@ def test_named_jit_works_without_axis_resources(): assert r.array.sharding.is_fully_replicated def foo2(x): - return hax.shard_with_axis_mapping(x, resource_map) + return hax.shard(x, resource_map) pjit_foo2 = named_jit(foo2) r2 = pjit_foo2(hax.ones((Dim1, Dim2))) @@ -180,10 +180,10 @@ def test_shard_with_axis_mapping_inside_jit(): @named_jit(in_axis_resources={}, out_axis_resources=resource_map) def do_shard(x, y): - x = hax.shard_with_axis_mapping(x, resource_map) + x = hax.shard(x, resource_map) assert_inside_pjit(x, NamedSharding(mesh, PartitionSpec(None, ResourceAxis.DATA))) - y = hax.shard_with_axis_mapping(y, resource_map) + y = hax.shard(y, resource_map) assert_inside_pjit(y, NamedSharding(mesh, PartitionSpec(ResourceAxis.DATA, ResourceAxis.MODEL))) return x, y commit dab6f751e2b1f2e085fb4c07573c5be9ce5e7cde Date: 2023-12-20T14:24:40-08:00 fix some upcoming deprecations in jax diff --git a/src/haliax/jax_utils.py b/src/haliax/jax_utils.py index aacd19b..9ed6a6c 100644 --- a/src/haliax/jax_utils.py +++ b/src/haliax/jax_utils.py @@ -17,7 +17,7 @@ class Static(eqx.Module): value: Any = eqx.field(static=True) -def shaped_rng_split(key, split_shape: Union[int, Sequence[int]] = 2) -> jrandom.KeyArray: +def shaped_rng_split(key, split_shape: Union[int, Sequence[int]] = 2) -> PRNGKeyArray: if isinstance(split_shape, int): num_splits = split_shape split_shape = (num_splits,) + key.shape commit 0f29c95eea05ed9e2d9d01c7ae48f4231cf1a57d Date: 2023-12-20T15:10:25-08:00 remove default dtype for one hot diff --git a/src/haliax/nn/__init__.py b/src/haliax/nn/__init__.py index 086a8ee..20193e0 100644 --- a/src/haliax/nn/__init__.py +++ b/src/haliax/nn/__init__.py @@ -49,7 +49,7 @@ from .scan import Stacked @functools.wraps(jnn.one_hot) -def one_hot(x: Union[NamedArray, int], class_axis: Axis, *, dtype=jnp.float_) -> NamedArray: +def one_hot(x: Union[NamedArray, int], class_axis: Axis, *, dtype=None) -> NamedArray: if isinstance(x, NamedArray): array = jnn.one_hot(x.array, num_classes=class_axis.size, dtype=dtype) return NamedArray(array, x.axes + (class_axis,)) commit b8b10f6e5c60f011e26d446e96288c29692c0d97 Date: 2023-12-20T21:05:37-08:00 Add Pooling operations (#51) diff --git a/docs/nn.md b/docs/nn.md index ab2d957..32a43cf 100644 --- a/docs/nn.md +++ b/docs/nn.md @@ -33,6 +33,15 @@ provided. Similarly, for transposed convolutions, we have [haliax.nn.ConvTranspo ::: haliax.nn.Conv ::: haliax.nn.ConvTranspose +### Pooling + +As with convolutions, we don't distinguish between 1D, 2D, and 3D pooling, and instead have a single +pooling operation for each of the kinds of reductions: + +::: haliax.nn.max_pool +::: haliax.nn.mean_pool +::: haliax.nn.min_pool + ## Attention We don't provide an explicit attention module, but we do provide an attention function and several related functions: diff --git a/src/haliax/axis.py b/src/haliax/axis.py index e6904df..e707d27 100644 --- a/src/haliax/axis.py +++ b/src/haliax/axis.py @@ -34,6 +34,10 @@ str and Axis""" AxisSpec = Union[Axis, Sequence[Axis]] """AxisSpec is a type that can be used to specify the axes of an array, usually for creation or adding a new axis whose size can't be determined another way. Axis or sequence of Axis""" +ShapeDict = Mapping[str, int] +"""ShapeDict is a type that can be used to specify the axes of an array, usually for creation or adding a new axis""" +PartialShapeDict = Mapping[str, Optional[int]] +"""Similar to an AxisSelection, in dict form.""" def selects_axis(selector: AxisSelection, selected: AxisSelection) -> bool: @@ -46,7 +50,7 @@ def selects_axis(selector: AxisSelection, selected: AxisSelection) -> bool: except ValueError: return False - selector_dict = _spec_to_dict(selector) + selector_dict = axis_spec_to_shape_dict(selector) selected_tuple = ensure_tuple(selected) # type: ignore for ax in selected_tuple: @@ -81,16 +85,16 @@ def is_axis_compatible(ax1: AxisSelector, ax2: AxisSelector): @overload -def _spec_to_dict(axis_spec: AxisSpec) -> Dict[str, int]: # type: ignore +def axis_spec_to_shape_dict(axis_spec: AxisSpec) -> Dict[str, int]: # type: ignore ... @overload -def _spec_to_dict(axis_spec: AxisSelection) -> Dict[str, Optional[int]]: # type: ignore +def axis_spec_to_shape_dict(axis_spec: AxisSelection) -> Dict[str, Optional[int]]: # type: ignore ... -def _spec_to_dict(axis_spec: AxisSelection) -> Dict[str, Optional[int]]: # type: ignore +def axis_spec_to_shape_dict(axis_spec: AxisSelection) -> Dict[str, Optional[int]]: # type: ignore spec = ensure_tuple(axis_spec) # type: ignore shape_dict: Dict[str, Optional[int]] = {} for ax in spec: @@ -158,8 +162,8 @@ def union_axes(a1: AxisSelection, a2: AxisSelection) -> AxisSelection: a1 = ensure_tuple(a1) a2 = ensure_tuple(a2) - a1_dict = _spec_to_dict(a1) - a2_dict = _spec_to_dict(a2) + a1_dict = axis_spec_to_shape_dict(a1) + a2_dict = axis_spec_to_shape_dict(a2) for ax, sz in a2_dict.items(): if ax in a1_dict: @@ -185,7 +189,7 @@ def eliminate_axes(axis_spec: AxisSelection, to_remove: AxisSelection) -> AxisSe """Returns a new axis spec that is the same as the original, but without any axes in axes. Raises if any axis in to_remove is not present in axis_spec""" to_remove = ensure_tuple(to_remove) - axis_spec_dict = _spec_to_dict(axis_spec) + axis_spec_dict = axis_spec_to_shape_dict(axis_spec) for ax in to_remove: name = axis_name(ax) if name not in axis_spec_dict: @@ -209,7 +213,7 @@ def without_axes(axis_spec: AxisSelection, to_remove: AxisSelection) -> AxisSele """As eliminate_axes, but does not raise if any axis in to_remove is not present in axis_spec""" to_remove = ensure_tuple(to_remove) - axis_spec_dict = _spec_to_dict(axis_spec) + axis_spec_dict = axis_spec_to_shape_dict(axis_spec) for ax in to_remove: name = axis_name(ax) if name in axis_spec_dict: @@ -218,6 +222,38 @@ def without_axes(axis_spec: AxisSelection, to_remove: AxisSelection) -> AxisSele return _dict_to_spec(axis_spec_dict) +@typing.overload +def unsize_axes(axis_spec: AxisSelection, to_unsize: AxisSelection) -> AxisSelection: + ... + + +@typing.overload +def unsize_axes(axis_spec: AxisSelection) -> AxisSelection: + ... + + +def unsize_axes(axis_spec: AxisSelection, to_unsize: Optional[AxisSelection] = None) -> AxisSelection: + """ + This function is used to remove the sizes of axes in an axis spec. + There are two overloads: + - If to_unsize is None, then all axes in axis_spec will be unsized + - If to_unsize is not None, then all axes in to_unsize will be unsized. Raises if any axis in to_unsize is not present in axis_spec + """ + + if to_unsize is None: + return tuple(axis_name(ax) for ax in ensure_tuple(axis_spec)) # type: ignore + + to_unsize = ensure_tuple(to_unsize) + axis_spec_dict: dict[str, Optional[int]] = axis_spec_to_shape_dict(axis_spec) # type: ignore + for ax in to_unsize: + name = axis_name(ax) + if name not in axis_spec_dict: + raise ValueError(f"Axis {name} not present in axis spec {axis_spec}") + axis_spec_dict[name] = None + + return _dict_to_spec(axis_spec_dict) + + @overload def replace_axis(axis_spec: AxisSpec, old: AxisSelector, new: AxisSpec) -> AxisSpec: ... @@ -257,7 +293,7 @@ def overlapping_axes(ax1: AxisSelection, ax2: AxisSelection) -> Tuple[AxisSelect def overlapping_axes(ax1: AxisSelection, ax2: AxisSelection) -> Tuple[AxisSelector, ...]: """Returns a tuple of axes that are present in both ax1 and ax2""" - ax2_dict = _spec_to_dict(ax2) + ax2_dict = axis_spec_to_shape_dict(ax2) out: List[AxisSelector] = [] ax1 = ensure_tuple(ax1) @@ -356,16 +392,6 @@ def dblock(idx: int, size: int) -> dslice: return dslice(idx * size, size) -def is_pallas_dslice(x: object) -> bool: - try: - from jax.experimental.pallas import dslice as pdslice - except ImportError: - return False - - _PALLAS_DSLICE_TYPE = type(pdslice(0, 1)) - return isinstance(x, _PALLAS_DSLICE_TYPE) - - __all__ = [ "Axis", "AxisSelector", @@ -374,8 +400,10 @@ __all__ = [ "axis_name", "concat_axes", "union_axes", + "axis_spec_to_shape_dict", "ds", "dslice", + "dblock", "eliminate_axes", "is_axis_compatible", "overlapping_axes", @@ -383,5 +411,5 @@ __all__ = [ "selects_axis", "union_axes", "without_axes", - "is_pallas_dslice", + "unsize_axes", ] diff --git a/src/haliax/core.py b/src/haliax/core.py index e7f0bcf..6cf5eca 100644 --- a/src/haliax/core.py +++ b/src/haliax/core.py @@ -14,7 +14,7 @@ import numpy as np import haliax import haliax.axis -from haliax.jax_utils import is_jax_array_like +from haliax.jax_utils import is_jax_array_like, is_pallas_dslice from haliax.util import ensure_tuple from ._src.util import index_where, py_slice, slice_t @@ -26,7 +26,6 @@ from .axis import ( axis_name, dslice, eliminate_axes, - is_pallas_dslice, selects_axis, union_axes, ) @@ -252,8 +251,19 @@ class NamedArray: return tuple(self._lookup_indices(a) for a in axis) # Axis rearrangement - def rearrange(self, axis: Sequence[Union[AxisSelector, EllipsisType]]) -> "NamedArray": - return haliax.rearrange(self, axis) + @typing.overload + def rearrange(self, axes: Sequence[AxisSelector | EllipsisType]) -> "NamedArray": + """See [haliax.rearrange][] for details.""" + pass + + @typing.overload + def rearrange(self, expression: str, **bindings: AxisSelector | int) -> "NamedArray": + """See [haliax.rearrange][] for details.""" + pass + + def rearrange(self, *args, **kwargs) -> "NamedArray": + """See [haliax.rearrange][] for details.""" + return haliax.rearrange(self, *args, **kwargs) def broadcast_to(self, axes: AxisSpec) -> "NamedArray": axes = ensure_tuple(axes) diff --git a/src/haliax/jax_utils.py b/src/haliax/jax_utils.py index 9ed6a6c..7856b25 100644 --- a/src/haliax/jax_utils.py +++ b/src/haliax/jax_utils.py @@ -130,3 +130,13 @@ def named_call(f=_UNSPECIFIED, name: Optional[str] = None): def is_in_jit(): return isinstance(jnp.zeros((), dtype=jnp.float32), jax.core.Tracer) + + +def is_pallas_dslice(x: object) -> bool: + try: + from jax.experimental.pallas import dslice as pdslice + except ImportError: + return False + + _PALLAS_DSLICE_TYPE = type(pdslice(0, 1)) + return isinstance(x, _PALLAS_DSLICE_TYPE) diff --git a/src/haliax/nn/__init__.py b/src/haliax/nn/__init__.py index 20193e0..a779cee 100644 --- a/src/haliax/nn/__init__.py +++ b/src/haliax/nn/__init__.py @@ -42,6 +42,7 @@ from .embedding import Embedding from .linear import Linear from .mlp import MLP from .normalization import LayerNorm, log_softmax, logsumexp, softmax, standardize +from .pool import max_pool, mean_pool, min_pool from .scan import Stacked @@ -145,4 +146,7 @@ __all__ = [ "elu", "celu", "selu", + "max_pool", + "mean_pool", + "min_pool", ] diff --git a/src/haliax/nn/pool.py b/src/haliax/nn/pool.py new file mode 100644 index 0000000..c504520 --- /dev/null +++ b/src/haliax/nn/pool.py @@ -0,0 +1,244 @@ +# Pooling operations, inspired by Flax +from functools import reduce +from typing import Callable, Literal, Optional + +import jax + +import haliax + +from ..axis import AxisSpec, axis_spec_to_shape_dict, unsize_axes +from ..core import NamedArray +from ..types import Scalar +from ..util import ensure_tuple + + +Padding = Literal["SAME", "VALID"] | int | tuple[tuple[int, int], ...] + +DEFAULT_PADDING: Literal["VALID"] = "VALID" + +# TODO: add dilation? + + +def pool( + Window: AxisSpec, + inputs: NamedArray, + init: Scalar, + reduce_fn: Callable[[Scalar, Scalar], Scalar], + stride: Optional[int | tuple[int, ...]] = None, + padding: Padding = DEFAULT_PADDING, + use_ceil: bool = False, +) -> NamedArray: + """ + General function for pooling. Broadly based on the Flax implementation. + + Pooling functions are implemented using the ReduceWindow XLA op. + + Notes: + JAX only implements autodiff for a few specific reductions (min, max, sum). + + Args: + Window: the size of the window to pool over + inputs: input data with dimensions (batch, window dims..., features). + init: the initial value for the reduction + reduce_fn: a reduce function of the form `(T, T) -> T`. + stride: int, or a sequence of `n` integers, representing the inter-window + stride (default: `(1, ..., 1)`). + padding: either the string `'SAME'`, the string `'VALID'`, or a sequence + of `n` `(low, high)` integer pairs that give the padding to apply before + and after each spatial dimension, or an integer to pad all dimensions. + use_ceil: if True, will use ceil instead of floor to compute the output shape + Returns: + The output of the reduction for each window slice. + """ + Window = ensure_tuple(Window) + + reduce_fn = _patch_up_reduce_fn(reduce_fn) + + window_map = axis_spec_to_shape_dict(Window) + dims = [] + for ax in inputs.axes: + if ax.name in window_map: + dims.append(window_map[ax.name]) + else: + dims.append(1) + + if isinstance(stride, int): + stride = (stride,) * len(Window) + + if stride is not None: + if len(Window) != len(stride): + raise ValueError(f"len(Window) ({len(Window)}) != len(stride) ({len(stride)})") + stride = ensure_tuple(stride) + stride_map = {w.name: s for w, s in zip(Window, stride)} + stride_out = [] + for ax in inputs.axes: + if ax.name in stride_map: + stride_out.append(stride_map[ax.name]) + else: + stride_out.append(1) + + stride = tuple(stride_out) + del stride_out + else: + stride = (1,) * len(dims) + stride_map = {w.name: 1 for w in Window} + + if isinstance(padding, int): + padding = ((padding, padding),) * len(Window) + + if not isinstance(padding, str): + padding = tuple(map(tuple, padding)) # type: ignore + if len(padding) != len(Window): + raise ValueError(f"len(padding) ({len(padding)}) != len(Window) ({len(Window)})") + if not all([len(x) == 2 for x in padding]): + raise ValueError(f"each entry in padding must be length 2, got {padding}") + + padding_map = {w.name: p for w, p in zip(Window, padding)} + if use_ceil: + window_inputs = {w.name: ax.size for w, ax in zip(Window, inputs.axes)} + padding_map = _use_ceil_padding( + window_inputs=window_inputs, + window_kernel=window_map, + window_padding=padding_map, + window_stride=stride_map, + ) + + padding_out = [] + for ax in inputs.axes: + if ax.name in padding_map: + padding_out.append(padding_map[ax.name]) + else: + padding_out.append((0, 0)) + + padding = tuple(padding_out) + elif padding == "VALID" and use_ceil: + padding = "SAME" + else: + padding = padding.upper() # type: ignore + if padding not in ("SAME", "VALID"): + raise ValueError(f"padding must be 'SAME' or 'VALID', got {padding}") + + assert inputs.ndim == len(dims), f"len({inputs.shape}) != len({dims})" + y = jax.lax.reduce_window(inputs.array, init, reduce_fn, dims, stride, padding) + + out_axes = unsize_axes(inputs.axes, Window) + + return haliax.named(y, out_axes) + + +def _patch_up_reduce_fn(reduce_fn): + if reduce_fn is haliax.max: + reduce_fn = jax.lax.max + elif reduce_fn is haliax.min: + reduce_fn = jax.lax.min + elif reduce_fn is haliax.sum: + reduce_fn = jax.lax.add + elif reduce_fn is haliax.prod: + reduce_fn = jax.lax.mul + + return reduce_fn + + +def max_pool( + Window: AxisSpec, + inputs: NamedArray, + stride: Optional[int | tuple[int, ...]] = None, + padding: Padding = DEFAULT_PADDING, + use_ceil: bool = False, +) -> NamedArray: + """ + Max pooling. + + Args: + Window: the size of the window to pool over + inputs: input data with dimensions (batch, window dims..., features). + stride: a sequence of `n` integers, representing the inter-window + stride (default: `(1, ..., 1)`). + padding: either the string `'SAME'`, the string `'VALID'`, or a sequence + of `n` `(low, high)` integer pairs that give the padding to apply before + and after each spatial dimension. + Returns: + The maximum value in each window slice. + """ + return pool(Window, inputs, -float("inf"), jax.lax.max, stride, padding, use_ceil=use_ceil) + + +def min_pool( + Window: AxisSpec, + inputs: NamedArray, + stride: Optional[int | tuple[int, ...]] = None, + padding: Padding = DEFAULT_PADDING, + use_ceil: bool = False, +) -> NamedArray: + """ + Min pooling. + + Args: + Window: the size of the window to pool over + inputs: input data with dimensions (batch, window dims..., features). + stride: a sequence of `n` integers, representing the inter-window + stride (default: `(1, ..., 1)`). + padding: either the string `'SAME'`, the string `'VALID'`, or a sequence + of `n` `(low, high)` integer pairs that give the padding to apply before + and after each spatial dimension. + use_ceil: if True, will use ceil instead of floor to compute the output shape + Returns: + The minimum value in each window slice. + """ + return pool(Window, inputs, float("inf"), jax.lax.min, stride, padding, use_ceil=use_ceil) + + +def mean_pool( + Window: AxisSpec, + inputs: NamedArray, + stride: Optional[int | tuple[int, ...]] = None, + padding: Padding = DEFAULT_PADDING, + *, + use_ceil: bool = False, + count_include_pad: bool = False, +) -> NamedArray: + """ + Mean pooling. + + Args: + Window: the size of the window to pool over + inputs: input data with dimensions (batch, window dims..., features). + stride: a sequence of `n` integers, representing the inter-window + stride (default: `(1, ..., 1)`). + padding: either the string `'SAME'`, the string `'VALID'`, or a sequence + of `n` `(low, high)` integer pairs that give the padding to apply before + and after each spatial dimension. + Returns: + The mean value in each window slice. + """ + tots = pool(Window, inputs, 0, jax.lax.add, stride, padding, use_ceil=use_ceil) + if count_include_pad: + Window = ensure_tuple(Window) + window_size = reduce(lambda x, y: x * y, [w.size for w in Window]) + return tots / window_size + else: + inputs_axes_without_batches = inputs.resolve_axis(unsize_axes(Window)) + ones = haliax.ones(inputs_axes_without_batches) + tots = tots / pool(Window, ones, 0.0, jax.lax.add, stride, padding) + return tots + + +def _use_ceil_padding( + window_inputs: dict[str, int], + window_kernel: dict[str, int], + window_padding: dict[str, tuple[int, int]], + window_stride: dict[str, int], +): + # cribbed/adapted from equinox + new_padding = {} + for ax in window_inputs.keys(): + input_size = window_inputs[ax] + kernel_size = window_kernel[ax] + stride = window_stride[ax] + left_padding, right_padding = window_padding[ax] + if (input_size + left_padding + right_padding - kernel_size) % stride == 0: + new_padding[ax] = (left_padding, right_padding) + else: + new_padding[ax] = (left_padding, right_padding + stride) + + return new_padding diff --git a/src/haliax/util.py b/src/haliax/util.py index 7062bcb..a175931 100644 --- a/src/haliax/util.py +++ b/src/haliax/util.py @@ -27,6 +27,15 @@ def ensure_tuple(x: Union[Sequence[T], T]) -> Tuple[T, ...]: return (x,) +def maybe_untuple(x: Union[Sequence[T], T]) -> Union[T, Sequence[T]]: + """ + If x is a tuple with one element, return that element. Otherwise return x. + """ + if isinstance(x, tuple) and len(x) == 1: + return x[0] + return x + + class StringHolderEnum(type): """Like a python enum but just holds string constants, as opposed to wrapped string constants""" diff --git a/tests/test_pool.py b/tests/test_pool.py new file mode 100644 index 0000000..f086247 --- /dev/null +++ b/tests/test_pool.py @@ -0,0 +1,183 @@ +import equinox as eqx +import jax +import jax.numpy as jnp + +import haliax +import haliax as hax +from haliax.nn.pool import max_pool, mean_pool + + +# Tests largely cribbed from equinox + + +def test_maxpool1d(): + D = hax.Axis("D", 14) + x = hax.arange(D) + output = max_pool((D.resize(2),), x, stride=(3,)) + answer = jnp.array([1, 4, 7, 10, 13], dtype=jnp.int32) + + assert jnp.all(output.array == answer) + + answer = jnp.array([2, 5, 8, 11]) + output = max_pool(D.resize(3), x, stride=(3,), padding=0) + assert jnp.all(output.array == answer) + + # max_pool = eqx.nn.MaxPool1d(kernel_size=3, stride=3, padding=0, use_ceil=True) + answer = jnp.array([2, 5, 8, 11, 13]) + output = max_pool(D.resize(3), x, stride=(3,), padding=0, use_ceil=True) + assert jnp.all(output.array == answer) + + # test batch axes + B = hax.Axis("B", 2) + x = x.rearrange("(B D) -> B D", B=B) + output = max_pool(D.resize(2), x, stride=(3,), padding="VALID") + answer = jnp.array([[1, 4], [8, 11]]) + assert jnp.all(output.array == answer) + + output = max_pool(D.resize(2), x, stride=(3,), use_ceil=True) + answer = jnp.array([[1, 4, 6], [8, 11, 13]]) + assert jnp.all(output.array == answer) + + output = max_pool(D.resize(3), x, stride=(3,), padding=0) + answer = jnp.array([[2, 5], [9, 12]]) + assert jnp.all(output.array == answer) + + output = max_pool(D.resize(3), x, stride=(3,), padding=0, use_ceil=True) + answer = jnp.array([[2, 5, 6], [9, 12, 13]]) + assert jnp.all(output.array == answer) + + output = max_pool(D.resize(2), x, stride=(3,), padding="SAME") + answer = jnp.array([[1, 4, 6], [8, 11, 13]]) + assert jnp.all(output.array == answer) + + +def test_maxpool2d(): + _x = jnp.arange(36).reshape(6, 6) + x = hax.named(_x, ("H", "W")) + + # max_pool = eqx.nn.MaxPool2d(2, (3, 2)) + output = max_pool((hax.Axis("H", 2), hax.Axis("W", 2)), x, stride=(3, 2)) + answer = jnp.array([[7, 9, 11], [25, 27, 29]]) + + assert jnp.all(output.array == answer) + + output = max_pool((hax.Axis("H", 3), hax.Axis("W", 3)), x, stride=2, padding=1) + answer = jnp.array([[7, 9, 11], [19, 21, 23], [31, 33, 35]]) + + assert jnp.all(output.array == answer) + + # test batch axes + B = hax.Axis("B", 2) + x = haliax.stack(B, [x, x]) + + output = max_pool((hax.Axis("H", 2), hax.Axis("W", 2)), x, stride=(3, 2)) + answer = jnp.array([[[7, 9, 11], [25, 27, 29]], [[7, 9, 11], [25, 27, 29]]]) + + assert jnp.all(output.array == answer) + + +def test_maxpool3d(): + _x = jnp.arange(64).reshape(4, 4, 4) + x = hax.named(_x, ("H", "W", "D")) + output = max_pool((hax.Axis("H", 2), hax.Axis("W", 2), hax.Axis("D", 2)), x, stride=(3, 2, 1)) + + answer = jnp.array([[[21, 22, 23], [29, 30, 31]]]) + + assert jnp.all(output.array == answer) + + answer = jnp.asarray( + [ + [[37, 39, 39], [45, 47, 47], [45, 47, 47]], + [[53, 55, 55], [61, 63, 63], [61, 63, 63]], + ] + ) + output = max_pool( + (hax.Axis("H", 3), hax.Axis("W", 3), hax.Axis("D", 3)), + x, + stride=2, + padding=((0, 1), (1, 1), (1, 1)), + use_ceil=True, + ) + assert jnp.all(output.array == answer) + + +def test_mean_pool_1d(): + D = hax.Axis("D", 14) + x = hax.arange(D) + output = mean_pool((D.resize(2),), x, stride=(3,)) + answer = jnp.array([0.5, 3.5, 6.5, 9.5, 12.5]) + + assert jnp.all(output.array == answer) + + # no pad + output = mean_pool(D.resize(3), x, stride=(3,), padding=0) + answer = jnp.array([1, 4, 7, 10]) + assert jnp.all(output.array == answer) + + # pad, no include pad in avg + output = mean_pool(D.resize(3), x, stride=(3,), padding="SAME", count_include_pad=False) + answer = jnp.array([1, 4, 7, 10, 12.5]) + + assert jnp.all(output.array == answer) + + output = mean_pool(D.resize(3), x, stride=(3,), padding="SAME", count_include_pad=True) + answer = jnp.array([1, 4, 7, 10, (12 + 13) / 3.0]) + + assert jnp.all(output.array == answer) + + +def test_mean_pool_2d(): + _x = jnp.arange(36).reshape(6, 6) + x = hax.named(_x, ("H", "W")) + + output = mean_pool((hax.Axis("H", 1), hax.Axis("W", 3)), x, stride=2) + answer = jnp.array([[1, 3], [13, 15], [25, 27]]) + + assert jnp.all(output.array == answer) + + # test batch axes + B = hax.Axis("B", 2) + x = haliax.stack(B, [x, x]) + + output = mean_pool((hax.Axis("H", 1), hax.Axis("W", 3)), x, stride=2) + answer = jnp.array([[[1, 3], [13, 15], [25, 27]], [[1, 3], [13, 15], [25, 27]]]) + + assert jnp.all(output.array == answer) + + +def test_mean_pool3d(): + _x = jnp.arange(64).reshape(4, 4, 4) + x = hax.named(_x, ("H", "W", "D")) + output = mean_pool((hax.Axis("H", 1), hax.Axis("W", 3), hax.Axis("D", 1)), x, stride=2) + + answer = jnp.array([[[4, 6]], [[36, 38]]]) + + assert jnp.all(output.array == answer) + + +def test_pool_backprop(): + def max_pool_mean(x): + pooled = max_pool( + (hax.Axis("H", 2), hax.Axis("W", 2), hax.Axis("D", 2)), x, stride=1, padding=((0, 1), (0, 1), (0, 1)) + ) + return hax.mean(pooled).scalar() + + _x = jnp.arange(64, dtype=jnp.float32).reshape(1, 4, 4, 4) + x = hax.named(_x, ("B", "H", "W", "D")) + grad_fn = jax.value_and_grad(max_pool_mean) + + hax_loss, hax_grad = grad_fn(x) + + # compare it to eqx + + eqx_max_pool = eqx.nn.MaxPool3d(2, (1, 1, 1), padding=((0, 1), (0, 1), (0, 1))) + + def eqx_max_pool_mean(x): + pooled = eqx_max_pool(x) + return pooled.mean() + + eqx_grad_fn = jax.value_and_grad(eqx_max_pool_mean) + eqx_loss, eqx_grad = eqx_grad_fn(_x) + + assert jnp.allclose(hax_loss, eqx_loss) + assert jnp.allclose(hax_grad.array, eqx_grad) commit 0a6ecb2ddb27b24b62d8d46ffed25be5bdb6018f Date: 2023-12-20T21:39:23-08:00 switch to always replicating scalars diff --git a/src/haliax/partitioning.py b/src/haliax/partitioning.py index 8e64627..913171e 100644 --- a/src/haliax/partitioning.py +++ b/src/haliax/partitioning.py @@ -209,12 +209,12 @@ def infer_resource_partitions( elif is_jax_array_like(node): sharding = getattr(node, "sharding", None) # TODO: these are usually replicated. Is there a better way to tell? - if isinstance(sharding, SingleDeviceSharding): + if node.shape == (): + return NamedSharding(mesh, PartitionSpec()) + elif isinstance(sharding, SingleDeviceSharding): return NamedSharding(mesh, PartitionSpec(None)) elif sharding is not None: return sharding - elif node.shape == (): - return NamedSharding(mesh, PartitionSpec()) # elif use_auto_sharding: # TODO: auto doesn't seem to really work reliably yet # compat between 0.4.10 and 0.4.11 commit 6c6709a9aafc79ee6318af89d4644703609a98ca Date: 2023-12-22T12:33:35-08:00 looks we can remove the last reference to pjit now diff --git a/src/haliax/partitioning.py b/src/haliax/partitioning.py index 913171e..2f168b2 100644 --- a/src/haliax/partitioning.py +++ b/src/haliax/partitioning.py @@ -14,7 +14,6 @@ from equinox import module_update_wrapper from equinox._compile_utils import compile_cache # from jax._src.sharding_impls import AUTO -from jax.experimental.pjit import pjit from jax.lax import with_sharding_constraint from jax.sharding import Mesh, NamedSharding, PartitionSpec, SingleDeviceSharding from jaxtyping import PyTree @@ -497,7 +496,7 @@ def _named_pjit_cache(fun_names, **jitkwargs) -> WrappedCallable: jitkwargs["out_shardings"] = (out_shardings, None) # TODO: jit should work here, but there's a weird error. see if it goes away on its own - return pjit( + return jax.jit( fun_wrapped, donate_argnums=0, static_argnums=2, commit f9b03b5c0dbbde0464d77bad63d36aa398ad3b80 Date: 2024-01-21T13:43:55-08:00 add htu.tree_map etc (#59) * add htu.tree_map etc * oops diff --git a/.flake8 b/.flake8 index d067c43..42be999 100644 --- a/.flake8 +++ b/.flake8 @@ -1,7 +1,7 @@ [flake8] exclude = .git max-line-length = 120 -ignore = E203, E501, W503, W605, F821, E266 +ignore = E203, E501, W503, W605, F821, E266, E402, E731, F401, F403, F40 per-file-ignores = */__init__.py: F401 examples/*.py: E402 diff --git a/src/haliax/hof.py b/src/haliax/hof.py index 1fb3d67..f90ef7c 100644 --- a/src/haliax/hof.py +++ b/src/haliax/hof.py @@ -1,13 +1,16 @@ import dataclasses import inspect from functools import wraps -from typing import Any, Callable, Tuple, TypeVar, Union +from typing import Any, Callable, ParamSpec, Protocol, Tuple, TypeVar, Union, overload import equinox as eqx import jax import jax.lax as lax from jaxtyping import PyTree +import haliax +import haliax.tree_util as htu + from ._src.util import index_where from .axis import Axis, AxisSelector, selects_axis from .core import NamedArray @@ -18,20 +21,56 @@ from .util import is_jax_or_hax_array_like, is_named_array BoolAxisSpec = Union[bool, Callable[[Any], bool]] Carry = TypeVar("Carry") -X = TypeVar("X") -Y = TypeVar("Y") +X = TypeVar("X", contravariant=True) +Y = TypeVar("Y", covariant=True) +Args = ParamSpec("Args") + + +def is_named_or_shaped_array_like(x): + return (is_jax_array_like(x) and x.ndim >= 1) or is_named_array(x) + + +class ScanFn(Protocol[Carry, Args, Y]): + """ """ + def __call__(self, carry: Carry, *args: Args.args, **kwargs: Args.kwargs) -> Tuple[Carry, Y]: + ... + +@overload def scan( f: Callable[[Carry, X], Tuple[Carry, Y]], axis: AxisSelector, *, + reverse: bool = False, + unroll: int = 1, + is_scanned: BoolAxisSpec = is_named_or_shaped_array_like, +) -> Callable[[Carry, PyTree[X]], Tuple[Carry, PyTree[Y]]]: + ... + + +@overload +def scan( + f: Callable, + axis: AxisSelector, + *, + reverse: bool = False, + unroll: int = 1, + is_scanned: BoolAxisSpec = is_named_or_shaped_array_like, +) -> Callable: + ... + + +def scan( + f: Callable, # : ScanFn[Carry, Args, Y], This confuses mypy too much + axis: AxisSelector, + *, reverse=False, unroll=1, - is_scanned: BoolAxisSpec = is_jax_or_hax_array_like, + is_scanned: BoolAxisSpec = is_named_or_shaped_array_like, ): """ - Scan over a named axis. Arrays that are not part of a NamedArray will have their 0th dim scanned over + Scan over a named axis. Non-scalar unnamed arrays will have their first axis scanned over. Unlike [jax.lax.scan][], this function is curried: it takes the function, axis, and configuration arguments first, and then the initial carry and then any arguments to scan over as a separate curried function call. @@ -47,6 +86,10 @@ def scan( False otherwise. Behaves similarly to the `default` argument in filter_jit """ + if isinstance(is_scanned, bool): + q = is_scanned # this is to make mypy happy + is_scanned = lambda _: q + def is_scanned_with_axis(leaf): if is_named_array(leaf): return selects_axis(leaf.axes, axis) and is_scanned(leaf) @@ -67,10 +110,11 @@ def scan( # We have to be careful that we don't try to create NamedArrays that have the shape of the scanned result # but don't yet have the scanned axis as ones of `axes`, so we use _ScannedArrayResult that doesn't check # invariants until we're ready to create the result. - axis_first_xs = jax.tree_util.tree_map(_ensure_first(axis), scanned_xs, is_leaf=is_named_array) + axis_first_xs = htu.tree_map(_ensure_first(axis), scanned_xs) # now get a template of an element of "X" - x_elem = jax.tree_util.tree_map(_select_0th(axis), axis_first_xs, is_leaf=is_named_array) + x_elem = htu.tree_map(_select_0th(axis), axis_first_xs) + # NB: we don't want to use htu.tree_structure here because we want to eliminate the leading axis x_elem_structure = jax.tree_util.tree_structure(x_elem) # now we can fold over the axis @@ -81,11 +125,13 @@ def scan( scanned_x = eqx.combine(scanned_x, unscanned_xs, is_leaf=is_named_array) args, kwargs = scanned_x carry, y = f(carry, *args, **kwargs) - y = jax.tree_util.tree_map(_pacify_named_arrays, y, is_leaf=is_named_array) + y = htu.tree_map(_pacify_named_arrays, y) return carry, y + # as above, we don't want to use htu.tree_leaves here because we want to eliminate the leading axis leaves = jax.tree_util.tree_leaves(axis_first_xs) - carry, ys = lax.scan(wrapped_fn, init, leaves, reverse=reverse, unroll=unroll) + with jax.named_scope(f"scan({haliax.axis_name(axis)})"): + carry, ys = lax.scan(wrapped_fn, init, leaves, reverse=reverse, unroll=unroll) true_axis = _infer_axis_size_from_result(ys, axis) ys = jax.tree_util.tree_map(_prepend_named_batch_axis(true_axis), ys, is_leaf=_is_passive_array) @@ -94,6 +140,7 @@ def scan( return scanned_f +@overload def fold( fn: Callable[[Carry, X], Carry], axis: AxisSelector, @@ -101,13 +148,39 @@ def fold( reverse: bool = False, unroll: int = 1, is_scanned: BoolAxisSpec = is_jax_or_hax_array_like, -) -> Callable[[Carry, PyTree], Carry]: +) -> Callable[[Carry, PyTree[X]], Carry]: + ... + + +@overload +def fold( + fn: Callable, + axis: AxisSelector, + *, + reverse: bool = False, + unroll: int = 1, + is_scanned: BoolAxisSpec = is_jax_or_hax_array_like, +) -> Callable: + ... + + +def fold( + fn: Callable, + axis: AxisSelector, + *, + reverse: bool = False, + unroll: int = 1, + is_scanned: BoolAxisSpec = is_named_or_shaped_array_like, +) -> Callable: """ Slightly simpler implementation of scan that folds over the named axis of the array, not returning intermediates. As with scan, this function is curried: it takes the function, axis, and configuration arguments first, and then the initial carry and then any arguments to scan over as a separate curried function call. + Unnamed arrays will have their first axis scanned over, unless they are scalars, in which case they will be passed + through unchanged. + Args: fn: function to reduce over axis: axis to reduce over @@ -246,18 +319,14 @@ def vmap( padded_spec_args = broadcast_prefix(padded_spec_args, actual_bound.args, is_leaf=is_named_array) padded_spec_kwargs = broadcast_prefix(padded_spec_kwargs, actual_bound.kwargs) - arg_axis_specs = jax.tree_util.tree_map( - _index_of_batch_axis, actual_bound.args, padded_spec_args, is_leaf=is_named_array - ) + arg_axis_specs = htu.tree_map(_index_of_batch_axis, actual_bound.args, padded_spec_args) - kwarg_axis_specs = jax.tree_util.tree_map( - _index_of_batch_axis, actual_bound.kwargs, padded_spec_kwargs, is_leaf=is_named_array - ) + kwarg_axis_specs = htu.tree_map(_index_of_batch_axis, actual_bound.kwargs, padded_spec_kwargs) # now we can actually vmap. We used "pacified" versions of NamedArrays that don't check # invariants, because intermediates creating during tracing won't have the axes right - arg_axis_specs = jax.tree_util.tree_map(_pacify_named_arrays, arg_axis_specs, is_leaf=is_named_array) - kwarg_axis_specs = jax.tree_util.tree_map(_pacify_named_arrays, kwarg_axis_specs, is_leaf=is_named_array) + arg_axis_specs = htu.tree_map(_pacify_named_arrays, arg_axis_specs) + kwarg_axis_specs = htu.tree_map(_pacify_named_arrays, kwarg_axis_specs) def wrapped_fn(args, kwargs): # the args that come in here are pacified. Their names will still have the batch axis even though the array @@ -270,14 +339,14 @@ def vmap( out = fn(*unchilled_args, **unchilled_kwargs) # now we need to pacify the output, which may include NamedArrays, and add the batch axis back at the end - chilled = jax.tree_util.tree_map(_pacify_named_arrays, out, is_leaf=is_named_array) + chilled = htu.tree_map(_pacify_named_arrays, out) arrays, nonarrays = eqx.partition(chilled, is_jax_array_like) return arrays, Static(nonarrays) spmd_axis_name = physical_axis_name(axis) - args = jax.tree_util.tree_map(_pacify_named_arrays, actual_bound.args, is_leaf=is_named_array) - kwargs = jax.tree_util.tree_map(_pacify_named_arrays, actual_bound.kwargs, is_leaf=is_named_array) + args = htu.tree_map(_pacify_named_arrays, actual_bound.args) + kwargs = htu.tree_map(_pacify_named_arrays, actual_bound.kwargs) result_dynamic, result_static = jax.vmap( wrapped_fn, diff --git a/src/haliax/partitioning.py b/src/haliax/partitioning.py index 2f168b2..c4ecdd3 100644 --- a/src/haliax/partitioning.py +++ b/src/haliax/partitioning.py @@ -18,6 +18,8 @@ from jax.lax import with_sharding_constraint from jax.sharding import Mesh, NamedSharding, PartitionSpec, SingleDeviceSharding from jaxtyping import PyTree +import haliax.tree_util as htu + from .axis import Axis, AxisSelection, AxisSelector from .core import NamedArray from .jax_utils import Static, is_in_jit, is_jax_array_like @@ -152,7 +154,7 @@ def shard(x: T, mapping: Optional[ResourceMapping] = None, mesh: Optional[Mesh] raw_x = jax.make_array_from_callback(shape, desired_sharding, lambda index: raw_x[index]) return NamedArray(raw_x, x.axes) - return jax.tree_util.tree_map(_do_device_put, x, is_leaf=is_named_array) + return htu.tree_map(_do_device_put, x) @functools.wraps(shard) @@ -225,7 +227,7 @@ def infer_resource_partitions( else: return None - return jax.tree_util.tree_map(partition_spec, tree, is_leaf=is_named_array) + return htu.tree_map(partition_spec, tree) class WrappedCallable(typing.Protocol[Args, R]): diff --git a/src/haliax/tree_util.py b/src/haliax/tree_util.py index 8f210fa..31b1ec0 100644 --- a/src/haliax/tree_util.py +++ b/src/haliax/tree_util.py @@ -11,6 +11,61 @@ from .jax_utils import maybe_rng_split from .util import is_named_array +def tree_map(fn, tree, *rest, is_leaf=None): + """ + Version of [jax.tree_util.tree_map][] that automatically treats NamedArrays as leaves. + """ + if is_leaf is None: + is_leaf = lambda x: isinstance(x, NamedArray) + else: + is_leaf = lambda x: is_leaf(x) or is_named_array(x) + + return jax.tree_util.tree_map(fn, tree, *rest, is_leaf=is_leaf) + + +def tree_flatten(tree, is_leaf=None): + """ + Version of [jax.tree_util.tree_flatten][] that automatically treats NamedArrays as leaves. + """ + if is_leaf is None: + is_leaf = lambda x: isinstance(x, NamedArray) + else: + is_leaf = lambda x: is_leaf(x) or is_named_array(x) + + return jax.tree_util.tree_flatten(tree, is_leaf=is_leaf) + + +def tree_unflatten(treedef, leaves): + """ + Provided for consistency with tree_flatten. + """ + return jax.tree_util.tree_unflatten(treedef, leaves) + + +def tree_leaves(tree, is_leaf=None): + """ + Version of [jax.tree_util.tree_leaves][] that automatically treats NamedArrays as leaves. + """ + if is_leaf is None: + is_leaf = lambda x: isinstance(x, NamedArray) + else: + is_leaf = lambda x: is_leaf(x) or is_named_array(x) + + return jax.tree_util.tree_leaves(tree, is_leaf=is_leaf) + + +def tree_structure(tree, is_leaf=None): + """ + Version of [jax.tree_util.tree_structure][] that automatically treats NamedArrays as leaves. + """ + if is_leaf is None: + is_leaf = lambda x: isinstance(x, NamedArray) + else: + is_leaf = lambda x: is_leaf(x) or is_named_array(x) + + return jax.tree_util.tree_structure(tree, is_leaf=is_leaf) + + def resize_axis(tree: PyTree[NamedArray], old_axis: AxisSelector, new_size: int, key: Optional[PRNGKeyArray] = None): """Resizes the NamedArrays of a PyTree along a given axis. If the array needs to grow and key is not none, then the new elements are sampled from a truncated normal distribution with the same mean and standard deviation as the commit ae5f4ce74a429a9ae45e350099f2ecc0cd95004c Date: 2024-01-24T20:47:22-08:00 top_k now returns indices in addition to values (#61) diff --git a/src/haliax/specialized_fns.py b/src/haliax/specialized_fns.py index 263ed37..709d1ab 100644 --- a/src/haliax/specialized_fns.py +++ b/src/haliax/specialized_fns.py @@ -1,4 +1,4 @@ -from typing import Optional +from typing import Optional, Tuple import jax import jax.numpy as jnp @@ -7,7 +7,9 @@ from .axis import Axis, AxisSelector from .core import NamedArray -def top_k(arr: NamedArray, axis: AxisSelector, k: int, new_axis: Optional[AxisSelector] = None) -> NamedArray: +def top_k( + arr: NamedArray, axis: AxisSelector, k: int, new_axis: Optional[AxisSelector] = None +) -> Tuple[NamedArray, NamedArray]: """ Select the top k elements along the given axis. Args: @@ -18,13 +20,15 @@ def top_k(arr: NamedArray, axis: AxisSelector, k: int, new_axis: Optional[AxisSe Returns: NamedArray: array with the top k elements along the given axis + NamedArray: array with the top k elements' indices along the given axis """ pos = arr._lookup_indices(axis) if pos is None: raise ValueError(f"Axis {axis} not found in {arr}") new_array = jnp.moveaxis(arr.array, pos, -1) # move axis to the last position - values, _ = jax.lax.top_k(new_array, k=k) + values, indices = jax.lax.top_k(new_array, k=k) values = jnp.moveaxis(values, -1, pos) # move axis back to its original position + indices = jnp.moveaxis(indices, -1, pos) if new_axis is None: axis = arr.resolve_axis(axis) @@ -33,4 +37,4 @@ def top_k(arr: NamedArray, axis: AxisSelector, k: int, new_axis: Optional[AxisSe new_axis = Axis(new_axis, k) updated_axes = arr.axes[:pos] + (new_axis,) + arr.axes[pos + 1 :] - return NamedArray(values, updated_axes) + return NamedArray(values, updated_axes), NamedArray(indices, updated_axes) diff --git a/tests/test_specialized_fns.py b/tests/test_specialized_fns.py index 0e9c5a3..dbc1449 100644 --- a/tests/test_specialized_fns.py +++ b/tests/test_specialized_fns.py @@ -13,13 +13,21 @@ def test_top_k(): rand = jax.random.uniform(jax.random.PRNGKey(0), (H.size, W.size, D.size)) n_rand = NamedArray(rand, (H, W, D)) - assert hfns.top_k(n_rand, D, 2).array.shape == (H.size, W.size, 2) + values, indices = hfns.top_k(n_rand, D, 2) + + assert values.array.shape == (H.size, W.size, 2) + assert indices.array.shape == (H.size, W.size, 2) assert jnp.all( - jnp.equal(jax.lax.top_k(rand, 2)[0], hfns.top_k(n_rand, D, 2).array) + jnp.equal(jax.lax.top_k(rand, 2)[0], values.array) ) # test that selecting last axis is same as default + assert jnp.all( + jnp.equal(jnp.moveaxis(n_rand.take(D, indices).array, 0, -1), values.array) + ) # test that indexing using indices is same as selected values for idx, i in enumerate(n_rand.axes): # then test selecting all axes t = jnp.transpose(rand, (*range(idx), *range(idx + 1, len(n_rand.axes)), idx)) t = jax.lax.top_k(t, 2)[0] t = jnp.moveaxis(t, -1, idx) - assert jnp.all(jnp.equal(t, hfns.top_k(n_rand, i, 2).array)) + values, indices = hfns.top_k(n_rand, i, 2) + assert jnp.all(jnp.equal(t, values.array)) + assert jnp.all(jnp.equal(jnp.moveaxis(n_rand.take(i, indices).array, 0, idx), values.array)) commit c7e0fc438c6ccfa3680ee5a096db101c60d51d21 Date: 2024-02-13T21:07:29-08:00 Add single argument mode for hax.where (#69) * add single argument mode for hax.where * type check fix * Update src/haliax/ops.py Co-authored-by: David Hall <dlwh@cs.stanford.edu> --------- Co-authored-by: David Hall <dlwh@cs.stanford.edu> diff --git a/src/haliax/core.py b/src/haliax/core.py index 6cf5eca..b403e48 100644 --- a/src/haliax/core.py +++ b/src/haliax/core.py @@ -518,7 +518,7 @@ class NamedArray: # types when they're in PyTrees if self.array is None: return other.array is None - if other.array is None: + if hasattr(other, "array") and other.array is None: return False return haliax.equal(self, other) diff --git a/src/haliax/ops.py b/src/haliax/ops.py index 66b3d89..8a1c061 100644 --- a/src/haliax/ops.py +++ b/src/haliax/ops.py @@ -1,4 +1,4 @@ -from typing import Union +from typing import Optional, Union import jax import jax.numpy as jnp @@ -26,12 +26,28 @@ def trace(array: NamedArray, axis1: AxisSelector, axis2: AxisSelector, offset=0, return NamedArray(inner, axes) -def where(condition: Union[NamedOrNumeric, bool], x: NamedOrNumeric, y: NamedOrNumeric) -> NamedArray: - """Like jnp.where, but with named axes. This version currently only accepts the three argument form.""" - - # TODO: support the one argument form - # if (x is None) != (y is None): - # raise ValueError("Must either specify both x and y, or neither") +def where( + condition: Union[NamedOrNumeric, bool], + x: NamedOrNumeric = None, + y: NamedOrNumeric = None, + fill_value: Optional[int] = None, + new_axis: Optional[Axis] = None, +) -> NamedArray | tuple[NamedArray, ...]: + """Like jnp.where, but with named axes.""" + + if (x is None) != (y is None): + raise ValueError("Must either specify both x and y, or neither") + + # one argument form + if (x is None) and (y is None): + if not isinstance(condition, NamedArray): + raise ValueError(f"condition {condition} must be a NamedArray in single argument mode") + if fill_value is None or new_axis is None: + raise ValueError("Must specify both fill_value and new_axis") + return tuple( + NamedArray(idx, (new_axis,)) + for idx in jnp.where(condition.array, size=new_axis.size, fill_value=fill_value) + ) if jnp.isscalar(condition): if x is None: diff --git a/tests/test_ops.py b/tests/test_ops.py index 5563d65..27f4778 100644 --- a/tests/test_ops.py +++ b/tests/test_ops.py @@ -136,6 +136,12 @@ def test_where(): with pytest.raises(ValueError): _ = hax.where(named5 > named6, named5, named6) + # now single argument mode + Volume = hax.Axis("Volume", Height.size * Width.size * Depth.size) + named7 = hax.random.uniform(PRNGKey(0), (Height, Width, Depth)) + named8, named9, named10 = hax.where(named7 > 0.5, fill_value=-1, new_axis=Volume) + assert jnp.all((named7[{"Height": named8, "Width": named9, "Depth": named10}] > 0.5).array) + def test_clip(): Height = Axis("Height", 10) commit 690623131e107972ec2ec67d6183c77649d4b7e0 Date: 2024-02-13T22:05:00-08:00 Don't check shapes in tree_unflatten. Fixes #66 (#68) diff --git a/src/haliax/core.py b/src/haliax/core.py index b403e48..127d45b 100644 --- a/src/haliax/core.py +++ b/src/haliax/core.py @@ -128,7 +128,10 @@ class NamedArray: @classmethod def tree_unflatten(cls, aux, tree: Any) -> Any: assert len(tree) == 1 - return cls(tree[0], axes=aux) + # We don't want check shapes b/c there are intermediate states where the shape is wrong + # e.g. in eqxi.while_loop + with enable_shape_checks(False): + return cls(tree[0], axes=aux) def has_axis(self, axis: AxisSelection) -> bool: """Returns true if the given axis is present in this NamedArray.""" diff --git a/tests/core_test.py b/tests/core_test.py index eac2958..00e4c26 100644 --- a/tests/core_test.py +++ b/tests/core_test.py @@ -795,3 +795,28 @@ def test_nice_short_string_in_named_array_in_eqx_module(): mod = TestModule(named1) assert str(mod).startswith("TestModule(named1=Named(int32{'H': 10, 'W': 20}))") + + +def test_named_arrays_work_in_eqxi_while_loop(): + H = Axis("H", 10) + W = Axis("W", 20) + + named1 = hax.random.uniform(PRNGKey(0), (H, W)) + + import equinox.internal as eqxi + + def body_fun(t): + i, named1 = t + return i + 1, named1 + named1 + + def cond_fun(t): + i, named1 = t + return i < 10 + + def loss_fun(named1): + i, named1 = eqxi.while_loop(cond_fun, body_fun, (0, named1), kind="checkpointed", max_steps=10) + return named1.sum().scalar() + + grad_fun = eqx.filter_value_and_grad(loss_fun) + + grad_fun(named1) commit 83ab30484cb7f2fd02332f7f0179d799edabed39 Date: 2024-02-29T22:28:16-08:00 tile and repeat (#71) * tile and repeat * port over a change from dev diff --git a/src/haliax/__init__.py b/src/haliax/__init__.py index a7efeac..d2678ce 100644 --- a/src/haliax/__init__.py +++ b/src/haliax/__init__.py @@ -169,6 +169,47 @@ def stack(axis: AxisSelector, arrays: Sequence[NamedArray]) -> NamedArray: return NamedArray(jnp.stack([a.array for a in arrays], axis=0), (axis,) + arrays[0].axes) +def repeat( + a: NamedArray, repeats: int | jnp.ndarray, axis: AxisSelector, total_repeat_length: Optional[int] = None +) -> NamedArray: + """Version of [jax.numpy.repeat][] that returns a NamedArray""" + index = a._lookup_indices(axis) + if index is None: + raise ValueError(f"Axis {axis} not found in array {a}") + + return named( + jnp.repeat(a.array, repeats, axis=index, total_repeat_length=total_repeat_length), + a.axes[:index] + (axis_name(axis),) + a.axes[index + 1 :], + ) + + +def tile(a: NamedArray, reps: dict[AxisSelector, int]) -> NamedArray: + """ + Version of [jax.numpy.tile][] that returns a NamedArray. + + As with the non-named tile, you can add new axes by passing a dict with an axis name as the key + and the number of reps as the value. The size of the axis (if it exists) will be ignored for new dims. + That is, the size of the resulting axis will be the number of reps for a new axis, and the size of the + original axis times the number of reps for an existing axis. + """ + # we need to convert the reps to a sequence of ints + new_dims = [] + dim_reps = [1] * len(a.axes) + for ax, i in reps.items(): + index = a._lookup_indices(ax) + if index is None: + new_dims.append(Axis(axis_name(ax), i)) + else: + dim_reps[index] = i + + if len(new_dims) > 0: + dim_reps = [ax.size for ax in new_dims] + dim_reps + + out_axes = tuple(new_dims) + tuple(ax.name for ax in a.axes) + + return named(jnp.tile(a.array, dim_reps), out_axes) + + def concatenate(axis: AxisSelector, arrays: Sequence[NamedArray]) -> NamedArray: """Version of [jax.numpy.concatenate][] that returns a NamedArray. The returns array will have the same axis names in the same order as the first, with the selected axis extended by the sum of the sizes of the selected axes in the diff --git a/src/haliax/core.py b/src/haliax/core.py index 127d45b..e5f45b5 100644 --- a/src/haliax/core.py +++ b/src/haliax/core.py @@ -1214,6 +1214,7 @@ def flatten(array: NamedArray, new_axis_name: AxisSelector) -> NamedArray: def named(a: jnp.ndarray, axis: AxisSelection) -> NamedArray: """Creates a NamedArray from a numpy array and a list of axes.""" + a = jnp.asarray(a) axes = check_shape(a.shape, axis) return NamedArray(a, axes) diff --git a/src/haliax/jax_utils.py b/src/haliax/jax_utils.py index 7856b25..cf510c9 100644 --- a/src/haliax/jax_utils.py +++ b/src/haliax/jax_utils.py @@ -9,6 +9,8 @@ from jax import numpy as jnp from jax import random as jrandom from jaxtyping import PRNGKeyArray +import haliax + F = typing.TypeVar("F", bound=Callable[..., Any]) @@ -140,3 +142,10 @@ def is_pallas_dslice(x: object) -> bool: _PALLAS_DSLICE_TYPE = type(pdslice(0, 1)) return isinstance(x, _PALLAS_DSLICE_TYPE) + + +def is_scalarish(x): + if isinstance(x, haliax.NamedArray): + return x.ndim == 0 + else: + return jnp.isscalar(x) or x.shape == () diff --git a/src/haliax/ops.py b/src/haliax/ops.py index 8a1c061..da92654 100644 --- a/src/haliax/ops.py +++ b/src/haliax/ops.py @@ -1,3 +1,4 @@ +import typing from typing import Optional, Union import jax @@ -5,6 +6,7 @@ import jax.numpy as jnp from .axis import Axis, AxisSelector from .core import NamedArray, NamedOrNumeric, broadcast_arrays, broadcast_arrays_and_return_axes +from .jax_utils import is_scalarish def trace(array: NamedArray, axis1: AxisSelector, axis2: AxisSelector, offset=0, dtype=None) -> NamedArray: @@ -26,10 +28,29 @@ def trace(array: NamedArray, axis1: AxisSelector, axis2: AxisSelector, offset=0, return NamedArray(inner, axes) +@typing.overload +def where( + condition: NamedOrNumeric | bool, + x: NamedOrNumeric, + y: NamedOrNumeric, +) -> NamedArray: + ... + + +@typing.overload +def where( + condition: NamedArray, + *, + fill_value: int, + new_axis: Axis, +) -> tuple[NamedArray, ...]: + ... + + def where( condition: Union[NamedOrNumeric, bool], - x: NamedOrNumeric = None, - y: NamedOrNumeric = None, + x: Optional[NamedOrNumeric] = None, + y: Optional[NamedOrNumeric] = None, fill_value: Optional[int] = None, new_axis: Optional[Axis] = None, ) -> NamedArray | tuple[NamedArray, ...]: @@ -49,25 +70,22 @@ def where( for idx in jnp.where(condition.array, size=new_axis.size, fill_value=fill_value) ) - if jnp.isscalar(condition): + if is_scalarish(condition): if x is None: raise ValueError("Must specify x and y when condition is a scalar") return jax.lax.cond(condition, lambda _: x, lambda _: y, None) - assert isinstance(condition, NamedArray) - - if jnp.isscalar(x): - x = NamedArray(jnp.broadcast_to(x, condition.array.shape), condition.axes) - - assert isinstance(x, NamedArray) + condition, x, y = broadcast_arrays(condition, x, y) # type: ignore - if jnp.isscalar(y): - y = NamedArray(jnp.broadcast_to(y, condition.array.shape), condition.axes) + assert isinstance(condition, NamedArray) - assert isinstance(y, NamedArray) + def _array_if_named(x): + if isinstance(x, NamedArray): + return x.array + return x - condition, x, y = broadcast_arrays(condition, x, y) # type: ignore - return NamedArray(jnp.where(condition.array, x.array, y.array), condition.axes) + raw = jnp.where(condition.array, _array_if_named(x), _array_if_named(y)) + return NamedArray(raw, condition.axes) def clip(array: NamedOrNumeric, a_min: NamedOrNumeric, a_max: NamedOrNumeric) -> NamedArray: diff --git a/tests/core_test.py b/tests/core_test.py index 00e4c26..caa5f27 100644 --- a/tests/core_test.py +++ b/tests/core_test.py @@ -431,6 +431,85 @@ def test_concatenate(): assert hax.concatenate("H", (named1, named2)).axes == (W, Axis("H", 7)) +def test_repeat(): + # Test analogs to this numpy code: + # x = np.array([[1,2],[3,4]]) + # + # np.repeat(x, 3, axis=1) + # array([[1, 1, 1, 2, 2, 2], + # [3, 3, 3, 4, 4, 4]]) + # + # np.repeat(x, [1, 2], axis=0) + # array([[1, 2], + # [3, 4], + # [3, 4]]) + + H = Axis("H", 2) + W = Axis("W", 2) + + named1 = hax.named([[1, 2], [3, 4]], (H, W)) + + assert jnp.all(jnp.equal(hax.repeat(named1, 3, axis=W).array, jnp.repeat(named1.array, 3, axis=1))) + assert hax.repeat(named1, 3, axis=W).axes == (H, Axis("W", 6)) + + assert jnp.all( + jnp.equal( + hax.repeat(named1, jnp.array([1, 2]), axis=H).array, jnp.repeat(named1.array, jnp.array([1, 2]), axis=0) + ) + ) + assert hax.repeat(named1, jnp.array([1, 2]), axis=H).axes == (Axis("H", 3), W) + + +def test_tile(): + # a = np.array([0, 1, 2]) + # + # np.tile(a, 2) + # array([0, 1, 2, 0, 1, 2]) + # + # np.tile(a, (2, 2)) + # array([[0, 1, 2, 0, 1, 2], + # [0, 1, 2, 0, 1, 2]]) + # + # np.tile(a, (2, 1, 2)) + # array([[[0, 1, 2, 0, 1, 2]], + # [[0, 1, 2, 0, 1, 2]]]) + # + # b = np.array([[1, 2], [3, 4]]) + # + # np.tile(b, 2) + # array([[1, 2, 1, 2], + # [3, 4, 3, 4]]) + # + # np.tile(b, (2, 1)) + # array([[1, 2], + # [3, 4], + # [1, 2], + # [3, 4]]) + # + # c = np.array([1,2,3,4]) + # + # np.tile(c,(4,1)) + # array([[1, 2, 3, 4], + # [1, 2, 3, 4], + # [1, 2, 3, 4], + # [1, 2, 3, 4]]) + + named1 = hax.named([0, 1, 2], "H") + + assert jnp.all(jnp.equal(hax.tile(named1, {"H": 2}).array, jnp.tile(named1.array, 2))) + assert jnp.all(jnp.equal(hax.tile(named1, {"H": 2, "W": 1}).array, jnp.tile(named1.array, (1, 2)))) + + named2 = hax.named([[1, 2], [3, 4]], ("H", "W")) + + assert jnp.all(jnp.equal(hax.tile(named2, {"H": 2}).array, jnp.tile(named2.array, (2, 1)))) + assert jnp.all(jnp.equal(hax.tile(named2, {"H": 2, "W": 1}).array, jnp.tile(named2.array, (2, 1)))) + + named3 = hax.named([1, 2, 3, 4], "H") + + assert jnp.all(jnp.equal(hax.tile(named3, {"H": 4, "W": 1}).array, jnp.tile(named3.array, (1, 4)))) + assert jnp.all(jnp.equal(hax.tile(named3, {"H": 4, "W": 1, "D": 1}).array, jnp.tile(named3.array, (1, 1, 4)))) + + def test_unflatten_axis(): H = Axis("Height", 2) W = Axis("Width", 3) commit f1be33d54915c824bde86bdf34ad9eda7c7eb5db Date: 2024-03-04T16:05:51-08:00 Dev (#55) * actually make sum etc return jnp.ndarray when None is provided * no cover * remove the coverage pragmas and just automatically exclude typing.overload * fix signature for ReductionFunction * cleanup typing.overloads * refactor dot to support None * make precommit stricter, please mypy * use auto_sharded internally, undeprecate it b/c it has a point * refactor dot to take a keyword argument for axis instead of it being a leading argument * fix some deprecation warnings * move dot to its own file * add support for out_axes to `dot` * add docs for the new dot * move rearrange_to_fit_order to axis * make "old-style" rearrange accept multiple ellipses * add support for multiple ellipsis to einops-style rearrange * try to fix dtypelike for older jax versions * missed a spot * remove old scalar thing from docs * allow AxisSpec for Embed in Embedding * copy in Equinox compile cache so Patrick isn't disappointed in me * use named arrays for the where check * let `named` work with anything asarray likes * catch some some dumb oversights in calling sharding * simplify handling of non-named arrays in binary ops * move losses to their own file, add binary cross entropy loss * less coverage noise * autocoerce scalar named arrays to plain jax arrays * don't reduce losses when reduction axis == () * on second thought, less magic in the Haliax API is probably better * on second thought, less magic in the Haliax API is probably better * minimize use of jax internals * make it so we don't scan scalars, which will be nicer * older jax doesn't expose DTypeLike * log the name that's being scanned * parens seem more normal * change default prevent_cse to False for Stacked * Adds a new einsum syntax (#63) Adds a new einsum syntax to Haliax that has three modes: "ordered", "unordered", and "output only". * Ordered looks like normal (einops-flavored) einsum * unordered uses syntax similar to rearrange: specify the names of axes involved in the operation, others are batched. * output only lets you specify only the expected output shape. use judiciously. * add a method for flattening all "batch" axes into a single batch axis, which is useful in a few situations diff --git a/.coveragerc b/.coveragerc new file mode 100644 index 0000000..16405cc --- /dev/null +++ b/.coveragerc @@ -0,0 +1,8 @@ +[report] +exclude_lines = + pragma: not covered + pragma: no cover + @overload + @typing.overload + @abc.abstractmethod + raise NotImplementedError diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml index 7a18c75..dc590d0 100644 --- a/.pre-commit-config.yaml +++ b/.pre-commit-config.yaml @@ -36,4 +36,4 @@ repos: rev: 'v1.5.1' hooks: - id: mypy - args: [--ignore-missing-imports] + args: [--ignore-missing-imports, --check-untyped-defs] diff --git a/README.md b/README.md index 070791f..9a700f9 100644 --- a/README.md +++ b/README.md @@ -52,7 +52,7 @@ Embed = hax.Axis("embed", 512) # embedding size def attention_scores(Key, KPos, query, key, mask): # how similar is each query to each key - scores = hax.dot(Key, query, key) / jnp.sqrt(Key.size) + scores = hax.dot(query, key, axis=Key) / jnp.sqrt(Key.size) if mask is not None: scores -= 1E9 * (1.0 - mask) @@ -64,7 +64,7 @@ def attention_scores(Key, KPos, query, key, mask): def attention(Key, KPos, query, key, value, mask): scores = attention_scores(Key, KPos, query, key, mask) - answers = hax.dot(KPos, scores, value) + answers = hax.dot(scores, value, axis=KPos) return answers diff --git a/docs/api.md b/docs/api.md index a3b9cdb..1886a8d 100644 --- a/docs/api.md +++ b/docs/api.md @@ -99,11 +99,14 @@ See also the section on [Indexing and Slicing](indexing.md). [Binary](#binary-operations) and [unary](#unary-operations) operations are all more or less directly from JAX's NumPy API. The only difference is they operate on named arrays instead. -## Matrix Multiplication +### Matrix Multiplication + +See also the page on [Matrix Multiplication](matmul.md) as well as the [cheat sheet section](cheatsheet.md#matrix-multiplication). ::: haliax.dot +::: haliax.einsum -### Reductions +## Reductions Reduction operations are things like [haliax.sum][] and [haliax.mean][] that reduce an array along one or more axes. Except for [haliax.argmin][] and [haliax.argmax][], they all have the form: @@ -113,11 +116,15 @@ def sum(x, axis: Optional[AxisSelection] = None, where: Optional[NamedArray] = N ... ``` -with the behavior closely mirroring that of JAX's NumPy API. The `axis` argument can +with the behavior closely following that of JAX's NumPy API. The `axis` argument can be a single axis (or axis name), a tuple of axes, or `None` to reduce all axes. The `where` argument is a boolean array that specifies which elements to include in the reduction. It must be broadcastable to the input array, using Haliax's [broadcasting rules](broadcasting.md). +The result of a reduction operation is always [haliax.NamedArray][] with the reduced axes removed. +If you reduce all axes, the result is a NamedArray with 0 axes, i.e. a scalar. +You can convert it to a [jax.numpy.ndarray][] with [haliax.NamedArray.scalar][], or just [haliax.NamedArray.array][]. + ::: haliax.all ::: haliax.amax ::: haliax.any @@ -132,7 +139,7 @@ Haliax's [broadcasting rules](broadcasting.md). ::: haliax.sum ::: haliax.var -### Axis-Wise Operations +### Axis-wise Operations Axis-wise operations are things like [haliax.cumsum][] and [haliax.sort][] that operate on a single axis of an array but don't reduce it. diff --git a/docs/cheatsheet.md b/docs/cheatsheet.md index 622fdf2..9329ed7 100644 --- a/docs/cheatsheet.md +++ b/docs/cheatsheet.md @@ -8,9 +8,8 @@ We're happy to add more examples if you have any that you think would be useful. Throughout we assume the following: -``` +```python import jax.numpy as jnp -import jax import haliax as hax @@ -18,10 +17,11 @@ Batch = hax.Axis("batch", 32) Embed = hax.Axis("embed", 64) H = hax.Axis("h", 16) W = hax.Axis("w", 16) +C = hax.Axis("c", 3) -Step = hax.axis("step", 2) -Mini = hax.axis("mini", 16) +Step = hax.Axis("step", 2) +Mini = hax.Axis("mini", 16) # for jax x = jnp.zeros((32, 64)) @@ -29,15 +29,17 @@ y = jnp.zeros((32, 64)) z = jnp.zeros((32,)) w = jnp.zeros((64,)) ind = jnp.arange((8,), dtype=jnp.int32) -im = jnp.zeros((32, 16, 16)) +im = jnp.zeros((32, 16, 16, 3)) +w2 = jnp.zeros((3, 64)) # for haliax x = hax.zeros((Batch, Embed)) y = hax.zeros((Batch, Embed)) z = hax.zeros((Batch,)) w = hax.zeros((Embed,)) -ind = hax.arange(Axis("Index", 8), dtype=jnp.int32) -im = hax.zeros((Batch, H, W)) +ind = hax.arange(hax.Axis("Index", 8), dtype=jnp.int32) +im = hax.zeros((Batch, H, W, C)) +w2 = hax.zeros((C, Embed)) ``` @@ -86,12 +88,12 @@ im = hax.zeros((Batch, H, W)) See also the section on [Rearrange](rearrange.md). -| JAX (with einops) | Haliax | -|-------------------------------------------------------------------------|--------------------------------------------------------------------------| +| JAX (with einops) | Haliax | +|--------------------------------------------------------------------------------------------|--------------------------------------------------------------------------| | [`einops.rearrange(x, "batch embed -> embed batch")`](https://einops.rocks/api/rearrange/) | [`hax.rearrange(x, ("embed", "batch"))`][haliax.rearrange] | | [`einops.rearrange(x, "batch embed -> embed batch")`](https://einops.rocks/api/rearrange/) | [`hax.rearrange(x, "b e -> e b")`][haliax.rearrange] | | [`einops.rearrange(im, "... h w -> ... (h w)")`](https://einops.rocks/api/rearrange/) | [`hax.flatten_axes(im, ("h", "w"), "hw")`][haliax.flatten_axes] | -| [`einops.rearrange(im, "... h w -> ... (h w)")`](https://einops.rocks/api/rearrange/) | [`hax.rearrange(im, "{h w} -> ... (embed: h w)")`][haliax.rearrange] | +| [`einops.rearrange(im, "... h w c -> ... (h w c)")`](https://einops.rocks/api/rearrange/) | [`hax.rearrange(im, "{h w c} -> ... (embed: h w c)")`][haliax.rearrange] | | [`einops.rearrange(x, "b (h w) -> b h w", h=8)`](https://einops.rocks/api/rearrange/) | [`hax.rearrange(x, "b (h w) -> b h w", h=8)`][haliax.rearrange] | | [`einops.rearrange(x, "b (h w) -> b h w", h=8)`](https://einops.rocks/api/rearrange/) | [`hax.rearrange(x, "{(embed: h w)} -> ... h w", h=8)`][haliax.rearrange] | @@ -151,9 +153,19 @@ Reductions are similar to JAX, except that they use an axis name instead of an a ### Matrix Multiplication -| JAX | Haliax | -|-----------------------------------------------------|----------------------------------------| -| [`jnp.dot(z, x)`][jax.numpy.dot] | [`hax.dot("batch", z, x)`][haliax.dot] | -| [`jnp.matmul(z, x)`][jax.numpy.matmul] | [`hax.dot("batch", z, x)`][haliax.dot] | -| [`jnp.dot(w, x.t)`][jax.numpy.dot] | [`hax.dot("embed", w, x)`][haliax.dot] | -| [`jnp.einsum("ij,j -> i", x, w)`][jax.numpy.einsum] | [`hax.dot("embed", x, w)`][haliax.dot] | +| JAX | Haliax | +|----------------------------------------------------------------|--------------------------------------------------------------------| +| [`jnp.dot(z, x)`][jax.numpy.dot] | [`hax.dot(z, x, axis="batch")`][haliax.dot] | +| [`jnp.matmul(z, x)`][jax.numpy.matmul] | [`hax.dot(z, x, axis="batch")`][haliax.dot] | +| [`jnp.dot(w, x.t)`][jax.numpy.dot] | [`hax.dot(w, x, axis="embed")`][haliax.dot] | +| [`jnp.einsum("ij,j -> i", x, w)`][jax.numpy.einsum] | [`hax.dot(x, w, axis="embed")`][haliax.dot] | +| [`jnp.einsum("i,ij,ij,j -> i", z, x, y, w)`][jax.numpy.einsum] | [`hax.dot(z, x, y, w, axis="embed")`][haliax.dot] | +| [`jnp.einsum("ij,j -> ji", x, w)`][jax.numpy.einsum] | [`hax.dot(x, w, axis=(), out_axes=("embed", "batch")`][haliax.dot] | +| [`jnp.einsum("bhwc,ce -> bhwe", im, w2)`][jax.numpy.einsum] | [`hax.einsum("b h w c, c e -> b h w e", im, w2)`][haliax.einsum] | +| [`jnp.einsum("...c,ce -> ...e", im, w2)`][jax.numpy.einsum] | [`hax.einsum("... c, c e -> ... e", im, w2)`][haliax.einsum] | +| [`jnp.einsum("bhwc,ce -> bhwe", im, w2)`][jax.numpy.einsum] | [`hax.einsum("{c embed} -> embed", im, w2)`][haliax.einsum] | +| [`jnp.einsum("bhwc,ce -> bhwe", im, w2)`][jax.numpy.einsum] | [`hax.einsum("-> batch h w embed", im, w2)`][haliax.einsum] | +| [`jnp.einsum("bhwc,ce -> bhwce", im, w2)`][jax.numpy.einsum] | [`hax.einsum("{...} -> ...", im, w2)`][haliax.einsum] | +| [`jnp.einsum("bhwc,ce -> ", im, w2)`][jax.numpy.einsum] | [`hax.einsum("{...} -> ", im, w2)`][haliax.einsum] | +| [`jnp.einsum("bhwc,ce -> bhwce", im, w2)`][jax.numpy.einsum] | [`hax.dot(im, w2, axis=())`][haliax.dot] | +| [`jnp.einsum("bhwc,ce -> ", im, w2)`][jax.numpy.einsum] | [`hax.dot(im, w2, axis=None)`][haliax.dot] | diff --git a/docs/indexing.md b/docs/indexing.md index dd31f7d..cd57b7b 100644 --- a/docs/indexing.md +++ b/docs/indexing.md @@ -90,7 +90,7 @@ q = hax.arange(N) def f(x, slice_size: int): num_blocks = N.size // slice_size def body(i, m): - return i + hax.mean(x["N", hax.dslice(i * slice_size, slice_size)]).scalar() + return i + hax.mean(x["N", hax.dslice(i * slice_size, slice_size)]) jax.lax.fori_loop(0, num_blocks, body, 0.0) f(q, 2) @@ -111,7 +111,7 @@ q = hax.arange(N) def f(x, slice_size: int): num_blocks = N.size // slice_size def body(i, m): - return i + hax.mean(x["N", hax.ds.block(i, slice_size)]).scalar() + return i + hax.mean(x["N", hax.ds.block(i, slice_size)]) jax.lax.fori_loop(0, num_blocks, body, 0.0) f(q, 2) diff --git a/docs/matmul.md b/docs/matmul.md new file mode 100644 index 0000000..6f7303e --- /dev/null +++ b/docs/matmul.md @@ -0,0 +1,144 @@ +## Matrix Multiplication + +Haliax has two ways to do matrix multiplication (and tensor contractions more generally): +[haliax.dot][] and [haliax.einsum][]. [haliax.dot][] and [haliax.einsum][] +can both express any tensor contraction, though in different situations one or the other may be +more suitable for expressing a particular contraction. + +See also the API reference for [haliax.dot][] and [haliax.einsum][] and the +[cheat sheet section](cheatsheet.md#matrix-multiplication). + +### `haliax.dot` + +With [haliax.dot][], you specify the axes to contract over, without needing to write out the +axes you want to keep (though you can if you want): + +```python +import haliax as hax + +H = hax.Axis("H", 3) +W = hax.Axis("W", 4) +D = hax.Axis("D", 5) + +x = hax.ones((H, W, D)) +w = hax.ones((D,)) +y = hax.dot(x, w, axis=D) # shape is (H, W), equivalent to np.einsum("hwd,d->hw", x, w) +``` + +[haliax.dot][] is at its best when you want to express a simple matrix multiplication over one or a few axes. +Syntactically, [haliax.dot][] is similar to reduction operations like [haliax.sum][] and [haliax.mean][]. + +The [cheat sheet](cheatsheet.md) has a section on [matrix multiplication](cheatsheet.md#matrix-multiplication) +that gives a few examples. Here are several more: + +```python +import haliax as hax + +H = hax.Axis("H", 3) +W = hax.Axis("W", 4) +D = hax.Axis("D", 5) +C = hax.Axis("C", 6) + +x = hax.arange((H, W, D, C)) +w = hax.arange((D, C)) +c = hax.arange((C,)) + +y = hax.dot(x, c, axis=C) # shape is (H, W, D), equivalent to jnp.dot(x, c) + +y = hax.dot(x, w, axis=(D, C)) # shape is (H, W), equivalent to np.einsum("...dc,dc->...", x, w) +y = hax.dot(x, w, axis=(D, C), out_axes=(W, H)) # shape is (W, H) instead of (H, W) +y = hax.dot(x, w, c, axis=(D, C)) # shape is (H, W), equivalent to np.einsum("...dc,dc,c->...", x, w, c) +y = hax.dot(x, c, axis=(H, D, C)) # shape is (W,), equivalent to np.einsum("hwdc,c->w", x, c) +s = hax.dot(x, w, axis=None) # scalar output, equivalent to np.einsum("hwdc,dc->", x, w) +y = hax.dot(x, w, c, axis=()) # shape is (H, W, D, C), equivalent to np.einsum("hwdc,dc,c->hwdc", x, w, c) +y = hax.dot(x, w, c, axis=(), out_axes=(D, ..., H)) # shape is (D, W, C, H), equivalent to np.einsum("hwdc,dc,c->dwch", x, w, c) +``` + +### `haliax.einsum` + +[haliax.einsum][] is at its best when you want to express a more complex tensor contraction. +It is similar to [numpy.einsum](https://numpy.org/doc/stable/reference/generated/numpy.einsum.html) +or [einops.einsum](https://einops.rocks/api/einsum/) in terms of syntax and behavior, +but extended to work with named axes, including added flexibility that named axes provide. +Our "flavor" of `einsum` is most similar to `einops.einsum`'s flavor, in that +it supports long names for axes (like `"batch h w, h w channel -> batch channel"`) +rather than the compact notation of `numpy.einsum` (like `"bhwc,hwc->bc"`). + +Haliax's version of `einsum` comes in three modes: "ordered", "unordered", and "output axes". +These modes are all accessible through the same function without any flags: the syntax +of the `einsum` string determines which mode is used. + +#### Ordered Mode + +Haliax's `einsum` has an "ordered" mode that is similar to `einops.einsum`'s behavior. +In this mode, the axes in the input arrays are matched to the axes in the `einsum` string in order. +It supports ellipses in the same way as `einops.einsum`. The names in the einsum string need not +match the names of the axes in the input arrays, but the order of the axes must match. + +```python +import haliax as hax + +H = hax.Axis("H", 3) +W = hax.Axis("W", 4) +D = hax.Axis("D", 5) + +x = hax.ones((H, W, D)) +w = hax.ones((D,)) +y = hax.einsum("h w d, d -> h w", x, w) # shape is (H, W), equivalent to jnp.einsum("hwd,d->hw", x, w) +y = hax.einsum("... d, d -> ...", x, w) # same as above +``` + +The `...` syntax is used to indicate that the axes in the input arrays that are not mentioned in the `einsum` string +should be preserved in the output. This should be the same as `einops.einsum`'s behavior, with the exception +that the names of axes with the same label in the string must have the same names in the input arrays. + +(If you notice any differences between Haliax's `einsum`'s ordered syntax and `einops.einsum`, please let us know!) + +#### Unordered Mode + +In "unordered mode," the axes in the input arrays are matched to the axes in the `einsum` string by name, +using similar rules to [haliax.rearrange][]. Names involved in the operation are specified inside `{}` +on the left hand side of the `->` in the `einsum` string. Axes not specified are implicitly preserved. + +```python +import haliax as hax + +H = hax.Axis("H", 3) +W = hax.Axis("W", 4) +D = hax.Axis("D", 5) + +x = hax.ones((H, W, D)) +w = hax.ones((D,)) + +y = hax.einsum("{H W D} -> H W", x) # shape is (H, W) +y = hax.einsum("{D} -> ", w) # shape is (H, W) +y = hax.einsum("{...} -> ", x) # shape is () +y = hax.einsum("{H ...} -> H", x) # shape is (H,) +y = hax.einsum("{H ...} -> ...", x) # shape is (W, D) +``` + +This mode is most similar to [haliax.dot][]'s behavior, though it's a bit more expressive. + +#### Output Axes Mode + +In "output axes" mode, you only specify the axes that should be in the output. All other +axes are implicitly contracted over. This mode is a bit "dangerous" in that it's easy to +accidentally contract over axes you didn't mean to, but it can be useful for expressing +certain contractions concisely. + +```python +import haliax as hax + +H = hax.Axis("H", 3) +W = hax.Axis("W", 4) +D = hax.Axis("D", 5) + +x = hax.ones((H, W, D)) +w = hax.ones((D,)) + +y = hax.einsum("-> H W", x) # shape is (H, W) +y = hax.einsum("-> D", w) # shape is (D,) +``` + +We don't recommend using this mode except in cases when you're sure of the full shape of the input arrays +or you are sure you don't want to let users implicitly batch over any axes. diff --git a/docs/partitioning.md b/docs/partitioning.md index ba56628..f27ab41 100644 --- a/docs/partitioning.md +++ b/docs/partitioning.md @@ -112,11 +112,15 @@ This is the main function you will use to shard arrays: ::: haliax.shard -These are older functions that are being deprecated and will be removed in a future release: +This function is like `shard` but does not issue a warning if there is no context axis mapping. +It's useful for library code where there may or may not be a context mapping: -::: haliax.shard_with_axis_mapping ::: haliax.auto_sharded +This is an older function that is being deprecated in favor of `shard`. It is functionally equivalent to `shard`: + +::: haliax.shard_with_axis_mapping + ### `named_jit` and friends ::: haliax.named_jit diff --git a/docs/rearrange.md b/docs/rearrange.md index 7c68738..80f8ec9 100644 --- a/docs/rearrange.md +++ b/docs/rearrange.md @@ -93,6 +93,11 @@ y = hax.rearrange(x, "{(N: step microbatch) ...} -> step microbatch ...", step=4 # merging dims requires a name x = hax.rearrange(y, "step microbatch ... -> (N: step microbatch) ...") +# you can partially specify the order by using two or more ellipses on the rhs +y = hax.rearrange(x, "{H W} -> ... (F: H W) ...") +y = hax.rearrange(x, "{H W C} -> ... (F: H W) ... C") # ensures C is the last dimension + + # some fancier examples # split into patches @@ -153,9 +158,9 @@ A note on "axis variable" vs "axis name": the former is an identifier that can r by **position** in the input, while the latter is an identifier that refers to a specific axis and is matched by **name** in the input (or used to name an axis in the output). -The `rhs` is always ordered. Its syntax is similar to an ordered `lhs`, except that merged axes must always be named. +The `rhs` is always ordered. Its syntax is similar to an ordered `lhs`, except that merged axes must always be named and there may be more than one ellipsis. -* *rhs* is a sequence of axis variable names or named merged axes, separated by spaces or commas, and up to one ellipsis. +* *rhs* is a sequence of axis variable names or named merged axes, separated by spaces or commas, and some number of ellipses. * *Named merged axes* are parenthesized expressions of the form `(name: ident ident ...)`, where `name` is an axis name and `ident` is an identifier. The name is used to name the merged axis in the output, and the `ident` are axis variable names that are merged from the input. diff --git a/mkdocs.yml b/mkdocs.yml index c0ee415..4d52dad 100644 --- a/mkdocs.yml +++ b/mkdocs.yml @@ -83,6 +83,7 @@ nav: - Broadcasting: 'broadcasting.md' - Indexing and Slicing: 'indexing.md' - Rearrange: 'rearrange.md' + - Matrix Multiplication: 'matmul.md' - Neural Networks: 'nn.md' - Partitioning: 'partitioning.md' - Higher Order Functions: 'hof.md' diff --git a/src/haliax/__init__.py b/src/haliax/__init__.py index d2678ce..3ca0ed6 100644 --- a/src/haliax/__init__.py +++ b/src/haliax/__init__.py @@ -3,7 +3,12 @@ from typing import Optional, Sequence import jax import jax.numpy as jnp -from jax._src.typing import DTypeLike + + +try: + from jax.typing import DTypeLike +except ImportError: + from jax._src.typing import DTypeLike import haliax.debug as debug import haliax.nn as nn @@ -11,6 +16,8 @@ import haliax.random as random import haliax.tree_util as tree_util import haliax.util as util +from ._src.dot import dot +from ._src.einsum import einsum from ._src.rearrange import rearrange from .axis import ( Axis, @@ -32,7 +39,6 @@ from .core import ( broadcast_arrays, broadcast_axis, broadcast_to, - dot, enable_shape_checks, flatten, flatten_axes, @@ -107,7 +113,7 @@ def full_like(a: NamedArray, fill_value: T, dtype: Optional[DTypeLike] = None) - return NamedArray(jnp.full_like(a.array, fill_value, dtype=dtype), a.axes) -def arange(axis: Axis, *, start: int = 0, step: int = 1, dtype: Optional[DTypeLike] = None) -> NamedArray: +def arange(axis: Axis, *, start=0, step=1, dtype: Optional[DTypeLike] = None) -> NamedArray: """Version of jnp.arange that returns a NamedArray""" # if start is a tracer, we need to be a bit cleverer since arange doesn't support tracers # return NamedArray(jnp.arange(start, stop, step, dtype=dtype), (axis,)) @@ -508,11 +514,11 @@ def any(array: NamedArray, axis: Optional[AxisSelection] = None, *, where: Optio return wrap_reduction_call(jnp.any, array, axis, where, single_axis_only=False, supports_where=True) -def argmax(array: NamedArray, axis: Optional[AxisSelector] = None) -> NamedArray: +def argmax(array: NamedArray, axis: Optional[AxisSelector]) -> NamedArray: return wrap_reduction_call(jnp.argmax, array, axis, None, single_axis_only=True, supports_where=False) -def argmin(array: NamedArray, axis: Optional[AxisSelector] = None) -> NamedArray: +def argmin(array: NamedArray, axis: Optional[AxisSelector]) -> NamedArray: return wrap_reduction_call(jnp.argmin, array, axis, None, single_axis_only=True, supports_where=False) @@ -544,26 +550,32 @@ def prod( return wrap_reduction_call(jnp.prod, array, axis, where, single_axis_only=False, supports_where=True, dtype=dtype) +def std( + array: NamedArray, + axis: Optional[AxisSelection] = None, + *, + where: Optional[NamedArray] = None, + ddof: int = 0, + dtype: Optional[DTypeLike] = None, +) -> NamedArray: + return wrap_reduction_call( + jnp.std, array, axis, where, single_axis_only=False, supports_where=True, dtype=dtype, ddof=ddof + ) + + def ptp(array: NamedArray, axis: Optional[AxisSelection] = None, *, where: Optional[NamedArray] = None) -> NamedArray: return wrap_reduction_call(jnp.ptp, array, axis, where, single_axis_only=False, supports_where=True) def product( - array: NamedArray, axis: Optional[AxisSelection] = None, *, where: Optional[NamedArray] = None -) -> NamedArray: - return wrap_reduction_call(jnp.product, array, axis, where, single_axis_only=False, supports_where=True) - - -def std( array: NamedArray, axis: Optional[AxisSelection] = None, *, where: Optional[NamedArray] = None, - ddof: int = 0, dtype: Optional[DTypeLike] = None, ) -> NamedArray: return wrap_reduction_call( - jnp.std, array, axis, where, single_axis_only=False, supports_where=True, dtype=dtype, ddof=ddof + jnp.product, array, axis, where, single_axis_only=False, supports_where=True, dtype=dtype ) @@ -596,30 +608,33 @@ def var( # "Normalization" functions that use an axis but don't change the shape -def cumsum(a: NamedArray, axis: Optional[AxisSelector] = None, dtype: Optional[DTypeLike] = None) -> NamedArray: +def cumsum(a: NamedArray, axis: AxisSelector, *, dtype: Optional[DTypeLike] = None) -> NamedArray: """ Named version of [jax.numpy.cumsum](https://jax.readthedocs.io/en/latest/_autosummary/jax.numpy.cumsum.html) """ return wrap_axiswise_call(jnp.cumsum, a, axis, dtype=dtype, single_axis_only=True) -def cumprod(a: NamedArray, axis: Optional[AxisSelector] = None, dtype: Optional[DTypeLike] = None) -> NamedArray: +def cumprod(a: NamedArray, axis: AxisSelector, dtype: Optional[DTypeLike] = None) -> NamedArray: """ Named version of [jax.numpy.cumprod](https://jax.readthedocs.io/en/latest/_autosummary/jax.numpy.cumprod.html) """ return wrap_axiswise_call(jnp.cumprod, a, axis, dtype=dtype, single_axis_only=True) -def sort(a: NamedArray, axis: Optional[AxisSelector] = None) -> NamedArray: +def sort(a: NamedArray, axis: AxisSelector) -> NamedArray: """ Named version of [jax.numpy.sort](https://jax.readthedocs.io/en/latest/_autosummary/jax.numpy.sort.html) """ return wrap_axiswise_call(jnp.sort, a, axis, single_axis_only=True) -def argsort(a: NamedArray, axis: Optional[AxisSelector] = None) -> NamedArray: +def argsort(a: NamedArray, axis: AxisSelector) -> NamedArray: """ - Named version of [jax.numpy.argsort](https://jax.readthedocs.io/en/latest/_autosummary/jax.numpy.argsort.html) + Named version of [jax.numpy.argsort](https://jax.readthedocs.io/en/latest/_autosummary/jax.numpy.argsort.html). + + If `axis` is None, the returned array will be a 1D array of indices that would sort the flattened array, + identical to `jax.numpy.argsort(a.array)`. """ return wrap_axiswise_call(jnp.argsort, a, axis, single_axis_only=True) diff --git a/src/haliax/_src/compile_utils.py b/src/haliax/_src/compile_utils.py new file mode 100644 index 0000000..63d98da --- /dev/null +++ b/src/haliax/_src/compile_utils.py @@ -0,0 +1,90 @@ +# This whole file is copied from Equinox. +# (c) 2023, Google LLC. and/or Patrick Kidger. Apache 2.0 licensed. +# Patrick doesn't like that I depend on Equinox internals, so I copied this stuff +import functools as ft +import types +import warnings +import weakref +from typing import Any + +import jax.tree_util as jtu + + +def _strip_wrapped_partial(fun): + if hasattr(fun, "__wrapped__"): # ft.wraps + return _strip_wrapped_partial(fun.__wrapped__) + if isinstance(fun, ft.partial): + return _strip_wrapped_partial(fun.func) + return fun + + +internal_caches = [] # type: ignore +internal_lru_caches = [] # type: ignore + + +def clear_caches(): + """Clears internal Equinox caches. + + Best used before calling `jax.clear_caches()` or `jax.clear_backends()`. + + **Arguments:** + + None. + + **Returns:** + + None. + """ + for cache in internal_caches: + cache.clear() + for cache in internal_lru_caches: + cache.cache_clear() + + +def _default_cache_key(): + assert False + + +def compile_cache(cacheable_fn): + cache = weakref.WeakKeyDictionary() # type: ignore + internal_caches.append(cache) + + def cached_fn_impl(leaves, treedef): + user_fn_names, args, kwargs = jtu.tree_unflatten(treedef, leaves) + return cacheable_fn(user_fn_names, *args, **kwargs) + + @ft.wraps(cacheable_fn) + def wrapped_cacheable_fn(user_fn, *args, **kwargs): + user_fn = _strip_wrapped_partial(user_fn) + # Best-effort attempt to clear the cache of old and unused entries. + cache_key: Any + if type(user_fn) is types.FunctionType: # noqa: E721 + cache_key = user_fn + else: + cache_key = _default_cache_key + + try: + user_fn_names = user_fn.__name__, user_fn.__qualname__ + except AttributeError: + user_fn_names = type(user_fn).__name__, type(user_fn).__qualname__ + leaves, treedef = jtu.tree_flatten((user_fn_names, args, kwargs)) + leaves = tuple(leaves) + + try: + cached_fn = cache[cache_key] + except KeyError: + cached_fn = cache[cache_key] = ft.lru_cache(maxsize=None)(cached_fn_impl) + return cached_fn(leaves, treedef) + + def delete(user_fn): + user_fn = _strip_wrapped_partial(user_fn) + if type(user_fn) is types.FunctionType: # noqa: E721 + try: + del cache[user_fn] + except KeyError: + warnings.warn(f"Could not delete cache for function {user_fn}. Has it already been deleted?") + else: + warnings.warn("Could not delete non-function from cache.") + + wrapped_cacheable_fn.delete = delete # type: ignore + return wrapped_cacheable_fn diff --git a/src/haliax/_src/dot.py b/src/haliax/_src/dot.py new file mode 100644 index 0000000..d17de78 --- /dev/null +++ b/src/haliax/_src/dot.py @@ -0,0 +1,163 @@ +import functools as ft +import typing +import warnings +from typing import Dict, Optional, Tuple + +import jax +import jax.numpy as jnp + +import haliax +from haliax.axis import ( + Axis, + AxisSelection, + PartialAxisSpec, + axis_name, + eliminate_axes, + rearrange_for_partial_order, + union_axes, +) +from haliax.core import NamedArray +from haliax.types import DTypeLike, PrecisionLike +from haliax.util import ensure_tuple + + +# deprecated overload +@typing.overload +def dot( + axis: Optional[AxisSelection], + *arrays: NamedArray, + precision: PrecisionLike = None, + preferred_element_type: Optional[DTypeLike] = None, + out_axes: Optional[PartialAxisSpec] = ..., +) -> NamedArray: + ... + + +@typing.overload +def dot( + *arrays: NamedArray, + axis: Optional[AxisSelection], + precision: PrecisionLike = None, + preferred_element_type: Optional[DTypeLike] = None, + out_axes: Optional[PartialAxisSpec] = ..., +) -> NamedArray: + ... + + +def dot( + *arrays, + precision: PrecisionLike = None, + preferred_element_type: Optional[DTypeLike] = None, + out_axes: Optional[PartialAxisSpec] = None, + **kwargs, +) -> NamedArray: + """Returns the tensor product of two NamedArrays. The axes `axis` are contracted over, + and any other axes that are shared between the arrays are batched over. Non-contracted Axes in one + that are not in the other are preserved. + + Note that if `axis` is None, the result will be a scalar, not a NamedArray. The semantics of `axis=None` are + similar to e.g. how `sum` and other reduction functions work in numpy. If `axis=()`, then the result will be + an "outer product" of the arrays, i.e. a tensor with shape equal to the concatenation of the shapes of the arrays. + + By default, the order of output axes is determined by the order of the input axes, such that each output axis + occurs in the same order as it first occurs in the concatenation of the input axes. + + If `out_axes` is provided, the output will be transposed to match the provided axes. `out_axes` may be a partial + specification of the output axes (using ellipses), in which case the output will be rearranged to be consistent + with the partial specification. For example, if `out_axes=(..., Height, Width)` and the output axes are + `(Width, Height, Depth)`, the output will be transposed to `(Depth, Height, Width)`. Multiple ellipses + are supported, in which case axes will be inserted according to a greedy heuristic that prefers to place + unconstrained axes as soon as all prior axes in the "natural" order are covered. + + Args: + *arrays (NamedArray): The arrays to contract. + axis (AxisSelection): The axes to contract over. + precision (PrecisionLike, optional): The precision to use. Defaults to None. This argument is passed to `jax.numpy.einsum`, + which in turn passes it to jax.lax.dot_general. + preferred_element_type (DTypeLike, optional): The preferred element type of the result. Defaults to None. + This argument is passed to `jax.numpy.einsum`. + out_axes (Optional[PartialAxisSpec], optional): a potentially partial specification of the output axes. + If provided, the output will be transposed to match the provided axes. Defaults to None. + + + Returns: + NamedArray: The result of the contraction. + """ + if len(arrays) == 0: + raise ValueError("Must provide at least one array to dot") + + if "axis" in kwargs: + axis = kwargs["axis"] + else: + axis = arrays[0] + arrays = arrays[1:] + if isinstance(axis, NamedArray): + raise ValueError("Must provide an axis to dot") + + warnings.warn("Axis has been changed to a keyword argument. Please update your code.", DeprecationWarning) + + _ensure_no_mismatched_axes(*arrays) + + all_axes: Tuple[Axis, ...] = ft.reduce(union_axes, (a.axes for a in arrays), ()) # type: ignore + output_axes: Tuple[Axis, ...] + if axis is None: + # we want to contract over all the axes + output_axes = () + else: + output_axes = eliminate_axes(all_axes, axis) + + if out_axes is not None: + output_axes = rearrange_for_partial_order(out_axes, output_axes) + + array_specs = [] + + next_index = 0 + axis_mappings: Dict[str, int] = {} + + for a in arrays: + spec = "" + for ax in a.axes: + if ax.name in axis_mappings: + spec += f"{axis_mappings[ax.name]} " + else: + axis_mappings[ax.name] = next_index + spec += f"{next_index} " + next_index += 1 + + array_specs.append(spec) + + # now compute the output axes: + output_spec = " ".join(str(axis_mappings[ax.name]) for ax in output_axes) + + # get a name for jax so it's easier to interpret logs + if axis is None: + jax_str = f"contract {', '.join(axis_name(ax) for ax in all_axes)} -> <scalar>" + else: + axis = ensure_tuple(axis) + jax_str = f"contract {', '.join(axis_name(ax) for ax in axis)} -> {', '.join(a.name for a in output_axes)}" + + with jax.named_scope(jax_str): + output = jnp.einsum( + ", ".join(array_specs) + "-> " + output_spec, + *[a.array for a in arrays], + precision=precision, + preferred_element_type=preferred_element_type, + ) + + out = NamedArray(output, output_axes) + return haliax.auto_sharded(out) + + +def _ensure_no_mismatched_axes(*arrays: NamedArray): + """Ensure that all the arrays have no axes with the same name but different sizes""" + if len(arrays) <= 1: + return + + known_sizes: dict[str, int] = {} + for a in arrays: + for ax in a.axes: + if ax.name in known_sizes: + if known_sizes[ax.name] != ax.size: + raise ValueError(f"Axis {ax.name} has multiple sizes: {known_sizes[ax.name]} and {ax.size}") + else: + known_sizes[ax.name] = ax.size diff --git a/src/haliax/_src/einsum.py b/src/haliax/_src/einsum.py new file mode 100644 index 0000000..a2e082f --- /dev/null +++ b/src/haliax/_src/einsum.py @@ -0,0 +1,283 @@ +import functools +from types import EllipsisType +from typing import Optional, Sequence, Tuple, Union + +import jax.numpy as jnp + +import haliax + +from ..axis import AxisSelector, axis_name, eliminate_axes, rearrange_for_partial_order, union_axes +from ..core import NamedArray +from ..types import DTypeLike, PrecisionLike +from ..util import ensure_tuple +from .parsing import AliasTable, parse_einsum, raise_parse_error + + +def einsum( + equation: str, + *arrays: NamedArray, + precision: PrecisionLike = None, + preferred_element_type: Optional[DTypeLike] = None, +) -> NamedArray: + """Compute the tensor contraction of the input arrays according to Haliax's named variant of the Einstein summation + convention. + + Examples: + >>> # normal einsum + >>> import haliax as hax + >>> H = hax.Axis("H", 32) + >>> W = hax.Axis("W", 32) + >>> D = hax.Axis("D", 64) + >>> a = hax.zeros((H, W, D)) + >>> b = hax.zeros((D, W, H)) + >>> hax.einsum("h w d, d w h -> h w", a, b) + >>> # named einsum + >>> hax.einsum("{H W D} -> H W", a, b) + >>> hax.einsum("{D} -> ", a, b) # same as the previous example + >>> hax.einsum("-> H W", a, b) # same as the first example + + Args: + equation: The einsum equation. + arrays: The input arrays. + precision: The precision of the computation. + preferred_element_type: The preferred element type of the computation. + + Returns: + The result of the einsum. + """ + lhses, rhs = parse_einsum(equation) + + # we have essentially 3 cases: + # 1. normal positional einsum + # 2. named einsum where a subset of dims are contracted and the rest are kept + # 3. named einsum without an lhs, with a specific set of dims to keep on the rhs + # in each case we need + + # NB: we're using JAX's einsum which only supports one letter names for dims + if len(lhses) == 1 and len(lhses[0].captures) == 0 and lhses[0].is_ordered: + # case 3: get the output axes, contract the others + spec, out_axes = _output_only_named_einsum(equation, arrays, rhs) + elif len(lhses) == 1 and not lhses[0].is_ordered: + # case 2: some axes are named. Those named only on the lhs are contracted, the others are kept + # subcase: if there's an ellipsis on the lhs, we contract all the axes that are not named on the rhs + spec, out_axes = _unordered_einsum(arrays, equation, lhses, rhs) + else: + # general case: we have a normal einsum. we don't allow unordered axes here + if any(not lhs.is_ordered for lhs in lhses): + raise_parse_error("Cannot have multiple unordered axes in an einsum", equation, None) + + spec, out_axes = _positional_einsum_spec(equation, arrays, lhses, rhs) + + out_raw = jnp.einsum( + spec, *[a.array for a in arrays], precision=precision, preferred_element_type=preferred_element_type + ) + + return haliax.named(out_raw, out_axes) + + +def _unordered_einsum(arrays, equation, lhses, rhs): + used_letters: set[str] = set() + name_mappings_for_einsum: dict[str, str] = {} + lhs = lhses[0] + candidate_axes, has_ellipsis_lhs = _captures_to_axis_names(equation, lhs) + rhs_axes, has_ellipsis_rhs = _captures_to_axis_names(equation, rhs) + all_input_axes = _all_input_axes(arrays) + if has_ellipsis_rhs: + out_axes = rearrange_for_partial_order(rhs_axes, all_input_axes) + + elif has_ellipsis_lhs: + # if the lhs has an ellipsis but not the right, we contract all the axes that are not named on the rhs + out_axes = tuple(rhs_axes) + else: + named_on_left_but_not_right = eliminate_axes(candidate_axes, rhs_axes) # type: ignore + # if neither has an ellipsis, we contract the axes that are named on the lhs but not on the rhs + almost_out_axes = eliminate_axes(all_input_axes, named_on_left_but_not_right) # type: ignore + # we now need to rearrange to be consistent with the rhs order. + # since there's no ellipsis on the rhs, we arbitrarily insert one at the beginning which is usually + # what people expect + rhs_axes = [Ellipsis] + rhs_axes # type: ignore + out_axes = rearrange_for_partial_order(rhs_axes, almost_out_axes) + spec = _make_einsum_spec(name_mappings_for_einsum, used_letters, arrays, out_axes) + return spec, out_axes + + +def _output_only_named_einsum(equation, arrays, rhs): + used_letters: set[str] = set() + name_mappings_for_einsum: dict[str, str] = {} + + out_axes = [] + for capture in rhs.captures: + if capture is Ellipsis: + raise_parse_error("Can't use ellipsis on the rhs of an einsum without an lhs", equation, None) + elif capture.binding is None or len(capture.axes) > 1: + raise_parse_error( + "Parenthesized axes are not currently supported in the output of an einsum", + equation, + capture.char_range, + ) + else: + name = capture.binding + + if name in out_axes: + raise_parse_error(f"Axis name {name} occurs multiple times on the rhs", equation, capture.char_range) + + out_axes.append(name) + + spec = _make_einsum_spec(name_mappings_for_einsum, used_letters, arrays, out_axes) + return spec, out_axes + + +def _positional_einsum_spec(equation, arrays, lhses, rhs): + used_letters: set[str] = set() + name_mappings_for_einsum: dict[str, str] = {} + + if len(lhses) != len(arrays): + raise ValueError(f"Number of lhses ({len(lhses)}) does not match number of arrays ({len(arrays)})") + table = AliasTable() + # ok, we're going to lead pretty heavily on einsum here. We just need to figure out the names of the axes + # and do any error checking (that there are no mismatched names) + # once we do that, we can pass a slightly modified spec to einsum (namely that we shorten the names of the axes) + # and we're good to go + spec = "" + for lhs, a in zip(lhses, arrays): + if len(spec): + spec += "," + + # have to deal with ellipsis: we support at most one per lhs and it can appear anywhere + has_ellipsis_lhs = False + axis_off = 0 + for capture in lhs.captures: + if capture is Ellipsis: + has_ellipsis_lhs = True + spec += "..." + axis_off += 1 + break + elif capture.binding is None or len(capture.axes) > 1: + raise_parse_error("Parenthesized axes are not currently supported", equation, capture.char_range) + else: + name = capture.binding + if axis_off >= len(a.axes): + raise ValueError("Mismatched number of axes in einsum") + table.bind_alias(name, a.axes[axis_off], equation, capture.char_range) + letter = _assign_letter_to_name(name, name_mappings_for_einsum, used_letters) + spec += letter + axis_off += 1 + + if has_ellipsis_lhs: + # check there aren't two ellipses + if Ellipsis in lhs.captures[axis_off:]: + raise_parse_error("Can't have two ellipses in an einsum", equation, None) + + final_lhs_axis_off = axis_off + + axis_off = len(a.axes) - 1 + for capture in reversed(lhs.captures): + if capture is Ellipsis: + break + else: + name = capture.binding + if axis_off < final_lhs_axis_off: + raise ValueError("Mismatched number of axes in einsum") + table.bind_alias(name, a.axes[axis_off], equation, capture.char_range) + letter = _assign_letter_to_name(name, name_mappings_for_einsum, used_letters) + spec += letter + axis_off -= 1 + else: + if axis_off != len(a.axes): + raise ValueError("Mismatched number of axes in einsum") + + named_on_left_but_not_right = set(table.bindings.keys()) + spec += "->" + out_axes: list[AxisSelector | EllipsisType] = [] + has_ellipsis_rhs = False + + for capture in rhs.captures: + if capture is Ellipsis: + spec += "..." + out_axes.append(Ellipsis) + if has_ellipsis_rhs: + raise_parse_error("Can't have two ellipses in an ordered einsum", equation, None) + has_ellipsis_rhs = True + elif capture.binding is None or len(capture.axes) > 1: + raise_parse_error( + "Parenthesized axes are not currently supported in the output of an einsum", + equation, + capture.char_range, + ) + else: + name = capture.binding + axis = table.dealias_binding(name) + if axis is None: + raise_parse_error(f"Axis {name} not found in the input arrays", equation, capture.char_range) + + if name_mappings_for_einsum.get(name) is not None: + letter = name_mappings_for_einsum[name] + else: + raise_parse_error( + f"Axis name {name} does not occur on the left hand side", equation, capture.char_range + ) + + named_on_left_but_not_right.discard(letter) + + spec += letter + out_axes.append(axis) + + if has_ellipsis_rhs: + all_input_axes = _all_input_axes(arrays) + # eliminate the axes that are contracted + unmentioned = tuple(table.dealias_binding(name) for name in named_on_left_but_not_right) + out = eliminate_axes(all_input_axes, unmentioned) # type: ignore + return spec, out + else: + return spec, out_axes + + +def _all_input_axes(arrays): + return ensure_tuple(functools.reduce(union_axes, (a.axes for a in arrays), ())) # type: ignore + + +def _captures_to_axis_names(equation, lhs) -> Tuple[list[str | EllipsisType], bool]: + candidate_axes: list[str | EllipsisType] = [] + has_ellipsis = False + for capture in lhs.captures: + if capture is Ellipsis: + has_ellipsis = True + candidate_axes.append(Ellipsis) + elif capture.binding is None or len(capture.axes) > 1: + raise_parse_error("Parenthesized axes are not currently supported", equation, capture.char_range) + else: + name = capture.binding + candidate_axes.append(name) + return candidate_axes, has_ellipsis + + +def _make_einsum_spec(name_mappings_for_einsum, used_letters, arrays, out_axes): + spec = "" + for operand in arrays: + if len(spec): + spec += "," + for axis in operand.axes: + letter = _assign_letter_to_name(axis.name, name_mappings_for_einsum, used_letters) + spec += letter + spec += "->" + for out in out_axes: + letter = name_mappings_for_einsum[axis_name(out)] + spec += letter + return spec + + +def _assign_letter_to_name(name, name_mappings_for_einsum, used_letters): + if name_mappings_for_einsum.get(name) is not None: + return name_mappings_for_einsum[name] + + letter = name[0] + if letter in used_letters: + # try to find another letter. This is obviously not efficient, but it's not a big deal + for letter in "abcdefghijklmnopqrstuvwxyz": + if letter not in used_letters: + break + else: + raise ValueError("Too many axes to contract") + name_mappings_for_einsum[name] = letter + used_letters.add(letter) + return letter diff --git a/src/haliax/_src/parsing.py b/src/haliax/_src/parsing.py new file mode 100644 index 0000000..98c0267 --- /dev/null +++ b/src/haliax/_src/parsing.py @@ -0,0 +1,313 @@ +import dataclasses +from types import EllipsisType +from typing import Mapping, NoReturn, Optional, Sequence + +from haliax.axis import Axis, AxisSelector + + +@dataclasses.dataclass +class _AxisCapture: + binding: Optional[str] = None + axes: tuple[str, ...] = () + char_range: Optional[tuple[int, int]] = None + + def __post_init__(self): + if len(self.axes) == 0: + raise ValueError("Empty axes not allowed") + + +@dataclasses.dataclass +class Expression: + captures: Sequence[_AxisCapture | EllipsisType] + is_ordered: bool + + +def raise_parse_error(message: str, expression: str, pos: Optional[int | tuple[int, int]]) -> NoReturn: + """Raise a ValueError with a message and the position in the expression.""" + fmt = f"Error while parsing:\n {expression}" + if pos is not None: + if isinstance(pos, int): + fmt += f'\n {" " * pos}^' + else: + fmt += f"\n {' ' * pos[0]}{'^' * max(1, pos[1] - pos[0])}" + + fmt += f"\n{message}" + + raise ValueError(fmt) + + +def _parse_quoted_string(expression: str, pos: int) -> tuple[str, int]: + """Parse a quoted string from an einops-style haliax rearrangement string.""" + + if expression[pos] not in "'\"": + raise_parse_error(f"Expected \" or ' at position {pos}", expression, pos) + quote = expression[pos] + pos += 1 + ident = "" + while pos < len(expression): + if expression[pos] == quote: + pos += 1 + break + elif expression[pos] == "\\": + pos += 1 + if pos >= len(expression): + raise_parse_error(f"Unexpected end of string at position {pos}", expression, pos) + ident += expression[pos] + pos += 1 + continue + else: + ident += expression[pos] + pos += 1 + continue + if len(ident) == 0: + raise_parse_error("Empty strings are not valid identifiers", expression, pos) + + return ident, pos + + +def _parse_ident(expression: str, pos: int) -> tuple[str, int]: + """parses an identifier or string literal from an einops-style haliax rearrangement string.""" + if expression[pos] in "'\"": + return _parse_quoted_string(expression, pos) + else: + ident = "" + while pos < len(expression): + if str.isalnum(expression[pos]) or expression[pos] == "_": + if len(ident) == 0 and str.isdigit(expression[pos]): + raise_parse_error("Identifiers cannot start with a number", expression, pos) + ident += expression[pos] + pos += 1 + continue + else: + break + if len(ident) == 0: + raise_parse_error("Identifier expected", expression, pos) + + return ident, pos + + +def _parse_group(expression, pos): + # parses a group of axes like (a b c) or (a: b c) + pos_in = pos + if expression[pos] != "(": + raise ValueError("Expected (") + pos += 1 + binding = None + axes: list[str] = [] + current_ident = "" + while pos < len(expression): + if expression[pos] == ")": + pos += 1 + break + elif expression[pos] == ":": + if binding is not None: + raise_parse_error("Only one binding allowed per group", expression, pos) + if not current_ident: + raise_parse_error("Binding cannot be empty", expression, pos) + if len(axes) > 0: + raise_parse_error("Binding must come before axes", expression, pos) + binding = current_ident + current_ident = "" + pos += 1 + continue + elif str.isspace(expression[pos]): + if current_ident: + axes.append(current_ident) + current_ident = "" + pos += 1 + continue + elif expression[pos] == "(": + raise_parse_error("Only one level of nesting is allowed", expression, pos) + elif expression[pos] == "}": + raise ValueError(f"Unexpected }} at {pos}") + elif str.isalnum(expression[pos]) or expression[pos] == "_": + # don't allow numbers at the start of an identifier + if len(current_ident) == 0 and str.isdigit(expression[pos]): + raise_parse_error("Identifiers cannot start with a number", expression, pos) + current_ident += expression[pos] + pos += 1 + continue + elif expression[pos] in "'\"": + # parse quoted string as identifier + if current_ident: + axes.append(current_ident) + + ident, pos = _parse_quoted_string(expression, pos) + current_ident = ident + continue + else: + raise_parse_error(f"Unexpected character {expression[pos]}", expression, pos) + + if current_ident: + axes.append(current_ident) + + if len(axes) == 0: + raise_parse_error("No axes found", expression, pos_in) + + # todo: should we allow anonymous/literal + char_range = (pos_in, pos) + return _AxisCapture(binding, tuple(axes), char_range), pos + + +def _parse_expression(expression: str, pos) -> tuple[Expression, int]: + """Parse one side of an einops-style haliax rearrangement string.""" + captures = [] + is_ordered = True + seen_char = False + finished = False + + while pos < len(expression): + if expression[pos] == "{": + if seen_char: + raise_parse_error("Unexpected {", expression, pos) + seen_char = True + is_ordered = False + pos += 1 + continue + elif expression[pos] == "}": + if is_ordered: + raise_parse_error("Unexpected }", expression, pos) + pos += 1 + finished = True + continue + elif expression[pos] == "(": + if finished: + raise_parse_error("Unexpected ( after }", expression, pos) + seen_char = True + capture, pos = _parse_group(expression, pos) + captures.append(capture) + continue + elif str.isspace(expression[pos]): + pos += 1 + continue + elif expression[pos : pos + 3] == "...": + seen_char = True + if finished: + raise_parse_error("Unexpected ... after }", expression, pos) + captures.append(Ellipsis) + pos += 3 + continue + elif expression[pos] == "-": + # if not seen_char: + # _raise_error("Unexpected -", expression, pos) + if pos + 1 >= len(expression): + raise_parse_error("Unexpected end of string", expression, pos) + if expression[pos + 1] != ">": + raise_parse_error("Expected >", expression, pos) + break + elif expression[pos] == ",": + # this ends the current expression if we're not inside a group or unordered capture + if not is_ordered: + # treat as whitespace + pos += 1 + continue + if finished: + break + + break + else: + if finished: + raise_parse_error("Unexpected character after }", expression, pos) + ident, new_pos = _parse_ident(expression, pos) + captures.append(_AxisCapture(binding=ident, axes=(ident,), char_range=(pos, new_pos))) + seen_char = True + pos = new_pos + continue + + if not finished and not is_ordered: + raise_parse_error("Expected }", expression, pos) + + return Expression(captures, is_ordered), pos + + +class AliasTable: + bindings: dict[str, AxisSelector] # names in the string to axes + + def __init__(self, bindings=None): + if bindings is None: + bindings = {} + self.bindings = bindings + + def dealias_binding(self, binding: str) -> Optional[AxisSelector]: + return self.bindings.get(binding, None) + + def bind_alias(self, alias: str, axis: Axis, expr, char_range): + if axis.name in self.bindings: + if self.bindings[alias] != axis: + raise_parse_error(f"Alias {alias} is assigned to more than one axis", expr, char_range) + else: + self.bindings[alias] = axis + + +def _resolve_bindings(array, bindings: Mapping[str, Axis | str | int]) -> AliasTable: + b: dict[str, AxisSelector] = {} + for name, selector in bindings.items(): + if isinstance(selector, str): + try: + selector = array.resolve_axis(selector) + except ValueError: + pass + elif isinstance(selector, int): + selector = Axis(name, selector) + assert not isinstance(selector, int) + b[name] = selector + return AliasTable(b) + + +def parse_rearrangement(expression: str) -> tuple[Expression, Expression]: + """Parse an einops-style haliax rearrangement string.""" + pos = 0 + lhs, pos = _parse_expression(expression, pos) + + # consume the -> + if pos + 2 >= len(expression): + raise_parse_error("Unexpected end of string", expression, pos) + if expression[pos : pos + 2] != "->": + raise_parse_error("Expected ->", expression, pos) + + pos += 2 + rhs, pos = _parse_expression(expression, pos) + + # make sure we consumed the whole string + if pos != len(expression): + raise_parse_error("Unexpected character", expression, pos) + + return lhs, rhs + + +def parse_einsum(expression: str) -> tuple[Sequence[Expression], Expression]: + """ + Parse a haliax-style einsum string. This is an expansion of the einsum syntax + to support named axes + """ + pos = 0 + lhses = [] + while pos < len(expression): + lhs, pos = _parse_expression(expression, pos) + lhses.append(lhs) + if pos >= len(expression): + break + if expression[pos] == ",": + pos += 1 + continue + elif expression[pos] == "-": + if pos + 1 >= len(expression): + raise_parse_error("Unexpected end of string", expression, pos) + if expression[pos + 1] != ">": + raise_parse_error("Expected >", expression, pos) + pos += 2 + break + else: + raise_parse_error("Expected , or ->", expression, pos) + + rhs, pos = _parse_expression(expression, pos) + + if any(x is None for x in lhses): + if len(lhses) > 1: + raise_parse_error("If there are multiple lhs expressions, they must all be ordered", expression, pos) + lhses = None # type: ignore + + if pos != len(expression): + raise_parse_error("Unexpected character", expression, pos) + + return lhses, rhs diff --git a/src/haliax/_src/rearrange.py b/src/haliax/_src/rearrange.py index 7f02376..ce6e5ef 100644 --- a/src/haliax/_src/rearrange.py +++ b/src/haliax/_src/rearrange.py @@ -2,249 +2,15 @@ import dataclasses import typing from types import EllipsisType -from typing import Mapping, NoReturn, Optional, Sequence +from typing import Mapping, Optional, Sequence import jax.lax import jax.numpy as jnp -from ..axis import Axis, AxisSelector, axis_name +from ..axis import Axis, AxisSelector, PartialAxisSpec, axis_name, rearrange_for_partial_order from ..core import NamedArray -from ..partitioning import shard - - -@dataclasses.dataclass -class _AxisCapture: - binding: Optional[str] = None - axes: tuple[str, ...] = () - char_range: Optional[tuple[int, int]] = None - - def __post_init__(self): - if len(self.axes) == 0: - raise ValueError("Empty axes not allowed") - - -@dataclasses.dataclass -class Expression: - captures: Sequence[_AxisCapture | EllipsisType] - is_ordered: bool - - -def _raise_error(message: str, expression: str, pos: Optional[int | tuple[int, int]]) -> NoReturn: - """Raise a ValueError with a message and the position in the expression.""" - fmt = f"Error while parsing:\n {expression}" - if pos is not None: - if isinstance(pos, int): - fmt += f'\n {" " * pos}^' - else: - fmt += f"\n {' ' * pos[0]}{'^' * max(1, pos[1] - pos[0])}" - - fmt += f"\n{message}" - - raise ValueError(fmt) - - -def _parse_quoted_string(expression: str, pos: int) -> tuple[str, int]: - """Parse a quoted string from an einops-style haliax rearrangement string.""" - - if expression[pos] not in "'\"": - _raise_error(f"Expected \" or ' at position {pos}", expression, pos) - quote = expression[pos] - pos += 1 - ident = "" - while pos < len(expression): - if expression[pos] == quote: - pos += 1 - break - elif expression[pos] == "\\": - pos += 1 - if pos >= len(expression): - _raise_error(f"Unexpected end of string at position {pos}", expression, pos) - ident += expression[pos] - pos += 1 - continue - else: - ident += expression[pos] - pos += 1 - continue - if len(ident) == 0: - _raise_error("Empty strings are not valid identifiers", expression, pos) - - return ident, pos - - -def _parse_ident(expression: str, pos: int) -> tuple[str, int]: - """parses an identifier or string literal from an einops-style haliax rearrangement string.""" - if expression[pos] in "'\"": - return _parse_quoted_string(expression, pos) - else: - ident = "" - while pos < len(expression): - if str.isalnum(expression[pos]) or expression[pos] == "_": - if len(ident) == 0 and str.isdigit(expression[pos]): - _raise_error("Identifiers cannot start with a number", expression, pos) - ident += expression[pos] - pos += 1 - continue - else: - break - if len(ident) == 0: - _raise_error("Identifier expected", expression, pos) - - return ident, pos - - -def _parse_group(expression, pos): - # parses a group of axes like (a b c) or (a: b c) - pos_in = pos - if expression[pos] != "(": - raise ValueError("Expected (") - pos += 1 - binding = None - axes = [] - current_ident = "" - while pos < len(expression): - if expression[pos] == ")": - pos += 1 - break - elif expression[pos] == ":": - if binding is not None: - _raise_error("Only one binding allowed per group", expression, pos) - if not current_ident: - _raise_error("Binding cannot be empty", expression, pos) - if len(axes) > 0: - _raise_error("Binding must come before axes", expression, pos) - binding = current_ident - current_ident = "" - pos += 1 - continue - elif str.isspace(expression[pos]) or expression[pos] == ",": - if current_ident: - axes.append(current_ident) - current_ident = "" - pos += 1 - continue - elif expression[pos] == "(": - _raise_error("Only one level of nesting is allowed", expression, pos) - elif expression[pos] == "}": - raise ValueError(f"Unexpected }} at {pos}") - elif str.isalnum(expression[pos]) or expression[pos] == "_": - # don't allow numbers at the start of an identifier - if len(current_ident) == 0 and str.isdigit(expression[pos]): - _raise_error("Identifiers cannot start with a number", expression, pos) - current_ident += expression[pos] - pos += 1 - continue - elif expression[pos] in "'\"": - # parse quoted string as identifier - if current_ident: - axes.append(current_ident) - - ident, pos = _parse_quoted_string(expression, pos) - current_ident = ident - continue - else: - _raise_error(f"Unexpected character {expression[pos]}", expression, pos) - - if current_ident: - axes.append(current_ident) - - if len(axes) == 0: - _raise_error("No axes found", expression, pos_in) - - # todo: should we allow anonymous/literal - char_range = (pos_in, pos) - return _AxisCapture(binding, tuple(axes), char_range), pos - - -def _parse_expression(expression: str, pos) -> tuple[Expression, int]: - """Parse one side of an einops-style haliax rearrangement string.""" - captures = [] - is_ordered = True - seen_char = False - finished = False - - while pos < len(expression): - if expression[pos] == "{": - if seen_char: - _raise_error("Unexpected {", expression, pos) - seen_char = True - is_ordered = False - pos += 1 - continue - elif expression[pos] == "}": - if is_ordered: - _raise_error("Unexpected }", expression, pos) - pos += 1 - finished = True - continue - elif expression[pos] == "(": - if finished: - _raise_error("Unexpected ( after }", expression, pos) - seen_char = True - capture, pos = _parse_group(expression, pos) - captures.append(capture) - continue - elif str.isspace(expression[pos]) or expression[pos] == ",": - pos += 1 - continue - elif expression[pos : pos + 3] == "...": - seen_char = True - if finished: - _raise_error("Unexpected ... after }", expression, pos) - captures.append(Ellipsis) - pos += 3 - continue - elif expression[pos] == "-": - if not seen_char: - _raise_error("Unexpected -", expression, pos) - if pos + 1 >= len(expression): - _raise_error("Unexpected end of string", expression, pos) - if expression[pos + 1] != ">": - _raise_error("Expected >", expression, pos) - break - else: - if finished: - _raise_error("Unexpected character after }", expression, pos) - ident, new_pos = _parse_ident(expression, pos) - captures.append(_AxisCapture(binding=ident, axes=(ident,), char_range=(pos, new_pos))) - seen_char = True - pos = new_pos - continue - - if not finished and not is_ordered: - _raise_error("Expected }", expression, pos) - - return Expression(captures, is_ordered), pos - - -def parse_rearrangement(expression: str) -> tuple[Expression, Expression]: - """Parse an einops-style haliax rearrangement string.""" - pos = 0 - lhs, pos = _parse_expression(expression, pos) - - # consume the -> - if pos + 2 >= len(expression): - _raise_error("Unexpected end of string", expression, pos) - if expression[pos : pos + 2] != "->": - _raise_error("Expected ->", expression, pos) - - pos += 2 - rhs, pos = _parse_expression(expression, pos) - - # make sure we consumed the whole string - if pos != len(expression): - _raise_error("Unexpected character", expression, pos) - - return lhs, rhs - - -@dataclasses.dataclass -class _Plan: - intermediate_axes: tuple[Axis, ...] - transpose: Optional[tuple[int, ...]] - needs_final_reshape: bool - - final_axes: tuple[Axis, ...] +from ..partitioning import auto_sharded +from .parsing import AliasTable, Expression, _resolve_bindings, parse_rearrangement, raise_parse_error @typing.overload @@ -321,52 +87,31 @@ def rearrange(array: NamedArray, *args, **kwargs) -> NamedArray: return axis_spec_rearrange(array, axes) -def axis_spec_rearrange(array: NamedArray, axes: Sequence[AxisSelector | EllipsisType]) -> NamedArray: - if len(axes) == 0 and len(array.axes) != 0: +def axis_spec_rearrange(array: NamedArray, axis_spec: PartialAxisSpec) -> NamedArray: + if len(axis_spec) == 0 and len(array.axes) != 0: raise ValueError("No axes specified") # various fast paths - if len(axes) == 1 and axes[0] is Ellipsis: + if len(axis_spec) == 1 and axis_spec[0] is Ellipsis: return array - if axes == array.axes: + if axis_spec == array.axes: return array - if axes[-1] is Ellipsis and array.axes[0 : len(axes) - 1] == axes[0 : len(axes) - 1]: + if axis_spec[-1] is Ellipsis and array.axes[0 : len(axis_spec) - 1] == axis_spec[0 : len(axis_spec) - 1]: return array - if axes[0] is Ellipsis and array.axes[len(axes) - 1 :] == axes[1:]: + if axis_spec[0] is Ellipsis and array.axes[len(axis_spec) - 1 :] == axis_spec[1:]: return array - if axes.count(Ellipsis) > 1: - raise ValueError("Only one ellipsis allowed") + out_axes = rearrange_for_partial_order(axis_spec, array.axes) - used_indices = [False] * len(array.axes) - permute_spec: list[int | EllipsisType] = [] - ellipsis_pos = None - for ax in axes: - if ax is Ellipsis: - permute_spec.append(Ellipsis) # will revisit - ellipsis_pos = len(permute_spec) - 1 - else: - assert isinstance(ax, Axis) or isinstance(ax, str) # please mypy - index = array._lookup_indices(ax) - if index is None: - raise ValueError(f"Axis {ax} not found in {array}") - if used_indices[index]: - raise ValueError(f"Axis {ax} specified more than once") - used_indices[index] = True - permute_spec.append(index) - - if not all(used_indices): - # find the ellipsis position, replace it with all the unused indices - if ellipsis_pos is None: - missing_axes = [ax for i, ax in enumerate(array.axes) if not used_indices[i]] - raise ValueError(f"Axes {missing_axes} not found and no ... specified. Array axes: {array.axes}") from None - - permute_spec[ellipsis_pos : ellipsis_pos + 1] = tuple(i for i in range(len(array.axes)) if not used_indices[i]) - elif ellipsis_pos is not None: - permute_spec.remove(Ellipsis) + # now build a permute_spec + permute_spec = [] + index_of_in = {ax: i for i, ax in enumerate(array.axes)} + + for ax in out_axes: + permute_spec.append(index_of_in[ax]) out_axes = tuple(array.axes[i] for i in typing.cast(list[int], permute_spec)) return NamedArray(jnp.transpose(array.array, permute_spec), out_axes) @@ -389,7 +134,7 @@ def einops_rearrange(array: NamedArray, expression: str, **bindings: AxisSelecto if plan.intermediate_axes != array.axes: raw_array = raw_array.reshape([ax.size for ax in plan.intermediate_axes]) array = NamedArray(raw_array, plan.intermediate_axes) - array = shard(array) + array = auto_sharded(array) raw_array = array.array final_shape = tuple(ax.size for ax in plan.final_axes) @@ -401,7 +146,16 @@ def einops_rearrange(array: NamedArray, expression: str, **bindings: AxisSelecto else: finished_array = raw_array - return shard(NamedArray(finished_array, plan.final_axes)) + return auto_sharded(NamedArray(finished_array, plan.final_axes)) + + +@dataclasses.dataclass +class _Plan: + intermediate_axes: tuple[Axis, ...] + transpose: Optional[tuple[int, ...]] + needs_final_reshape: bool + + final_axes: tuple[Axis, ...] def _plan_rearrange( @@ -426,90 +180,59 @@ def _plan_rearrange( return _Plan(intermediate_axes, transpose, needs_final_reshape, final_axes) -class AliasTable: - bindings: dict[str, AxisSelector] # names in the string to either axes or - - def __init__(self, bindings): - self.bindings = bindings - - def dealias_binding(self, binding: str) -> Optional[AxisSelector]: - return self.bindings.get(binding, None) - - def bind_alias(self, alias: str, axis: Axis, expr, char_range): - if axis.name in self.bindings: - if self.bindings[alias] != axis: - _raise_error(f"Alias {alias} is assigned to more than one axis", expr, char_range) - else: - self.bindings[alias] = axis - - -def _resolve_bindings(array, bindings: Mapping[str, Axis | str | int]) -> AliasTable: - b: dict[str, AxisSelector] = {} - for name, selector in bindings.items(): - if isinstance(selector, str): - try: - selector = array.resolve_axis(selector) - except ValueError: - pass - elif isinstance(selector, int): - selector = Axis(name, selector) - assert not isinstance(selector, int) - b[name] = selector - return AliasTable(b) - - def _determine_final_transpose_and_reshape( expression, rhs: Expression, aliases: "AliasTable", intermediate_axes: tuple[Axis, ...] ) -> tuple[tuple[int, ...], tuple[Axis, ...]]: - # The rhs tells us two things: + # The rhs tells us three things: # 1. how to reorder the intermediate axes # 2. how to merge the intermediate axes into the final axes + # 3. where ellipses are in the final axes (where we can put unused intermediate axes) + + # MUTATES `aliases` + + # Our approach is to: + # 1. Figure out the partial order of the intermediate axes + # 2. Compute the full final axes (using rearrange_for_partial_order) + # 3. Figure out the transposition order to get the intermediate axes into the right order + # return (2) and (3) - transposition_order: list[int | EllipsisType] = [] + transposed_intermediate_axes_order: list[Axis | EllipsisType] = [] - final_axes: list[Axis | EllipsisType] = [] - used_axes = set() # axes must be used exactly once + first_intermediate_for_final: dict[Axis, Axis] = {} # intermediate -> final - position_of_ellipsis = None # If there's an ellipsis, we want to put any remaining axes there - position_of_ellipsis_in_transposition = None # if there's an ellipsis, we want to put any remaining axes there + used_intermediate_axes = set() # axes must be used exactly once + has_ellipsis = False - # each capture, except for ellipsis results in one final axis for cpos, capture in enumerate(rhs.captures): if capture == Ellipsis: - if position_of_ellipsis is not None: - previous_capture = rhs.captures[cpos - 1] - _raise_error("Only one ellipsis allowed", expression, previous_capture.char_range) - position_of_ellipsis = cpos - final_axes.append(Ellipsis) - transposition_order.append(Ellipsis) - position_of_ellipsis_in_transposition = len(transposition_order) - 1 + has_ellipsis = True + transposed_intermediate_axes_order.append(Ellipsis) continue assert not isinstance(capture, EllipsisType) binding = capture.binding if binding is None: - _raise_error("All rhs axes must have a name. Use (name: bindings)", expression, capture.char_range) + raise_parse_error("All rhs axes must have a name. Use (name: bindings)", expression, capture.char_range) - # now look at the captured axes. these are the axes that we're going to merge into one final axis - # we're also going to move them around to match the order of the intermediate axes sz = 1 + first_axis = None for ax_name in capture.axes: - axis = aliases.dealias_binding(ax_name) - if not isinstance(axis, Axis): - _raise_error(f"Axis {ax_name} is not bound on the lhs", expression, capture.char_range) + intermed_axis = aliases.dealias_binding(ax_name) + + if not isinstance(intermed_axis, Axis): + raise_parse_error(f"Axis {ax_name} is not bound on the lhs", expression, capture.char_range) - if axis in used_axes: - _raise_error(f"Axis {axis} is used more than once", expression, capture.char_range) - used_axes.add(axis) + if first_axis is None: + first_axis = intermed_axis - sz *= axis.size + if intermed_axis in used_intermediate_axes: + raise_parse_error(f"Axis {intermed_axis} is used more than once", expression, capture.char_range) + used_intermediate_axes.add(intermed_axis) + transposed_intermediate_axes_order.append(intermed_axis) + + sz *= intermed_axis.size # now find the position of this axis in the intermediate axes - try: - index_in_intermediate = intermediate_axes.index(axis) - transposition_order.append(index_in_intermediate) - except ValueError: - _raise_error(f"Axis {ax_name} is not in the lhs", expression, capture.char_range) # figure out the name of the final axis axis = aliases.dealias_binding(binding) @@ -518,41 +241,35 @@ def _determine_final_transpose_and_reshape( else: new_axis = Axis(axis_name(axis), sz) - # Do not bind here because axis names can be reused + # TODO: this isn't ideal for the unusual case where we have an empty set of axes to bind to an axis + # we won't accurately get the order for these unitary axes + if first_axis is not None: + first_intermediate_for_final[first_axis] = new_axis - final_axes.append(new_axis) - - if position_of_ellipsis is not None: - unused_intermediate_axes = [ax for ax in intermediate_axes if ax not in used_axes] + if not has_ellipsis: + unused_intermediate_axes = set(intermediate_axes) - used_intermediate_axes if len(unused_intermediate_axes) > 0: - # we need to put the unused axes in the ellipsis - final_axes = ( - final_axes[:position_of_ellipsis] + unused_intermediate_axes + final_axes[position_of_ellipsis + 1 :] - ) + raise ValueError("Not all intermediate axes are used. Use ... to insert unused axes") - unused_indices = [i for i in range(len(intermediate_axes)) if intermediate_axes[i] not in used_axes] + # now we have a partial order of the intermediate axes + reordered_intermediate_axes = rearrange_for_partial_order(transposed_intermediate_axes_order, intermediate_axes) - assert position_of_ellipsis_in_transposition is not None + # now we need to figure out the final axes + final_axes: list[Axis] = [] + transposition_order: list[int] = [] - transposition_order = ( - transposition_order[:position_of_ellipsis_in_transposition] - + unused_indices - + transposition_order[position_of_ellipsis_in_transposition + 1 :] - ) + for intermediate_axis in reordered_intermediate_axes: + if intermediate_axis not in used_intermediate_axes: + # this axis is not used, so we keep it from the reordered axes + final_axes.append(intermediate_axis) + transposition_order.append(intermediate_axes.index(intermediate_axis)) + else: + final_axis = first_intermediate_for_final.get(intermediate_axis, None) - else: - # make sure we used all the axes - if len(used_axes) < len(intermediate_axes): - # figure out their binding names as possible: - inverse_bindings = {v: k for k, v in aliases.bindings.items()} - unused_intermediate_axis_names = [ - inverse_bindings.get(ax, ax.name) for ax in intermediate_axes if ax not in used_axes - ] - _raise_error( - f"Not all intermediate axes are used: {','.join(unused_intermediate_axis_names) }", - expression, - len(expression) - 1, - ) + if final_axis is not None: + final_axes.append(final_axis) + + transposition_order.append(intermediate_axes.index(intermediate_axis)) return tuple(transposition_order), tuple(final_axes) # type: ignore @@ -593,7 +310,7 @@ def _determine_initial_reshape( assert not isinstance(capture, EllipsisType) if axis_pos >= len(array.axes): - _raise_error("Too many axes in lhs", expression, capture.char_range) + raise_parse_error("Too many axes in lhs", expression, capture.char_range) axis_index_for_capture[cpos] = axis_pos covered_axes.add(axis_pos) @@ -605,13 +322,13 @@ def _determine_initial_reshape( for cpos in range(len(lhs.captures) - 1, ellipsis_pos, -1): capture = lhs.captures[cpos] if capture == Ellipsis: - _raise_error("Only one ellipsis allowed", expression, None) + raise_parse_error("Only one ellipsis allowed", expression, None) assert not isinstance(capture, EllipsisType) axis_index_for_capture[cpos] = axis_pos if axis_pos in covered_axes: - _raise_error( + raise_parse_error( f"Axis {array.axes[axis_pos]} is bound more than once", expression, capture.char_range, @@ -621,11 +338,11 @@ def _determine_initial_reshape( else: # no ellipsis, so we need to check that we covered all axes if len(covered_axes) < len(array.axes): - _raise_error( + raise_parse_error( "Not all axes are bound, use ... to skip missing axes", expression, len(expression) - 1 ) # type: ignore elif len(covered_axes) > len(array.axes): - _raise_error("Too many axes are bound", expression, lhs.captures[-1].char_range) # type: ignore + raise_parse_error("Too many axes are bound", expression, lhs.captures[-1].char_range) # type: ignore # now that we have the bindings, we can figure out the new shapes for cpos, capture in enumerate(lhs.captures): @@ -635,11 +352,11 @@ def _determine_initial_reshape( axis_index = axis_index_for_capture[cpos] if axis_index is None: - _raise_error("Internal error", expression, capture.char_range) + raise_parse_error("Internal error", expression, capture.char_range) axis = array.axes[axis_index] if new_shapes[axis_index] is not None: - _raise_error(f"Axis {axis} is bound more than once", expression, capture.char_range) + raise_parse_error(f"Axis {axis} is bound more than once", expression, capture.char_range) new_axes = _solve_split_axes(axis, capture, aliases, used_new_names, expression) new_shapes[axis_index] = new_axes # type: ignore @@ -654,7 +371,7 @@ def _determine_initial_reshape( assert not isinstance(capture, EllipsisType) if capture.binding is None: - _raise_error( + raise_parse_error( "Unordered axes must be bound by name, e.g. (a: b) or just a", expression, capture.char_range ) @@ -669,14 +386,14 @@ def _determine_initial_reshape( axis = array.resolve_axis(maybe_alias) # aliases.bind_alias(capture.binding, axis, expression, capture.char_range) except ValueError: - _raise_error(f"Could not resolve axis {maybe_alias}", expression, capture.char_range) + raise_parse_error(f"Could not resolve axis {maybe_alias}", expression, capture.char_range) try: axis_index = array.axes.index(axis) except ValueError: - _raise_error(f"Axis {axis} is not in the array", expression, capture.char_range) + raise_parse_error(f"Axis {axis} is not in the array", expression, capture.char_range) if new_shapes[axis_index] is not None: - _raise_error(f"Axis {axis} is bound more than once", expression, capture.char_range) + raise_parse_error(f"Axis {axis} is bound more than once", expression, capture.char_range) new_axes = _solve_split_axes(axis, capture, aliases, used_new_names, expression) new_shapes[axis_index] = new_axes # type: ignore @@ -699,7 +416,7 @@ def _solve_split_axes(axis, capture, aliases, used_new_names, expression): if len(capture.axes) == 1: new_axis_name = capture.axes[0] if new_axis_name in used_new_names: - _raise_error(f"Capture {new_axis_name} is assigned more than once", expression, capture.char_range) + raise_parse_error(f"Capture {new_axis_name} is assigned more than once", expression, capture.char_range) used_new_names.add(new_axis_name) new_axes.append(axis) @@ -711,7 +428,9 @@ def _solve_split_axes(axis, capture, aliases, used_new_names, expression): for new_axis_name in capture.axes: if new_axis_name in used_new_names: - _raise_error(f"Capture {new_axis_name} is assigned more than once in lhs", expression, capture.char_range) + raise_parse_error( + f"Capture {new_axis_name} is assigned more than once in lhs", expression, capture.char_range + ) used_new_names.add(new_axis_name) @@ -722,11 +441,11 @@ def _solve_split_axes(axis, capture, aliases, used_new_names, expression): if isinstance(new_axis, Axis): new_axes.append(new_axis) if remaining_size % new_axis.size: - _raise_error(f"Axes do not divide evenly into axis {axis}", expression, capture.char_range) + raise_parse_error(f"Axes do not divide evenly into axis {axis}", expression, capture.char_range) remaining_size //= new_axis.size else: if unsolved_axis_index is not None: - _raise_error( + raise_parse_error( "Sizes for this split axis are ambiguous. You must provide a size as a kwarg.", expression, capture.char_range, diff --git a/src/haliax/_src/util.py b/src/haliax/_src/util.py index ac5824a..61f3ea9 100644 --- a/src/haliax/_src/util.py +++ b/src/haliax/_src/util.py @@ -2,18 +2,19 @@ from typing import Callable, MutableMapping, Sequence, TypeAlias, TypeVar T = TypeVar("T") +U = TypeVar("U") py_slice = slice slice_t: TypeAlias = slice -def index_where(pred: Callable[[T], bool], xs: Sequence[T]) -> int: - for i, x in enumerate(xs): - if pred(x): +def index_where(pred: Callable[[T], bool], xs: Sequence[T], start: int = 0) -> int: + for i in range(start, len(xs)): + if pred(xs[i]): return i raise ValueError("No element satisfies predicate") -class IdentityMap(MutableMapping): +class IdentityMap(MutableMapping[T, U]): """Map that compares keys by identity. This is a map that compares keys by identity instead of equality. It is diff --git a/src/haliax/axis.py b/src/haliax/axis.py index e707d27..736c8aa 100644 --- a/src/haliax/axis.py +++ b/src/haliax/axis.py @@ -1,5 +1,6 @@ import typing from dataclasses import dataclass +from types import EllipsisType from typing import Dict, List, Mapping, Optional, Sequence, Tuple, Union, overload import equinox as eqx @@ -40,6 +41,13 @@ PartialShapeDict = Mapping[str, Optional[int]] """Similar to an AxisSelection, in dict form.""" +PartialAxisSpec = Sequence[EllipsisType | AxisSelector] +"""Used for rearrange and dot. A tuple of AxisSelectors and Ellipsis. Ellipsis means "any number of axes." +Some functions may require that the Ellipsis is present at most once, while others may allow it to be present +multiple times. +""" + + def selects_axis(selector: AxisSelection, selected: AxisSelection) -> bool: """Returns true if the selector has every axis in selected and, if dims are given, that they match""" if isinstance(selector, Axis) or isinstance(selector, str): @@ -292,7 +300,9 @@ def overlapping_axes(ax1: AxisSelection, ax2: AxisSelection) -> Tuple[AxisSelect def overlapping_axes(ax1: AxisSelection, ax2: AxisSelection) -> Tuple[AxisSelector, ...]: - """Returns a tuple of axes that are present in both ax1 and ax2""" + """Returns a tuple of axes that are present in both ax1 and ax2. + The returned order is the same as ax1. + """ ax2_dict = axis_spec_to_shape_dict(ax2) out: List[AxisSelector] = [] ax1 = ensure_tuple(ax1) @@ -392,11 +402,127 @@ def dblock(idx: int, size: int) -> dslice: return dslice(idx * size, size) +Ax = typing.TypeVar("Ax", AxisSelector, Axis) + + +def rearrange_for_partial_order(partial_order: PartialAxisSpec, axes: tuple[Ax, ...]) -> tuple[Ax, ...]: + """Rearrange the axes to fit the provided partial order. + Uses a greedy algorithm that tries to keep elements in roughly the same order they came in + (subject to the partial order), but moves them to the earliest slot that is after all prior axes + in the original order. + The exact behavior of this function is not guaranteed to be stable, but it should be stable + for most reasonable use cases. If you really need a specific order, you should provide a full + order instead of a partial order. + """ + + if partial_order == (Ellipsis,): + return axes + + spec = axis_spec_to_shape_dict(axes) + + def as_axis(ax_name: str) -> Ax: + if spec[ax_name] is None: + return ax_name # type: ignore + else: + return Axis(ax_name, spec[ax_name]) # type: ignore + + if Ellipsis not in partial_order: + pa: tuple[AxisSelector, ...] = partial_order # type: ignore + if set(axis_name(a) for a in pa) != set(spec.keys()) or len(pa) != len(spec.keys()): + raise ValueError( + "Partial order must be a permutation of the axes if no ellipsis is provided." + f" However {pa} is not a permutation of {axes}" + ) + + # reorder axes to match partial order + return tuple(as_axis(axis_name(name)) for name in pa) + + partial_order_names = [axis_name(s) for s in partial_order if s is not ...] + + uncovered_ordered_elements = set(partial_order_names) + + if len(partial_order_names) != len(uncovered_ordered_elements): + raise ValueError("Partial order must not contain duplicate elements") + + # replace ... with [], which is where we'll put the remaining axes + + out_order = [[axis_name(a)] if a is not ... else [] for a in partial_order] + + # now we'll fill in the ordered elements + target_pos = index_where(lambda x: x == [], out_order) + + for ax in axes: + ax_name = axis_name(ax) + if ax_name in uncovered_ordered_elements: + uncovered_ordered_elements.remove(ax_name) + # already in the right place + # update target_pos to come after this if possible + try: + this_pos = index_where(lambda x: ax_name in x, out_order) + # find first empty slot after this_pos. prefer not to go backwards + this_pos = max(this_pos + 1, target_pos) + target_pos = index_where(lambda x: x == [], out_order, start=this_pos) + except ValueError: + # leave it where it is + pass + elif ax_name in partial_order_names: + raise ValueError(f"Axis {ax_name} appears multiple times in the partial order") + else: + # this can appear in any ... slot. our heuristic is to put it in the first + # slot that comes after the most recently seen ordered element + out_order[target_pos].append(ax_name) + + if len(uncovered_ordered_elements) > 0: + raise ValueError(f"The following axes are not present in output: {' '.join(uncovered_ordered_elements)}") + + # now we have a list of lists of axis names. we need to flatten it and convert to axes + return tuple(as_axis(name) for name in sum(out_order, [])) + + +def replace_missing_with_ellipsis(ax1: AxisSelection, ax2: AxisSelection) -> PartialAxisSpec: + """Returns ax1, except that: + + * any axis not in ax2 is replaced with Ellipsis + * if ax1 has a str axis where ax2 has an Axis, then it is replaced with the Axis + + Raises if ax1 and ax2 have any axes with the same name but different sizes + """ + ax2_dict = axis_spec_to_shape_dict(ax2) + out: List[AxisSelector | EllipsisType] = [] + ax1 = ensure_tuple(ax1) + + for ax in ax1: + if isinstance(ax, Axis): + if ax.name in ax2_dict: + sz = ax2_dict[ax.name] + if sz is not None and sz != ax.size: + raise ValueError(f"Axis {ax.name} has different sizes in {ax1} and {ax2}") + out.append(ax) + else: + out.append(Ellipsis) + elif isinstance(ax, str): + if ax in ax2_dict: + ax_sz = ax2_dict[ax] + if ax_sz is not None: + out.append(Axis(ax, ax_sz)) + else: + out.append(ax) + else: + out.append(Ellipsis) + else: + raise ValueError(f"Invalid axis spec: {ax}") + + return tuple(out) + + __all__ = [ "Axis", "AxisSelector", "AxisSelection", "AxisSpec", + "PartialAxisSpec", + "PartialShapeDict", + "ShapeDict", "axis_name", "concat_axes", "union_axes", @@ -412,4 +538,5 @@ __all__ = [ "union_axes", "without_axes", "unsize_axes", + "rearrange_for_partial_order", ] diff --git a/src/haliax/core.py b/src/haliax/core.py index e5f45b5..9618394 100644 --- a/src/haliax/core.py +++ b/src/haliax/core.py @@ -5,7 +5,7 @@ import warnings from dataclasses import dataclass from math import prod from types import EllipsisType -from typing import Any, Dict, List, Mapping, Optional, Sequence, Tuple, Union, overload +from typing import Any, Callable, Dict, List, Mapping, Optional, Sequence, Tuple, Union, overload import jax import jax.numpy as jnp @@ -29,7 +29,7 @@ from .axis import ( selects_axis, union_axes, ) -from .types import IntScalar, PrecisionLike, Scalar +from .types import DTypeLike, IntScalar, PrecisionLike, Scalar NamedOrNumeric = Union[Scalar, "NamedArray"] @@ -109,6 +109,16 @@ class NamedArray: raise ValueError(f"Expected scalar, got {self.array.ndim}-dimensional array") return self.array + def __jax_array__(self): + if self.ndim == 0: + return self.array + else: + raise ValueError( + "Only scalar NamedArrays can be implicitly converted to jax arrays, but " + f"got {self.shape} array. This error typically occurs when you pass a " + "NamedArray to a plain jax.numpy function. Please use `x.array` instead." + ) + @ft.cached_property def shape(self) -> Dict[str, int]: return {axis.name: axis.size for axis in self.axes} @@ -301,13 +311,13 @@ class NamedArray: def slice( self, axis: AxisSelector, new_axis: Optional[AxisSelector] = None, start: int = 0, length: Optional[int] = None ) -> "NamedArray": - pass + ... @typing.overload def slice( self, start: Mapping[AxisSelector, int], length: Mapping[AxisSelector, Union[int, Axis]] ) -> "NamedArray": - pass + ... def slice(self, *args, **kwargs) -> "NamedArray": return haliax.slice(self, *args, **kwargs) @@ -319,20 +329,18 @@ class NamedArray: return haliax.take(self, axis=axis, index=index) @overload - def __getitem__(self, item: Tuple[AxisSelector, NamedIndex]) -> Union["NamedArray", Scalar]: - ... # pragma: no cover + def __getitem__(self, item: Tuple[AxisSelector, NamedIndex]) -> "NamedArray": + ... @overload - def __getitem__( - self, item: Tuple[AxisSelector, NamedIndex, AxisSelector, NamedIndex] - ) -> Union["NamedArray", jnp.ndarray]: + def __getitem__(self, item: Tuple[AxisSelector, NamedIndex, AxisSelector, NamedIndex]) -> "NamedArray": ... @overload - def __getitem__(self, item: Mapping[AxisSelector, NamedIndex]) -> Union["NamedArray", jnp.ndarray]: + def __getitem__(self, item: Mapping[AxisSelector, NamedIndex]) -> "NamedArray": ... - def __getitem__(self, idx) -> Union["NamedArray", jnp.ndarray]: + def __getitem__(self, idx) -> "NamedArray": """Syntactic sugar for [haliax.index][], which is the actual implementation. Supports indexing like: @@ -369,17 +377,16 @@ class NamedArray: return index(self, idx) # np.ndarray methods: - def all(self, axis: Optional[AxisSelection] = None) -> "NamedArray": - return haliax.all(self, axis=axis) + def all(self, axis: Optional[AxisSelection] = None, *, where: Optional["NamedArray"] = None) -> "NamedArray": + return haliax.all(self, axis=axis, where=where) - def any(self, axis: Optional[AxisSelection] = None) -> "NamedArray": - return haliax.any(self, axis=axis) + def any(self, axis: Optional[AxisSelection] = None, *, where: Optional["NamedArray"] = None) -> "NamedArray": + return haliax.any(self, axis=axis, where=where) - # TODO: test - def argmax(self, axis: AxisSelector) -> "NamedArray": + def argmax(self, axis: Optional[AxisSelector] = None) -> "NamedArray": return haliax.argmax(self, axis=axis) - def argmin(self, axis: AxisSelector) -> "NamedArray": + def argmin(self, axis: Optional[AxisSelector]) -> "NamedArray": return haliax.argmin(self, axis=axis) def argsort(self, axis: AxisSelector) -> "NamedArray": @@ -400,57 +407,54 @@ class NamedArray: def copy(self) -> "NamedArray": return NamedArray(self.array.copy(), self.axes) - def cumprod(self, axis: Optional[AxisSelector] = None, *, dtype=None) -> "NamedArray": + def cumprod(self, axis: AxisSelector, *, dtype=None) -> "NamedArray": return haliax.cumprod(self, axis=axis, dtype=dtype) - def cumsum(self, axis: Optional[AxisSelector] = None, *, dtype=None) -> "NamedArray": + def cumsum(self, axis: AxisSelector, *, dtype=None) -> "NamedArray": return haliax.cumsum(self, axis=axis, dtype=dtype) - def dot(self, axis: AxisSelection, b, *, precision: PrecisionLike = None) -> "NamedArray": - return dot(axis, self, b, precision=precision) + # Deprecated overload + @typing.overload + def dot(self, axis: Optional[AxisSelection], *b, precision: PrecisionLike = None) -> "NamedArray": + ... + + @typing.overload + def dot(self, *args, axis: Optional[AxisSelection], precision: PrecisionLike = None) -> "NamedArray": + ... + + def dot(self, *args, **kwargs) -> "NamedArray": + if "axis" in kwargs or len(args) == 0: + return haliax.dot(self, *args, **kwargs) + else: + axis = args[0] + args = args[1:] + # We want to get the deprecation warning for this style + return haliax.dot(axis, self, *args, **kwargs) @property def imag(self) -> "NamedArray": return NamedArray(self.array.imag, self.axes) - def max( - self, - axis: Optional[AxisSelection] = None, - *, - where=None, - ) -> "NamedArray": + def max(self, axis: Optional[AxisSelection] = None, *, where=None) -> "NamedArray": return haliax.max(self, axis=axis, where=where) def mean( - self, - axis: Optional[AxisSelection] = None, - *, - dtype=None, - where=None, + self, axis: Optional[AxisSelection] = None, *, dtype=None, where: Optional["NamedArray"] = None ) -> "NamedArray": return haliax.mean(self, axis=axis, dtype=dtype, where=where) - def min( - self, - axis: Optional[AxisSelection] = None, - *, - where=None, - ) -> "NamedArray": + def min(self, axis: Optional[AxisSelection] = None, *, where: Optional["NamedArray"] = None) -> "NamedArray": return haliax.min(self, axis=axis, where=where) def prod( - self, - axis: Optional[AxisSelection] = None, - *, - dtype=None, - where=None, + self, axis: Optional[AxisSelection] = None, *, dtype=None, where: Optional["NamedArray"] = None ) -> "NamedArray": - return haliax.prod( - self, - axis=axis, - dtype=dtype, - where=where, - ) + return haliax.prod(self, axis=axis, dtype=dtype, where=where) + + def product( + self, axis: Optional[AxisSelection] = None, *, dtype=None, where: Optional["NamedArray"] = None + ) -> "NamedArray": + return haliax.product(self, axis=axis, dtype=dtype, where=where) def ptp(self, axis: Optional[AxisSelection] = None) -> "NamedArray": return haliax.ptp(self, axis=axis) @@ -465,15 +469,13 @@ class NamedArray: def sort(self, axis: AxisSelector) -> Any: return haliax.sort(self, axis=axis) - def std(self, axis: Optional[AxisSelection] = None, *, dtype=None, ddof=0, where=None) -> "NamedArray": + def std( + self, axis: Optional[AxisSelection] = None, *, dtype=None, ddof=0, where: Optional["NamedArray"] = None + ) -> "NamedArray": return haliax.std(self, axis=axis, dtype=dtype, ddof=ddof, where=where) def sum( - self, - axis: Optional[AxisSelection] = None, - *, - dtype=None, - where=None, + self, axis: Optional[AxisSelection] = None, *, dtype=None, where: Optional["NamedArray"] = None ) -> "NamedArray": return haliax.sum( self, @@ -492,20 +494,9 @@ class NamedArray: return haliax.trace(self, offset=offset, axis1=axis1, axis2=axis2, dtype=dtype) def var( - self, - axis: Optional[AxisSelection] = None, - dtype=None, - ddof=0, - *, - where=None, + self, axis: Optional[AxisSelection] = None, dtype=None, ddof=0, *, where: Optional["NamedArray"] = None ) -> "NamedArray": - return haliax.var( - self, - axis=axis, - dtype=dtype, - ddof=ddof, - where=where, - ) + return haliax.var(self, axis=axis, dtype=dtype, ddof=ddof, where=where) # operators @@ -521,6 +512,7 @@ class NamedArray: # types when they're in PyTrees if self.array is None: return other.array is None + if hasattr(other, "array") and other.array is None: return False @@ -880,7 +872,7 @@ def updated_slice( return NamedArray(updated, array.axes) -def index(array: NamedArray, slices: Mapping[AxisSelector, NamedIndex]) -> Union[NamedArray, Scalar]: +def index(array: NamedArray, slices: Mapping[AxisSelector, NamedIndex]) -> NamedArray: """ Selects elements from an array along an axis via index or another named array. @@ -976,64 +968,9 @@ def index(array: NamedArray, slices: Mapping[AxisSelector, NamedIndex]) -> Union ordered_slices[i] = py_slice(None, None, None) sliced = sliced[tuple(ordered_slices)] - - if len(new_axes) == 0: - # this is a scalar - return sliced - return haliax.named(sliced, new_axes) -def dot(axis: AxisSelection, *arrays: NamedArray, precision: PrecisionLike = None) -> NamedArray: - """Returns the tensor product of two NamedArrays. The axes `axis` are contracted over, - and any other axes that are shared between the arrays are batched over. Non-contracted Axes in one - that are not in the other are preserved. - - Args: - axis (AxisSelection): The axes to contract over. - *arrays (NamedArray): The arrays to contract. - precision (PrecisionLike, optional): The precision to use. Defaults to None. This argument is passed to `jax.numpy.einsum`, - which in turn passes it to jax.lax.dot_general. - - Returns: - NamedArray: The result of the contraction. - """ - _ensure_no_mismatched_axes(*arrays) - output_axes: Tuple[Axis, ...] = ft.reduce(union_axes, (a.axes for a in arrays), ()) # type: ignore - output_axes = eliminate_axes(output_axes, axis) - - axis = ensure_tuple(axis) - - array_specs = [] - - next_index = 0 - axis_mappings: Dict[str, int] = {} - - for a in arrays: - spec = "" - for ax in a.axes: - if ax.name in axis_mappings: - spec += f"{axis_mappings[ax.name]} " - else: - axis_mappings[ax.name] = next_index - spec += f"{next_index} " - next_index += 1 - - array_specs.append(spec) - - # now compute the output axes: - output_spec = " ".join(str(axis_mappings[ax.name]) for ax in output_axes) - - output = jnp.einsum( - ", ".join(array_specs) + "-> " + output_spec, - *[a.array for a in arrays], - precision=precision, - ) - - out = NamedArray(output, output_axes) - return haliax.shard(out) - - def split(a: NamedArray, axis: AxisSelector, new_axes: Sequence[Axis]) -> Sequence[NamedArray]: """ Splits an array along an axis into multiple arrays, one for each element of new_axes. @@ -1079,7 +1016,7 @@ def unbind(array: NamedArray, axis: AxisSelector) -> List[NamedArray]: axis_size = array.axes[axis_index].size arrays = [jnp.take(array.array, i, axis=axis_index) for i in range(axis_size)] - return [haliax.shard(NamedArray(a, new_axes)) for a in arrays] + return [haliax.auto_sharded(NamedArray(a, new_axes)) for a in arrays] def roll(array: NamedArray, shift: Union[int, Tuple[int, ...]], axis: AxisSelection) -> NamedArray: @@ -1135,16 +1072,19 @@ def flatten_axes(array: NamedArray, old_axes: AxisSelection, new_axis: AxisSelec """ old_axes = ensure_tuple(old_axes) old_axes = array.resolve_axis(old_axes) - - if len(old_axes) == 0: - raise ValueError("Must specify at least one axis to merge") + total_axis_size = prod(array.axis_size(ax) for ax in old_axes) if isinstance(new_axis, Axis): - if new_axis.size != prod(array.axis_size(ax) for ax in old_axes): + if new_axis.size != total_axis_size: raise ValueError(f"Cannot merge {old_axes} into {new_axis}: size mismatch") else: assert isinstance(new_axis, str) - new_axis = Axis(new_axis, prod(ax.size for ax in old_axes)) + new_axis = Axis(new_axis, total_axis_size) + + if len(old_axes) == 0: + # just unsqueeze the array + new_array = jnp.expand_dims(array.array, axis=0) + return NamedArray(new_array, (new_axis,) + array.axes) # ensure that the old_axes are contiguous # we basically ensure that the old_axes occur after the index of the first old_axis @@ -1212,7 +1152,7 @@ def flatten(array: NamedArray, new_axis_name: AxisSelector) -> NamedArray: return ravel(array, new_axis_name) -def named(a: jnp.ndarray, axis: AxisSelection) -> NamedArray: +def named(a, axis: AxisSelection) -> NamedArray: """Creates a NamedArray from a numpy array and a list of axes.""" a = jnp.asarray(a) axes = check_shape(a.shape, axis) @@ -1392,18 +1332,17 @@ def broadcast_arrays_and_return_axes( """ Broadcasts a sequence of arrays to a common set of axes. - Parameters - ---------- - arrays: NamedArray - The arrays to broadcast - require_subset: bool - If True, then one of the arrays must be a subset of the other. This is a bit stricter than numpy's broadcasting - rules, but I've been bitten by numpy's rules too many times. False is looser than numpy's rules, and allows - broadcasting any pair of arrays (so long as the axes don't overtly conflict with different sizes for the same - name.) - ensure_order: bool - If True, then the returned arrays will have the same axes in the same order as the given axes. Otherwise, the - axes may not be moved. + Args: + arrays: NamedArray + The arrays to broadcast + require_subset: bool + If True, then one of the arrays must be a subset of the other. This is a bit stricter than numpy's broadcasting + rules, but I've been bitten by numpy's rules too many times. False is looser than numpy's rules, and allows + broadcasting any pair of arrays (so long as the axes don't overtly conflict with different sizes for the same + name.) + ensure_order: bool + If True, then the returned arrays will have the same axes in the same order as the given axes. Otherwise, the + axes may not be moved. """ if len(arrays) == 0: return ((), ()) @@ -1458,24 +1397,50 @@ def check_shape(jnp_shape: Sequence[int], hax_axes: AxisSelection) -> Tuple[Axis return tuple(result_axes) -def _ensure_no_mismatched_axes(*arrays: NamedArray): - """Ensure that all the arrays have no axes with the same name but different sizes""" - if len(arrays) <= 1: - return +def flatten_all_axes_but( + a: NamedArray, axis_name: str, axis: AxisSelection, reorder_to_front: bool = False +) -> tuple[NamedArray, Callable[[NamedArray], NamedArray]]: + """ + Flattens all axes of `a` except for `axes`. + The flattened axes are merged into a single axis with the name `axis_name`. - known_sizes: dict[str, int] = {} - for a in arrays: - for ax in a.axes: - if ax.name in known_sizes: - if known_sizes[ax.name] != ax.size: - raise ValueError(f"Axis {ax.name} has multiple sizes: {known_sizes[ax.name]} and {ax.size}") - else: - known_sizes[ax.name] = ax.size + Also returns a function to restore the original axes. This function takes a NamedArray with at least the flattened axes + and returns a NamedArray with an order that is broadly consistent with the original order of the axes. + + On TPU, this operation should be free as long as this doesn't impact the last two dims. + + Usually you can just use vmap, but sometimes you actually want there to be exactly 1 batch axis, + or it's a pain to do a bunch of vmaps + + """ + + result = a.flatten_axes(axis, axis_name) + + if reorder_to_front: + result = result.rearrange((axis_name, ...)) + + old_axes = a.axes + axis = a.resolve_axis(axis) + + del a + + def unflatten(new_a: NamedArray) -> NamedArray: + # we want to restore the array to an order that is as consistent as possible with the original order + new_a = new_a.unflatten_axis(axis_name, axis) + if new_a.axes == old_axes: + return new_a + + axes_from_first_array_present_in_new = haliax.axis.replace_missing_with_ellipsis( + haliax.axis_name(old_axes), new_a.axes + ) + out_axes = haliax.axis.rearrange_for_partial_order(axes_from_first_array_present_in_new, new_a.axes) + return new_a.rearrange(out_axes) + + return result, unflatten __all__ = [ "NamedArray", - "dot", "named", "slice", "updated_slice", @@ -1495,4 +1460,5 @@ __all__ = [ "enable_shape_checks", "are_shape_checks_enabled", "check_shape", + "flatten_all_axes_but", ] diff --git a/src/haliax/jax_utils.py b/src/haliax/jax_utils.py index cf510c9..9f66d9a 100644 --- a/src/haliax/jax_utils.py +++ b/src/haliax/jax_utils.py @@ -80,7 +80,7 @@ def is_jax_array_like(x): # adapted from jax but exposed so i can use it -def broadcast_prefix(prefix_tree: Any, full_tree: Any, is_leaf: Optional[Callable[[Any], bool]] = None) -> List[Any]: +def broadcast_prefix(prefix_tree: Any, full_tree: Any, is_leaf: Optional[Callable[[Any], bool]] = None): """Broadcast a prefix tree to match the structure of a full tree.""" result = [] num_leaves = lambda t: jax.tree_util.tree_structure(t).num_leaves # noqa: E731 diff --git a/src/haliax/nn/__init__.py b/src/haliax/nn/__init__.py index a779cee..41e64fa 100644 --- a/src/haliax/nn/__init__.py +++ b/src/haliax/nn/__init__.py @@ -1,7 +1,3 @@ -import functools -import warnings -from typing import Optional, Tuple, Union - import jax.nn as jnn import jax.numpy as jnp @@ -11,10 +7,8 @@ import haliax.nn.activations import haliax.nn.attention as attention import haliax.nn.normalization -from ..axis import Axis, AxisSelector +from ..axis import Axis from ..core import NamedArray -from ..util import UNSPECIFIED, Unspecified -from ..wrap import ReductionFunction from .activations import ( celu, elu, @@ -40,6 +34,7 @@ from .conv import Conv, ConvTranspose from .dropout import Dropout, dropout from .embedding import Embedding from .linear import Linear +from .loss import binary_cross_entropy_loss, cross_entropy_loss, cross_entropy_loss_and_log_normalizers from .mlp import MLP from .normalization import LayerNorm, log_softmax, logsumexp, softmax, standardize from .pool import max_pool, mean_pool, min_pool @@ -49,70 +44,37 @@ from .scan import Stacked # TODO: support where in softmax, etc -@functools.wraps(jnn.one_hot) -def one_hot(x: Union[NamedArray, int], class_axis: Axis, *, dtype=None) -> NamedArray: +def one_hot(x: NamedArray | int, class_axis: Axis, *, dtype=None) -> NamedArray: + """ + Convert an integer to a one-hot vector. This is basically a generalization of [jax.nn.one_hot][] + for NamedArrays. + + Args: + x: the integer or NamedArray of integers to convert + class_axis: the axis to convert to one-hot + dtype: the dtype of the result. If None, it will default to jax's default (currently float_) + Returns: + a NamedArray with the same axes as `x` plus `class_axis`, with 1s in the appropriate places + """ if isinstance(x, NamedArray): array = jnn.one_hot(x.array, num_classes=class_axis.size, dtype=dtype) - return NamedArray(array, x.axes + (class_axis,)) + return hax.auto_sharded(hax.named(array, x.axes + (class_axis,))) else: assert isinstance(x, int) assert class_axis.size > x >= -class_axis.size - array = jnp.zeros(class_axis.size, dtype=dtype).at[x].set(1) - return haliax.named(array, class_axis) - - -def cross_entropy_loss( - pred_y: NamedArray, - Label: AxisSelector, - target_y: NamedArray, - reduction: Optional[ReductionFunction] | Unspecified = UNSPECIFIED, - where: Optional[NamedArray] = None, - reduction_axis: Optional[AxisSelector] = None, -) -> NamedArray: - loss, _ = cross_entropy_loss_and_log_normalizers(pred_y, Label, target_y) - - # if target_y isn't some kind of floating point, something is wrong, so warn - if not jnp.issubdtype(target_y.dtype, jnp.floating): - warnings.warn( - f"target_y has dtype {target_y.dtype}, which is not a floating point type. This is probably a mistake." - ) - - if reduction is not None: - if reduction is UNSPECIFIED: - reduction = haliax.mean - loss = reduction(loss, where=where, axis=reduction_axis) - elif where is not None: - loss = hax.where(where, loss, 0) - - return loss - - -def cross_entropy_loss_and_log_normalizers( - pred_y: NamedArray, - Label: AxisSelector, - target_y: NamedArray, -) -> Tuple[NamedArray, NamedArray]: - """ - Compute the cross entropy loss and log normalizers for a batch of predictions and targets. - - :param pred_y: a NamedArray with the Label axis (and possibly others for e.g. batch and seq) containing the logits - :param Label: the Label axis - :param target_y: a NamedArray with the Label axis (and possibly others) containing the targets - - :return: tuple of two named arrays, with "per position" losses and log normalizers - """ - log_normalizers = haliax.nn.normalization.logsumexp(pred_y, Label) - neg_log_normalized = log_normalizers - pred_y - - loss = hax.dot(Label, target_y, neg_log_normalized) + one = 1 + if dtype is not None: + one = dtype(one) - return loss, log_normalizers + array = jnp.zeros(class_axis.size, dtype=dtype).at[x].set(one) + return hax.auto_sharded(haliax.named(array, class_axis)) __all__ = [ "attention", "one_hot", + "binary_cross_entropy_loss", "cross_entropy_loss", "cross_entropy_loss_and_log_normalizers", "Conv", diff --git a/src/haliax/nn/attention.py b/src/haliax/nn/attention.py index ccbe909..6e2f5f4 100644 --- a/src/haliax/nn/attention.py +++ b/src/haliax/nn/attention.py @@ -57,7 +57,7 @@ def dot_product_attention_weights( query = query.astype(attention_dtype) key = key.astype(attention_dtype) - weights = haliax.dot(Key, query, key, precision=precision) + weights = haliax.dot(query, key, precision=precision, axis=Key) if bias is not None: weights = weights + bias @@ -115,7 +115,7 @@ def dot_product_attention( Key, KPos, query, key, mask=mask, bias=bias, attention_dtype=attention_dtype, precision=precision ) - return haliax.dot(KPos, weights, value) + return haliax.dot(weights, value, axis=KPos) def self_attention( diff --git a/src/haliax/nn/conv.py b/src/haliax/nn/conv.py index 88e70ce..a1ea779 100644 --- a/src/haliax/nn/conv.py +++ b/src/haliax/nn/conv.py @@ -192,27 +192,22 @@ class Conv(_ConvBase): # jax's conv_general_dilated only supports exactly one batch dimension (not 0), so we vmap over any others. # We could choose instead to flatten them, but then we'd definitely lose sharding. batch_dims = without_axes(inputs.axes, self.weight.axes) - x = _vmap_all_but_one_batch_dim(self._do_conv, batch_dims)(inputs) + flat_inputs, unflatten = haliax.core.flatten_all_axes_but( + inputs, "__batch__", batch_dims, reorder_to_front=True + ) + x = self._do_conv(flat_inputs) + x = unflatten(x) if self.bias is not None: x = x + self.bias - output_axes = _compute_output_axes(inputs, batch_dims, self.In, self.Out) - x = x.rearrange(output_axes) - return x def _do_conv(self, inputs): - batch_dims = without_axes(inputs.axes, self.weight.axes) - output_axes = _compute_output_axes(inputs, batch_dims, self.In, self.Out) + # _do_conv expects there ot be a single __batch__ dimension + output_axes = _compute_output_axes(inputs, "__batch__", self.In, self.Out) - if len(batch_dims) == 1: - batch_index = inputs.axes.index(batch_dims[0]) - else: - assert len(batch_dims) == 0 - # there must be a batch dimension, even if it's size 1 - inputs = inputs.broadcast_axis(Axis("__batch__", 1)) - batch_index = 0 + batch_index = _index_of_name(inputs.axes, "__batch__") lhs_dim_spec = self._lhs_dim_spec(batch_index, inputs) rhs_dim_spec = self._weight_dim_spec @@ -227,9 +222,6 @@ class Conv(_ConvBase): dimension_numbers=(lhs_dim_spec, rhs_dim_spec, output_dim_spec), ) - if len(batch_dims) == 0: - x = x.squeeze(0) - return named(x, output_axes) @@ -334,7 +326,11 @@ class ConvTranspose(_ConvBase): del key batch_dims = without_axes(inputs.axes, self.weight.axes) - x = _vmap_all_but_one_batch_dim(self._do_conv, batch_dims)(inputs) + flat_inputs, unflatten = haliax.core.flatten_all_axes_but( + inputs, "__batch__", batch_dims, reorder_to_front=True + ) + x = self._do_conv(flat_inputs) + x = unflatten(x) if self.bias is not None: x = x + self.bias @@ -344,23 +340,15 @@ class ConvTranspose(_ConvBase): return x.rearrange(output_axes) def _do_conv(self, inputs): - batch_dims = without_axes(inputs.axes, self.weight.axes) - output_axes = _compute_output_axes(inputs, batch_dims, self.In, self.Out) - - if len(batch_dims) == 1: - batch_index = inputs.axes.index(batch_dims[0]) - else: - assert len(batch_dims) == 0 - # there must be a batch dimension, even if it's size 1 - inputs = inputs.broadcast_axis(Axis("__batch__", 1)) - batch_index = 0 - # cribbed from Equinox's ConvTranspose class padding = tuple( (d * (k - 1) - p0, d * (k - 1) - p1 + o) for k, (p0, p1), o, d in zip(self.kernel_size, self.padding, self.output_padding, self.dilation) ) + output_axes = _compute_output_axes(inputs, "__batch__", self.In, self.Out) + batch_index = _index_of_name(inputs.axes, "__batch__") + lhs_dim_spec = self._lhs_dim_spec(batch_index, inputs) rhs_dim_spec = self._weight_dim_spec output_dim_spec = lhs_dim_spec @@ -376,9 +364,6 @@ class ConvTranspose(_ConvBase): dimension_numbers=(lhs_dim_spec, rhs_dim_spec, output_dim_spec), ) - if len(batch_dims) == 0: - x = x.squeeze(0) - return named(x, output_axes) @@ -397,7 +382,7 @@ def _convert_padding_spec(Spatial, padding): padding = ((padding, padding),) * len(Spatial) elif isinstance(padding, tuple): padding = _expand_and_check_shape(len(Spatial), padding, "padding") - padding_spec = [] + padding_spec: list = [] for p in padding: if isinstance(p, int): padding_spec.append((p, p)) @@ -422,21 +407,6 @@ def _index_of_name(names: Sequence[str | Axis], name) -> int: return -1 -def _vmap_all_but_one_batch_dim(op, batch_dims): - batch_dims = list(batch_dims) - # We want to prioritize vmapping over *sharded* batch dimensions (TODO: make sure this is correct) - # TODO: I think we may need to do shard_map or something to make sure we don't lose sharding - sharded_batch_dims = [ax for ax in batch_dims if haliax.partitioning.physical_axis_name(ax) is not None] - while len(sharded_batch_dims) > 1: - dim = sharded_batch_dims.pop() - batch_dims.remove(dim) - op = haliax.vmap(op, axis=dim.name) - while len(batch_dims) > 1: - dim = batch_dims.pop() - op = haliax.vmap(op, axis=dim.name) - return op - - def _compute_output_axes(inputs, batch_dims, In, Out): """ Does two things: diff --git a/src/haliax/nn/dropout.py b/src/haliax/nn/dropout.py index ca0c233..ad1da1e 100644 --- a/src/haliax/nn/dropout.py +++ b/src/haliax/nn/dropout.py @@ -44,7 +44,7 @@ def dropout(x, pdrop, broadcast_axes=None, *, inference, key=None): shape_to_generate = tuple(ax for ax in x.axes if ax not in axes) q = 1 - pdrop - mask = haliax.random.bernoulli(key, shape_to_generate, q) + mask: NamedArray = haliax.random.bernoulli(key, shape_to_generate, q) q = x.dtype.type(q) out = haliax.where(mask, x / q, 0) diff --git a/src/haliax/nn/embedding.py b/src/haliax/nn/embedding.py index 561c10f..39169d3 100644 --- a/src/haliax/nn/embedding.py +++ b/src/haliax/nn/embedding.py @@ -6,10 +6,11 @@ from jaxtyping import PRNGKeyArray import haliax as hax -from ..axis import Axis +from ..axis import Axis, AxisSpec from ..core import NamedArray from ..jax_utils import named_call from ..tree_util import resize_axis +from ..util import ensure_tuple class Embedding(eqx.Module): @@ -17,24 +18,24 @@ class Embedding(eqx.Module): # axes Vocab: Axis = eqx.static_field() - Embed: Axis = eqx.static_field() + Embed: AxisSpec = eqx.static_field() - # TODO: should allow axisspec for Embed @staticmethod - def init(Vocab: Axis, Embed: Axis, initializer_range: float = 0.02, *, key): - weight = hax.random.normal(key, (Vocab, Embed)) * initializer_range + def init(Vocab: Axis, Embed: AxisSpec, initializer_range: float = 0.02, *, key): + all_axes = (Vocab,) + ensure_tuple(Embed) + weight = hax.random.normal(key, all_axes) * initializer_range return Embedding(weight=weight, Vocab=Vocab, Embed=Embed) - @named_call def __call__(self, input_ids, *, key: Optional[PRNGKeyArray] = None): return self.embed(input_ids) + @named_call def embed(self, input_ids): input_embeds = self.weight.take(self.Vocab, input_ids) return input_embeds def unembed(self, input_embeds): - return input_embeds.dot(self.Embed, self.weight) + return input_embeds.dot(self.weight, axis=self.Embed) def resize_embeddings(self, new_size: int, key: Optional[PRNGKeyArray] = None): new_weights = resize_axis(self.weight, self.Vocab, new_size, key=key) diff --git a/src/haliax/nn/linear.py b/src/haliax/nn/linear.py index bbd924e..0c3e2d5 100644 --- a/src/haliax/nn/linear.py +++ b/src/haliax/nn/linear.py @@ -44,12 +44,12 @@ class Linear(eqx.Module): key: Not used, but there for compat with other modules """ del key - q = inputs.dot(self.In, self.weight) - q = hax.shard(q) + q = inputs.dot(self.weight, axis=self.In) + q = hax.auto_sharded(q) if self.bias is not None: q = q + self.bias - q = hax.shard(q) + q = hax.auto_sharded(q) return q diff --git a/src/haliax/nn/loss.py b/src/haliax/nn/loss.py new file mode 100644 index 0000000..0db9ced --- /dev/null +++ b/src/haliax/nn/loss.py @@ -0,0 +1,131 @@ +import typing +import warnings +from typing import Optional + +from jax import numpy as jnp + +import haliax as hax +from haliax.axis import AxisSelection, AxisSelector +from haliax.core import NamedArray +from haliax.util import UNSPECIFIED, Unspecified +from haliax.wrap import ReductionFunction + + +@typing.overload +def cross_entropy_loss( + logits: NamedArray, + Label: AxisSelector, + targets: NamedArray, + reduction: Optional[ReductionFunction] | Unspecified = UNSPECIFIED, + where: Optional[NamedArray] = None, + reduction_axis: None = None, +) -> jnp.ndarray | NamedArray: + ... + + +@typing.overload +def cross_entropy_loss( + logits: NamedArray, + Label: AxisSelector, + targets: NamedArray, + reduction: Optional[ReductionFunction] | Unspecified = UNSPECIFIED, + where: Optional[NamedArray] = None, + reduction_axis: AxisSelection = ..., +) -> NamedArray: + ... + + +def cross_entropy_loss( + logits: NamedArray, + Label: AxisSelector, + targets: NamedArray, + reduction: Optional[ReductionFunction] | Unspecified = UNSPECIFIED, + where: Optional[NamedArray] = None, + reduction_axis: Optional[AxisSelection] = None, +) -> jnp.ndarray | NamedArray: + loss, _ = cross_entropy_loss_and_log_normalizers(logits, Label, targets) + + # if target_y isn't some kind of floating point, something is wrong, so warn + if not jnp.issubdtype(targets.dtype, jnp.floating): + warnings.warn( + f"target_y has dtype {targets.dtype}, which is not a floating point type. This is probably a mistake." + ) + + loss = maybe_reduce_loss(loss, reduction, reduction_axis, where) + + return loss + + +@typing.overload +def binary_cross_entropy_loss( + logits: NamedArray, + targets: NamedArray, + reduction: Optional[ReductionFunction] | Unspecified = UNSPECIFIED, + where: Optional[NamedArray] = None, + reduction_axis: None = None, +) -> jnp.ndarray | NamedArray: + ... + + +@typing.overload +def binary_cross_entropy_loss( + logits: NamedArray, + targets: NamedArray, + reduction: Optional[ReductionFunction] | Unspecified = UNSPECIFIED, + where: Optional[NamedArray] = None, + reduction_axis: AxisSelection = ..., +) -> NamedArray: + ... + + +def binary_cross_entropy_loss( + logits: NamedArray, + targets: NamedArray, + reduction: Optional[ReductionFunction] | Unspecified = UNSPECIFIED, + where: Optional[NamedArray] = None, + reduction_axis: Optional[AxisSelection] = None, +) -> jnp.ndarray | NamedArray: + log_p = hax.nn.log_sigmoid(logits) + log_not_p = hax.nn.log_sigmoid(-logits) # == log(1-sigmoid(x)) + targets = targets.astype(logits.dtype) + loss = -targets * log_p - (1.0 - targets) * log_not_p + + loss = maybe_reduce_loss(loss, reduction, reduction_axis, where) + return loss + + +def maybe_reduce_loss( + arr, + reduction: Optional[ReductionFunction] | Unspecified, + reduction_axis: Optional[AxisSelection], + where: Optional[NamedArray], +): + if reduction is not None and reduction_axis != (): + if reduction is UNSPECIFIED: + reduction = hax.mean + arr = reduction(arr, where=where, axis=reduction_axis) + elif where is not None: + arr = hax.where(where, arr, 0) + return arr + + +def cross_entropy_loss_and_log_normalizers( + pred_y: NamedArray, + Label: AxisSelector, + target_y: NamedArray, +) -> tuple[NamedArray, NamedArray]: + """ + Compute the cross entropy loss and log normalizers for a batch of predictions and targets. + + :param pred_y: a NamedArray with the Label axis (and possibly others for e.g. batch and seq) containing the logits + :param Label: the Label axis + :param target_y: a NamedArray with the Label axis (and possibly others) containing the targets + + :return: tuple of two named arrays, with "per position" losses and log normalizers + """ + log_normalizers = hax.nn.logsumexp(pred_y, Label) + neg_log_normalized = log_normalizers - pred_y + + loss = hax.dot(target_y, neg_log_normalized, axis=Label) + + return loss, log_normalizers diff --git a/src/haliax/nn/pool.py b/src/haliax/nn/pool.py index c504520..9aa5597 100644 --- a/src/haliax/nn/pool.py +++ b/src/haliax/nn/pool.py @@ -8,6 +8,7 @@ import haliax from ..axis import AxisSpec, axis_spec_to_shape_dict, unsize_axes from ..core import NamedArray +from ..partitioning import auto_sharded from ..types import Scalar from ..util import ensure_tuple @@ -123,7 +124,7 @@ def pool( out_axes = unsize_axes(inputs.axes, Window) - return haliax.named(y, out_axes) + return auto_sharded(haliax.named(y, out_axes)) def _patch_up_reduce_fn(reduce_fn): diff --git a/src/haliax/nn/scan.py b/src/haliax/nn/scan.py index f9750c3..8d5ecad 100644 --- a/src/haliax/nn/scan.py +++ b/src/haliax/nn/scan.py @@ -70,7 +70,7 @@ class Stacked(eqx.Module, Generic[M]): @staticmethod def init( - Block: Axis, module: Type[M], *, gradient_checkpointing: bool = False, prevent_cse: bool = True + Block: Axis, module: Type[M], *, gradient_checkpointing: bool = False, prevent_cse: bool = False ) -> ModuleInit["Stacked[M]"]: """ Initialize a Stacked module. This method is curried: you can pass in the Block and module, and it will return @@ -98,7 +98,7 @@ class Stacked(eqx.Module, Generic[M]): def fold(self, init, *args, **kwargs): if self.gradient_checkpointing: - do_block = filter_checkpoint(self._do_block) + do_block = filter_checkpoint(self._do_block, prevent_cse=self.prevent_cse) else: do_block = self._do_block diff --git a/src/haliax/partitioning.py b/src/haliax/partitioning.py index c4ecdd3..4d04421 100644 --- a/src/haliax/partitioning.py +++ b/src/haliax/partitioning.py @@ -4,21 +4,17 @@ import threading import typing import warnings from math import prod -from typing import Callable, Mapping, Optional, ParamSpec, Sequence, TypeVar, Union +from typing import Callable, ContextManager, Mapping, Optional, ParamSpec, Sequence, TypeVar, Union import equinox as eqx import jax from equinox import module_update_wrapper - -# TODO: avoid depending on private Equinox internals. -from equinox._compile_utils import compile_cache - -# from jax._src.sharding_impls import AUTO from jax.lax import with_sharding_constraint from jax.sharding import Mesh, NamedSharding, PartitionSpec, SingleDeviceSharding from jaxtyping import PyTree import haliax.tree_util as htu +from haliax._src.compile_utils import compile_cache from .axis import Axis, AxisSelection, AxisSelector from .core import NamedArray @@ -99,7 +95,7 @@ def auto_sharded(x: T, mesh: Optional[Mesh] = None) -> T: if mapping is None: return x - return shard(x, mapping, mesh) + return shard(x, mapping=mapping, mesh=mesh) def shard(x: T, mapping: Optional[ResourceMapping] = None, mesh: Optional[Mesh] = None) -> T: @@ -123,6 +119,17 @@ def shard(x: T, mapping: Optional[ResourceMapping] = None, mesh: Optional[Mesh] return x + assert not isinstance(mesh, dict) + + if mesh is None: + mesh = _get_mesh() + + if mesh.empty: + mesh = None + + if mesh is None: + return x + def _do_device_put(x): if not is_named_array(x): return x @@ -189,6 +196,7 @@ def infer_resource_partitions( raise ValueError("No resource mapping found") mesh = mesh or _get_mesh() + assert not isinstance(mesh, dict) def partition_spec(node: typing.Any): if isinstance(node, NamedArray): @@ -305,6 +313,7 @@ class _NamedJitWrapper(eqx.Module): static = (self._static_fun, static_argspec) + cmanager: ContextManager if axis_resources is not None: cmanager = axis_mapping(axis_resources) else: @@ -312,10 +321,6 @@ class _NamedJitWrapper(eqx.Module): with cmanager: output_shape = _cached_filter_eval_shape(self._fn, *args, **kwargs) - # TODO: with new jax.Array I shouldn't have to specify shardings, but I do for now - # https://github.com/google/jax/issues/15600 - # we don't really need in_shardings though - my_pjit_args = dict(**self._pjit_args) if in_axis_resources is not None or axis_resources is not None: @@ -345,6 +350,39 @@ class _NamedJitWrapper(eqx.Module): return out +@typing.overload +def named_jit( + fn: Callable[Args, R], + axis_resources: Optional[ResourceMapping] = None, + *, + in_axis_resources: Optional[ResourceMapping] = None, + out_axis_resources: Optional[ResourceMapping] = None, + donate_args: Optional[PyTree] = None, + donate_kwargs: Optional[PyTree] = None, + # args from jit + keep_unused: bool = False, + backend: Optional[str] = None, + inline: Optional[bool] = None, +) -> WrappedCallable[Args, R]: + ... + + +@typing.overload +def named_jit( + *, + axis_resources: Optional[ResourceMapping] = None, + in_axis_resources: Optional[ResourceMapping] = None, + out_axis_resources: Optional[ResourceMapping] = None, + donate_args: Optional[PyTree] = None, + donate_kwargs: Optional[PyTree] = None, + # args from jit + keep_unused: bool = False, + backend: Optional[str] = None, + inline: Optional[bool] = None, +) -> typing.Callable[[Callable[Args, R]], WrappedCallable[Args, R]]: + ... + + def named_jit( fn: Optional[Callable[Args, R]] = None, axis_resources: Optional[ResourceMapping] = None, @@ -354,7 +392,7 @@ def named_jit( donate_args: Optional[PyTree] = None, donate_kwargs: Optional[PyTree] = None, **pjit_args, -) -> WrappedCallable[Args, R]: +): """ A version of pjit that uses NamedArrays and the provided resource mapping to infer resource partitions for sharded computation for. @@ -497,7 +535,6 @@ def _named_pjit_cache(fun_names, **jitkwargs) -> WrappedCallable: # None for the static jitkwargs["out_shardings"] = (out_shardings, None) - # TODO: jit should work here, but there's a weird error. see if it goes away on its own return jax.jit( fun_wrapped, donate_argnums=0, diff --git a/src/haliax/random.py b/src/haliax/random.py index a466ee2..9d2c4ea 100644 --- a/src/haliax/random.py +++ b/src/haliax/random.py @@ -25,7 +25,7 @@ def uniform( maxval = broadcast_to(maxval, shape).array jax_shape = _to_jax_shape(shape) jax_array = jrandom.uniform(key=key, shape=jax_shape, dtype=dtype, minval=minval, maxval=maxval) - return haliax.shard(NamedArray(jax_array, shape)) + return haliax.auto_sharded(NamedArray(jax_array, shape)) @named_call @@ -33,7 +33,7 @@ def normal(key, shape: AxisSpec, dtype=float): shape = ensure_tuple(shape) jax_shape = _to_jax_shape(shape) jax_array = jrandom.normal(key=key, shape=jax_shape, dtype=dtype) - return haliax.shard(NamedArray(jax_array, shape)) + return haliax.auto_sharded(NamedArray(jax_array, shape)) @named_call @@ -42,7 +42,7 @@ def bernoulli(key, shape: AxisSpec, p: NamedOrNumeric): p = broadcast_to(p, shape).array jax_shape = _to_jax_shape(shape) jax_array = jrandom.bernoulli(key=key, p=p, shape=jax_shape) - return haliax.shard(NamedArray(jax_array, shape)) + return haliax.auto_sharded(NamedArray(jax_array, shape)) @named_call @@ -52,7 +52,7 @@ def randint(key, shape: AxisSpec, minval: NamedOrNumeric, maxval: NamedOrNumeric maxval = broadcast_to(maxval, shape).array jax_shape = _to_jax_shape(shape) jax_array = jrandom.randint(key=key, shape=jax_shape, minval=minval, maxval=maxval, dtype=dtype) - return haliax.shard(NamedArray(jax_array, shape)) + return haliax.auto_sharded(NamedArray(jax_array, shape)) @named_call @@ -61,7 +61,7 @@ def poisson(key, shape: AxisSpec, lam: NamedOrNumeric, dtype=int): lam = broadcast_to(lam, shape).array jax_shape = _to_jax_shape(shape) jax_array = jrandom.poisson(key=key, lam=lam, shape=jax_shape, dtype=dtype) - return haliax.shard(NamedArray(jax_array, shape)) + return haliax.auto_sharded(NamedArray(jax_array, shape)) @named_call @@ -69,7 +69,7 @@ def exponential(key, shape: AxisSpec, dtype=float): shape = ensure_tuple(shape) jax_shape = _to_jax_shape(shape) jax_array = jrandom.exponential(key=key, shape=jax_shape, dtype=dtype) - return haliax.shard(NamedArray(jax_array, shape)) + return haliax.auto_sharded(NamedArray(jax_array, shape)) @named_call @@ -78,7 +78,7 @@ def gamma(key, shape: AxisSpec, a: NamedOrNumeric, dtype=float): a = broadcast_to(a, shape).array jax_shape = _to_jax_shape(shape) jax_array = jrandom.gamma(key=key, a=a, shape=jax_shape, dtype=dtype) - return haliax.shard(NamedArray(jax_array, shape)) + return haliax.auto_sharded(NamedArray(jax_array, shape)) @named_call @@ -88,7 +88,7 @@ def beta(key, shape: AxisSpec, a: NamedOrNumeric, b: NamedOrNumeric, dtype=float b = broadcast_to(b, shape).array jax_shape = _to_jax_shape(shape) jax_array = jrandom.beta(key=key, a=a, b=b, shape=jax_shape, dtype=dtype) - return haliax.shard(NamedArray(jax_array, shape)) + return haliax.auto_sharded(NamedArray(jax_array, shape)) @named_call @@ -96,7 +96,7 @@ def laplace(key, shape: AxisSpec, dtype=float): shape = ensure_tuple(shape) jax_shape = _to_jax_shape(shape) jax_array = jrandom.laplace(key=key, shape=jax_shape, dtype=dtype) - return haliax.shard(NamedArray(jax_array, shape)) + return haliax.auto_sharded(NamedArray(jax_array, shape)) @named_call @@ -104,7 +104,7 @@ def cauchy(key, shape: AxisSpec, dtype=float): shape = ensure_tuple(shape) jax_shape = _to_jax_shape(shape) jax_array = jrandom.cauchy(key=key, shape=jax_shape, dtype=dtype) - return haliax.shard(NamedArray(jax_array, shape)) + return haliax.auto_sharded(NamedArray(jax_array, shape)) @named_call @@ -112,7 +112,7 @@ def logistic(key, shape: AxisSpec, dtype=float): shape = ensure_tuple(shape) jax_shape = _to_jax_shape(shape) jax_array = jrandom.logistic(key=key, shape=jax_shape, dtype=dtype) - return haliax.shard(NamedArray(jax_array, shape)) + return haliax.auto_sharded(NamedArray(jax_array, shape)) @named_call @@ -122,7 +122,7 @@ def truncated_normal(key, shape: AxisSpec, lower: NamedOrNumeric, upper: NamedOr upper = broadcast_to(upper, shape).array jax_shape = _to_jax_shape(shape) jax_array = jrandom.truncated_normal(key=key, lower=lower, upper=upper, shape=jax_shape, dtype=dtype) - return haliax.shard(NamedArray(jax_array, shape)) + return haliax.auto_sharded(NamedArray(jax_array, shape)) _enforce_sharded_generate = False @@ -177,7 +177,7 @@ def generate_sharded(fn, axis: Optional[AxisSelector] = None): _axis = _axis or shape[0] else: - biggest_physical = physical_axis_name(axis) + biggest_physical = physical_axis_name(_axis) if _enforce_sharded_generate or biggest_physical: with jax.named_scope(f"generate_sharded({_axis})"): @@ -185,7 +185,7 @@ def generate_sharded(fn, axis: Optional[AxisSelector] = None): # remove axis from shape shape_without_axis = shape[:index_of_axis_to_shard] + shape[index_of_axis_to_shard + 1 :] - keys = jrandom.split(key, _axis.size) + keys = jrandom.split(key, shape[index_of_axis_to_shard].size) bound.arguments["shape"] = shape_without_axis bound.arguments["key"] = keys @@ -203,7 +203,7 @@ def ball(key, shape: AxisSpec, D: Axis, p: float = 2.0, dtype=float): shape = ensure_tuple(shape) jax_shape = _to_jax_shape(shape) jax_array = jrandom.ball(key=key, shape=jax_shape, d=D.size, p=p, dtype=dtype) - return haliax.shard(NamedArray(jax_array, shape + (D,))) + return haliax.auto_sharded(NamedArray(jax_array, shape + (D,))) @named_call @@ -232,7 +232,7 @@ def choice( expected_shape = shape + tuple(a.axes[:index] + a.axes[index + 1 :]) - return haliax.shard(NamedArray(jax_array, expected_shape)) + return haliax.auto_sharded(NamedArray(jax_array, expected_shape)) @named_call @@ -267,7 +267,7 @@ def categorical(key, logits: NamedArray, axis: AxisSelector, shape: Optional[Axi jax_shape = _to_jax_shape(shape) jax_array = jrandom.categorical(key, logits.array, axis=index, shape=jax_shape) - return haliax.shard(NamedArray(jax_array, shape)) + return haliax.auto_sharded(NamedArray(jax_array, shape)) @named_call @@ -275,14 +275,14 @@ def gumbel(key, shape: AxisSpec, dtype=float): shape = ensure_tuple(shape) jax_shape = _to_jax_shape(shape) jax_array = jrandom.gumbel(key, jax_shape, dtype=dtype) - return haliax.shard(NamedArray(jax_array, shape)) + return haliax.auto_sharded(NamedArray(jax_array, shape)) @named_call def permutation(key, x: NamedArray, axis: AxisSelector, independent: bool = False): axis_index = x._lookup_indices(axis) jax_array = jrandom.permutation(key, x.array, axis_index, independent=independent) - return haliax.shard(NamedArray(jax_array, x.axes)) + return haliax.auto_sharded(NamedArray(jax_array, x.axes)) @named_call @@ -290,7 +290,7 @@ def rademacher(key, shape: AxisSpec, dtype=float): shape = ensure_tuple(shape) jax_shape = _to_jax_shape(shape) jax_array = jrandom.rademacher(key, jax_shape, dtype=dtype) - return haliax.shard(NamedArray(jax_array, shape)) + return haliax.auto_sharded(NamedArray(jax_array, shape)) @named_call @@ -299,7 +299,7 @@ def t(key, shape: AxisSpec, df: NamedOrNumeric, dtype=float): df = broadcast_to(df, shape) jax_shape = _to_jax_shape(shape) jax_array = jrandom.t(key, df.array, jax_shape, dtype=dtype) - return haliax.shard(NamedArray(jax_array, shape)) + return haliax.auto_sharded(NamedArray(jax_array, shape)) @named_call @@ -309,7 +309,7 @@ def weibull_min(key, shape: AxisSpec, scale: NamedOrNumeric, concentration: Name concentration = broadcast_to(concentration, shape) jax_shape = _to_jax_shape(shape) jax_array = jrandom.weibull_min(key, scale.array, concentration.array, jax_shape, dtype=dtype) - return haliax.shard(NamedArray(jax_array, shape)) + return haliax.auto_sharded(NamedArray(jax_array, shape)) @named_call @@ -318,7 +318,7 @@ def pareto(key, shape: AxisSpec, b: NamedOrNumeric, dtype=float): b = broadcast_to(b, shape) jax_shape = _to_jax_shape(shape) jax_array = jrandom.pareto(key, b.array, jax_shape, dtype=dtype) - return haliax.shard(NamedArray(jax_array, shape)) + return haliax.auto_sharded(NamedArray(jax_array, shape)) @named_call @@ -327,7 +327,7 @@ def loggamma(key, shape: AxisSpec, a: NamedOrNumeric, dtype=float): a = broadcast_to(a, shape) jax_shape = _to_jax_shape(shape) jax_array = jrandom.loggamma(key, a.array, jax_shape, dtype=dtype) - return haliax.shard(NamedArray(jax_array, shape)) + return haliax.auto_sharded(NamedArray(jax_array, shape)) def _to_jax_shape(shape): diff --git a/src/haliax/types.py b/src/haliax/types.py index 512d453..f4b0ea3 100644 --- a/src/haliax/types.py +++ b/src/haliax/types.py @@ -1,9 +1,29 @@ -from typing import Tuple, Union +from typing import Any, Protocol, Tuple, TypeAlias, Union import jax.numpy as jnp +import numpy as np from jax.lax import Precision +DType: TypeAlias = np.dtype + +try: + from jax.typing import DTypeLike +except ImportError: + # Cribbed from jax.typing, for older versions of JAX + class SupportsDType(Protocol): + @property + def dtype(self) -> DType: + ... + + DTypeLike = Union[ + str, # like 'float32', 'int32' + type, # like np.float32, np.int32, float, int + np.dtype, # like np.dtype('float32'), np.dtype('int32') + SupportsDType, # like jnp.float32, jnp.int32 + ] + + Scalar = Union[float, int, jnp.ndarray] # ndarray b/c array(1) is a scalar IntScalar = Union[int, jnp.ndarray] diff --git a/src/haliax/wrap.py b/src/haliax/wrap.py index f5d0c7c..56943ed 100644 --- a/src/haliax/wrap.py +++ b/src/haliax/wrap.py @@ -1,9 +1,11 @@ +import typing from typing import Optional, Protocol import jax import jax.numpy as jnp from haliax.core import NamedArray, _broadcast_order, broadcast_to +from haliax.jax_utils import is_scalarish from haliax.util import ensure_tuple from .axis import AxisSelection, AxisSelector, selects_axis @@ -39,16 +41,13 @@ def wrap_reduction_call( if isinstance(a, NamedArray): if where is not None: if not isinstance(where, NamedArray): - raise TypeError("where must be a NamedArray if a is a NamedArray") + raise TypeError(f"where must be a NamedArray if a is a NamedArray, but is {where}") where = broadcast_to(where, a.axes) kwargs["where"] = where.array if axis is None: result = fn(a.array, axis=None, **kwargs) - if jnp.isscalar(result): - return result - else: - return NamedArray(result, ()) + return NamedArray(result, ()) else: axis = ensure_tuple(axis) if single_axis_only and len(axis) > 1: @@ -61,8 +60,6 @@ def wrap_reduction_call( result = fn(a.array, axis=indices[0], **kwargs) else: result = fn(a.array, axis=indices, **kwargs) - if jnp.isscalar(result): - return result return NamedArray(result, tuple(new_axes)) else: if where is not None: @@ -75,7 +72,7 @@ def wrap_reduction_call( def wrap_axiswise_call(fn, a, axis: Optional[AxisSelection], *, single_axis_only: bool, **kwargs): if isinstance(a, NamedArray): if axis is None: - return NamedArray(fn(a.array, axis=None, **kwargs), a.axes) + return fn(a.array, axis=None, **kwargs) else: indices = ensure_tuple(a._lookup_indices(axis)) if any(x is None for x in indices): @@ -98,9 +95,9 @@ def wrap_elemwise_binary(op): a = broadcast_to(a, axes) b = broadcast_to(b, axes) return NamedArray(op(a.array, b.array), axes) - elif isinstance(a, NamedArray) and jnp.isscalar(b): + elif isinstance(a, NamedArray): return NamedArray(op(a.array, b), a.axes) - elif isinstance(b, NamedArray) and jnp.isscalar(a): + elif isinstance(b, NamedArray): return NamedArray(op(a, b.array), b.axes) else: return op(a, b) @@ -112,17 +109,6 @@ def unwrap_namedarrays(*a): return tuple(x.array if isinstance(x, NamedArray) else x for x in a) -__all__ = [ - "wrap_elemwise_unary", - "wrap_reduction_call", - "wrap_axiswise_call", - "wrap_elemwise_binary", - "unwrap_namedarrays", - "ReductionFunction", - "SimpleReductionFunction", -] - - class ReductionFunction(Protocol): def __call__( self, @@ -137,3 +123,14 @@ class ReductionFunction(Protocol): class SimpleReductionFunction(Protocol): def __call__(self, array: NamedArray, axis: Optional[AxisSelector] = None, **kwargs) -> NamedArray: ... + + +__all__ = [ + "wrap_elemwise_unary", + "wrap_reduction_call", + "wrap_axiswise_call", + "wrap_elemwise_binary", + "unwrap_namedarrays", + "ReductionFunction", + "SimpleReductionFunction", +] diff --git a/tests/core_test.py b/tests/core_test.py index caa5f27..e20bb08 100644 --- a/tests/core_test.py +++ b/tests/core_test.py @@ -8,66 +8,6 @@ import haliax as hax from haliax import Axis, NamedArray -def test_dot(): - Height = Axis("Height", 2) - Width = Axis("Width", 3) - Depth = Axis("Depth", 4) - - m1 = NamedArray(jnp.ones((Height.size, Width.size, Depth.size)), (Height, Width, Depth)) - m2 = NamedArray(jnp.ones((Depth.size, Width.size, Height.size)), (Depth, Width, Height)) - - assert jnp.all(jnp.equal(hax.dot(Height, m1, m2).array, jnp.einsum("ijk,kji->jk", m1.array, m2.array))) - assert jnp.all( - jnp.equal( - hax.dot((Height, Width), m1, m2).array, - jnp.einsum("ijk,kji->k", m1.array, m2.array), - ) - ) - assert jnp.all( - jnp.equal( - hax.dot((Height, Width, Depth), m1, m2).array, - jnp.einsum("ijk,kji->", m1.array, m2.array), - ) - ) - - -def test_dot_string_selection(): - Height = Axis("Height", 2) - Width = Axis("Width", 3) - Depth = Axis("Depth", 4) - - m1 = NamedArray(jnp.ones((Height.size, Width.size, Depth.size)), (Height, Width, Depth)) - m2 = NamedArray(jnp.ones((Depth.size, Width.size, Height.size)), (Depth, Width, Height)) - - assert jnp.all(jnp.equal(hax.dot("Height", m1, m2).array, jnp.einsum("ijk,kji->jk", m1.array, m2.array))) - assert jnp.all( - jnp.equal( - hax.dot(("Height", "Width"), m1, m2).array, - jnp.einsum("ijk,kji->k", m1.array, m2.array), - ) - ) - assert jnp.all( - jnp.equal( - hax.dot(("Height", "Width", "Depth"), m1, m2).array, - jnp.einsum("ijk,kji->", m1.array, m2.array), - ) - ) - - -def test_dot_errors_if_different_sized_axes(): - Height = Axis("Height", 2) - Width = Axis("Width", 3) - Depth = Axis("Depth", 4) - - H2 = Axis("Height", 4) - - m1 = NamedArray(jnp.ones((Height.size, Width.size, Depth.size)), (Height, Width, Depth)) - m2 = NamedArray(jnp.ones((Depth.size, Width.size, H2.size)), (Depth, Width, H2)) - - with pytest.raises(ValueError): - hax.dot("Height", m1, m2) - - def test_unary_np_functions(): Height = Axis("Height", 2) Width = Axis("Width", 3) @@ -98,7 +38,7 @@ def test_reduction_functions(): m1 = NamedArray(rand_m, (Height, Width, Depth)) # sum out everything - assert jnp.all(jnp.equal(hax.sum(m1).array, jnp.sum(m1.array))) + assert jnp.all(jnp.equal(hax.sum(m1), jnp.sum(m1.array))) # ensure it's a scalar assert jnp.all(jnp.equal(hax.sum(m1, axis=Height).array, jnp.sum(m1.array, axis=0))) @@ -124,7 +64,7 @@ def test_reduction_functions(): ) # argmax - assert jnp.all(jnp.equal(hax.argmax(m1).array, jnp.argmax(m1.array))) + assert jnp.all(jnp.equal(hax.argmax(m1, axis=None), jnp.argmax(m1.array))) assert jnp.all(jnp.equal(hax.argmax(m1, axis=Height).array, jnp.argmax(m1.array, axis=0))) @@ -141,7 +81,7 @@ def test_reduction_functions_with_where(): jmask = m1.array > 0.5 # sum out everything - assert jnp.all(jnp.equal(hax.sum(m1, where=mask).array, jnp.sum(rand_m, where=jmask))) + assert jnp.all(jnp.equal(hax.sum(m1, where=mask), jnp.sum(rand_m, where=jmask))) # ensure it's a scalar assert jnp.all(jnp.equal(hax.sum(m1, axis=H, where=mask).array, jnp.sum(rand_m, axis=0, where=jmask))) @@ -336,9 +276,7 @@ def test_rearrange(): # test ellipsis assert jnp.all(jnp.equal(hax.rearrange(named1, (C, ..., D)).array, jnp.transpose(named1.array, (3, 0, 1, 2)))) - # test errors for double ellipsis - with pytest.raises(ValueError): - hax.rearrange(named1, (C, ..., ...)) + # this should be ok now # test errors for multiply specified axes with pytest.raises(ValueError): @@ -353,6 +291,16 @@ def test_rearrange(): with pytest.raises(ValueError): hax.rearrange(named1, (C, W, D)) + # test double ellipsis + assert hax.rearrange(named1, (C, ..., ...)).axes == (C, H, W, D) + + # test ellipses in different places + assert hax.rearrange(named1, (..., C, ..., W)).axes == (H, D, C, W) + + assert hax.rearrange(named1, (..., H, ..., D)).axes == (H, W, C, D) + + assert hax.rearrange(named1, (D, ..., H, ...)).axes == (D, H, W, C) + def test_rearrange_unused_ellipsis(): # Make sure we just ignore the ellipsis if all axes are specified in addition @@ -575,8 +523,8 @@ def test_index(): named1 = hax.random.uniform(PRNGKey(0), (H, W, D)) - assert jnp.all(jnp.equal(hax.index(named1, {"H": slice(0, 10, 2)}).array, named1.array[0:10:2, :, :])) - assert hax.index(named1, {"H": slice(0, 10, 2)}).axes == (Axis("H", 5), W, D) + assert jnp.all(jnp.equal(hax.index(named1, {"H": slice(0, 10, 2)}).array, named1.array[0:10:2, :, :])) # type: ignore + assert hax.index(named1, {"H": slice(0, 10, 2)}).axes == (Axis("H", 5), W, D) # type: ignore # try indexing syntax assert jnp.all(jnp.equal(named1[{"H": slice(0, 10, 2)}].array, named1.array[0:10:2, :, :])) @@ -701,7 +649,7 @@ def test_slice_nd_array_present_dims(): assert jnp.all(jnp.equal(named1[{"H": index2}].array, named1.array[index2.array, :, :])) -def test_full_indexing_returns_scalar(): +def test_full_indexing_returns_named_array(): H = Axis("H", 10) W = Axis("W", 20) D = Axis("D", 30) @@ -709,8 +657,8 @@ def test_full_indexing_returns_scalar(): named1 = hax.random.uniform(PRNGKey(0), (H, W, D)) sliced = named1[{"H": 0, "W": 0, "D": 0}] - assert isinstance(sliced, jnp.ndarray) - assert sliced.shape == () + assert isinstance(sliced, NamedArray) + assert sliced.shape == {} def test_indexing_bug_from_docs(): diff --git a/tests/test_attention.py b/tests/test_attention.py index b8d267e..b1faa47 100644 --- a/tests/test_attention.py +++ b/tests/test_attention.py @@ -82,10 +82,10 @@ def test_alibi_attention_bias(): weights_bias = dot_product_attention_weights(Hid, KeyPos, query, key, bias=bias) weights_no_bias = dot_product_attention_weights(Hid, KeyPos, query, key) - assert weights_bias.take(KeyPos, -1).item() > weights_bias.take(KeyPos, -2).item() - assert weights_bias.take(KeyPos, -1).item() > weights_no_bias.take(KeyPos, -1).item() + assert weights_bias[KeyPos, -1] > weights_bias[KeyPos, -2] + assert weights_bias[KeyPos, -1] > weights_no_bias[KeyPos, -1] - assert weights_no_bias.take(KeyPos, -1).item() == weights_no_bias.take(KeyPos, -2).item() + assert weights_no_bias[KeyPos, -1] == weights_no_bias[KeyPos, -2] @skip_if_no_torch @@ -125,9 +125,7 @@ def test_fcm_attention_mask(): weights = dot_product_attention_weights(Head, KeyPos, query, key, mask=mask) # check that all masked out values are zero - # TODO: think about how to make this work with named arrays - weights = weights.rearrange((KeyPos, QueryPos)).array - mask = mask.array + weights = weights.rearrange((KeyPos, QueryPos)) - assert weights[mask == 0].sum() == 0 - assert weights[mask == 1].sum() > 0 + assert (weights * (mask == 0)).sum() == 0 + assert (weights * (mask == 1)).sum() > 0 diff --git a/tests/test_axis.py b/tests/test_axis.py index 56432d7..ae8f689 100644 --- a/tests/test_axis.py +++ b/tests/test_axis.py @@ -1,6 +1,6 @@ import pytest -from haliax.axis import Axis, eliminate_axes +from haliax.axis import Axis, eliminate_axes, rearrange_for_partial_order def test_eliminate_axes(): @@ -23,3 +23,115 @@ def test_eliminate_axes(): assert eliminate_axes(("H", W), (H,)) == (W,) assert eliminate_axes(("H", W), ("H",)) == (W,) assert eliminate_axes(("H", W), ("H", "W")) == () + + +def assert_partial_order_respected(partial_order, output): + positions = {el: i for i, el in enumerate(output)} + + last_pos = -1 + for el in partial_order: + if el is ...: + # Reset last_pos for flexible positions + last_pos = -1 + else: + # Check if the element is in the correct order + assert el in positions, f"{el} is missing in the output" + assert positions[el] > last_pos, f"Partial order not respected for {el}" + last_pos = positions[el] + + +def test_basic_order(): + partial_order = ("apple", ..., "banana") + candidates = ("banana", "apple", "cherry") + expected_output = ("apple", "cherry", "banana") + actual_output = rearrange_for_partial_order(partial_order, candidates) + assert actual_output == expected_output + assert_partial_order_respected(partial_order, actual_output) + + +def test_start_with_ellipsis(): + partial_order = (..., "apple", "banana") + candidates = ("banana", "apple", "cherry") + actual_output = rearrange_for_partial_order(partial_order, candidates) + assert_partial_order_respected(partial_order, actual_output) + assert actual_output == ("cherry", "apple", "banana") + + +def test_end_with_ellipsis(): + partial_order = ("apple", ..., "banana", ...) + candidates = ("banana", "apple", "cherry") + actual_output = rearrange_for_partial_order(partial_order, candidates) + assert_partial_order_respected(partial_order, actual_output) + + # this one could be either but we'll assert the order so we catch changes + assert actual_output == ("apple", "banana", "cherry") + + +def test_full_flexibility(): + partial_order = (...,) + candidates = ("banana", "apple", "cherry") + actual_output = rearrange_for_partial_order(partial_order, candidates) + assert_partial_order_respected(partial_order, actual_output) + + +def test_no_flexibility(): + partial_order = ("apple", "banana") + candidates = ("banana", "apple", "cherry") + with pytest.raises(ValueError): + rearrange_for_partial_order(partial_order, candidates) + + +def test_final_ellipsis(): + partial_order = ("apple", "banana", ...) + candidates = ("banana", "apple", "cherry") + actual_output = rearrange_for_partial_order(partial_order, candidates) + assert_partial_order_respected(partial_order, actual_output) + assert actual_output == ("apple", "banana", "cherry") + + +def test_lots_of_ellipsis(): + partial_order = ("apple", ..., "banana", ..., "cherry", ...) + candidates = ("banana", "orange", "cherry", "apple", "grape") + actual_output = rearrange_for_partial_order(partial_order, candidates) + assert_partial_order_respected(partial_order, actual_output) + assert actual_output == ("apple", "banana", "orange", "cherry", "grape") + + +def test_no_ellipsis(): + partial_order = ("apple", "banana", "cherry") + candidates = ("banana", "apple", "cherry") + actual_output = rearrange_for_partial_order(partial_order, candidates) + assert_partial_order_respected(partial_order, actual_output) + assert actual_output == ("apple", "banana", "cherry") + + +def test_no_elements(): + partial_order = (...,) + candidates = () + actual_output = rearrange_for_partial_order(partial_order, candidates) + assert_partial_order_respected(partial_order, actual_output) + assert actual_output == () + + +def test_missing_elements_errors(): + partial_order = ("qux", ...) + candidates = ("banana", "apple", "cherry") + with pytest.raises(ValueError): + rearrange_for_partial_order(partial_order, candidates) + + +def test_duplicate_elements_errors(): + partial_order: tuple = ("apple", "apple", ...) + candidates = ("banana", "apple", "cherry") + with pytest.raises(ValueError): + rearrange_for_partial_order(partial_order, candidates) + + candidates = ("banana", "apple", "apple") + + with pytest.raises(ValueError): + rearrange_for_partial_order(partial_order, candidates) + + partial_order = ("apple", "banana", "grape", ...) + + with pytest.raises(ValueError): + rearrange_for_partial_order(partial_order, candidates) diff --git a/tests/test_conv.py b/tests/test_conv.py index f2fb028..e460412 100644 --- a/tests/test_conv.py +++ b/tests/test_conv.py @@ -45,6 +45,24 @@ def test_conv_basic_equiv_to_eqx(): assert hax_output.array.shape == eqx_output.shape assert jnp.allclose(hax_output.array, eqx_output) + input = hax.random.normal( + jax.random.PRNGKey(1), + ( + hax.Axis("Batch", 2), + In, + hax.Axis("Height", 5), + hax.Axis("Width", 6), + hax.Axis("Batch2", 3), + ), + ) + hax_output = hax_conv(input).rearrange(("Batch", "Batch2", "Out", "Height", "Width")) + eqx_output = eqx.filter_vmap(eqx.filter_vmap(eqx_conv))( + input.rearrange(("Batch", "Batch2", "In", "Height", "Width")).array + ) + + assert hax_output.array.shape == eqx_output.shape + assert jnp.allclose(hax_output.array, eqx_output) + def test_conv_grouped_equiv_to_eqx(): key = jax.random.PRNGKey(0) diff --git a/tests/test_dot.py b/tests/test_dot.py new file mode 100644 index 0000000..d4c306c --- /dev/null +++ b/tests/test_dot.py @@ -0,0 +1,132 @@ +# these test if the rearrange logic works for partial orders +import pytest +from jax import numpy as jnp + +import haliax as hax +from haliax import Axis, NamedArray + + +def test_dot(): + Height = Axis("Height", 2) + Width = Axis("Width", 3) + Depth = Axis("Depth", 4) + + m1 = hax.ones((Height, Width, Depth)) + m2 = hax.ones((Depth, Width, Height)) + + assert jnp.all(jnp.equal(hax.dot(m1, m2, axis=Height).array, jnp.einsum("ijk,kji->jk", m1.array, m2.array))) + assert jnp.all( + jnp.equal( + hax.dot(m1, m2, axis=(Height, Width)).array, + jnp.einsum("ijk,kji->k", m1.array, m2.array), + ) + ) + assert jnp.all( + jnp.equal( + hax.dot(m1, m2, axis=(Height, Width, Depth)).array, + jnp.einsum("ijk,kji->", m1.array, m2.array), + ) + ) + + # reduce to scalar + assert jnp.all( + jnp.equal( + hax.dot(m1, m2, axis=None), + jnp.einsum("ijk,kji->", m1.array, m2.array), + ) + ) + + +def test_dot_string_selection(): + Height = Axis("Height", 2) + Width = Axis("Width", 3) + Depth = Axis("Depth", 4) + + m1 = hax.ones((Height, Width, Depth)) + m2 = hax.ones((Depth, Width, Height)) + + assert jnp.all(jnp.equal(hax.dot(m1, m2, axis="Height").array, jnp.einsum("ijk,kji->jk", m1.array, m2.array))) + assert jnp.all( + jnp.equal( + hax.dot(m1, m2, axis=("Height", "Width")).array, + jnp.einsum("ijk,kji->k", m1.array, m2.array), + ) + ) + assert jnp.all( + jnp.equal( + hax.dot(m1, m2, axis=("Height", "Width", "Depth")).array, + jnp.einsum("ijk,kji->", m1.array, m2.array), + ) + ) + + +def test_dot_errors_if_different_sized_axes(): + Height = Axis("Height", 2) + Width = Axis("Width", 3) + Depth = Axis("Depth", 4) + + H2 = Axis("Height", 4) + + m1 = hax.ones((Height, Width, Depth)) + m2 = hax.ones((Depth, Width, H2)) + + with pytest.raises(ValueError): + hax.dot(m1, m2, axis="Height") + + +def test_dot_with_output_axes(): + Height = Axis("Height", 2) + Width = Axis("Width", 3) + Depth = Axis("Depth", 4) + + m1 = hax.ones((Height, Width, Depth)) + m2 = hax.ones((Depth, Width, Height)) + + assert jnp.all( + jnp.equal( + hax.dot(m1, m2, axis=Height, out_axes=(Width, ...)).array, + jnp.einsum("ijk,kji->jk", m1.array, m2.array), + ) + ) + + assert jnp.all( + jnp.equal( + hax.dot(m1, m2, axis=Height, out_axes=(Depth, ...)).array, + jnp.einsum("ijk,kji->kj", m1.array, m2.array), + ) + ) + + assert jnp.all( + jnp.equal( + hax.dot(m1, m2, axis=Height, out_axes=(Depth, Width)).array, + jnp.einsum("ijk,kji->kj", m1.array, m2.array), + ) + ) + + assert jnp.all( + jnp.equal( + hax.dot(m1, m2, axis=(), out_axes=(Depth, Height, ...)).array, + jnp.einsum("ijk,kji->kij", m1.array, m2.array), + ) + ) + + assert jnp.all( + jnp.equal( + hax.dot(m1, m2, axis=(), out_axes=(..., Depth, Height)).array, + jnp.einsum("ijk,kji->jki", m1.array, m2.array), + ) + ) + + assert jnp.all( + jnp.equal( + hax.dot(m1, m2, axis=(), out_axes=(..., Depth, ...)).array, + jnp.einsum("ijk,kji->ijk", m1.array, m2.array), + ) + ) + + assert jnp.all( + jnp.equal( + hax.dot(m1, m2, axis=(), out_axes=(..., Depth, Height, ...)).array, + jnp.einsum("ijk,kji->kij", m1.array, m2.array), + ) + ) diff --git a/tests/test_einsum.py b/tests/test_einsum.py new file mode 100644 index 0000000..e73031f --- /dev/null +++ b/tests/test_einsum.py @@ -0,0 +1,274 @@ +import jax.numpy as jnp +import pytest + +import haliax as hax +from haliax import Axis, NamedArray +from haliax._src.einsum import einsum + + +def test_einsum_basic_positional(): + Height = Axis("Height", 2) + Width = Axis("Width", 3) + Depth = Axis("Depth", 4) + + m1 = NamedArray(jnp.ones((Height.size, Width.size, Depth.size)), (Height, Width, Depth)) + m2 = NamedArray(jnp.ones((Depth.size, Width.size, Height.size)), (Depth, Width, Height)) + + assert jnp.all(jnp.equal(einsum("i j k,k j i-> j k", m1, m2).array, jnp.einsum("ijk,kji->jk", m1.array, m2.array))) + assert jnp.all( + jnp.equal( + einsum("i j k,k j i->k", m1, m2).array, + jnp.einsum("ijk,kji->k", m1.array, m2.array), + ) + ) + assert jnp.all( + jnp.equal( + einsum("i j k,k j i->", m1, m2).array, + jnp.einsum("ijk,kji->", m1.array, m2.array), + ) + ) + + # reduce to scalar + assert jnp.all( + jnp.equal( + einsum("i j k,k j i->", m1, m2).array, + jnp.einsum("ijk,kji->", m1.array, m2.array), + ) + ) + + +def test_einsum_basic_named(): + Height = Axis("Height", 2) + Width = Axis("Width", 3) + Depth = Axis("Depth", 4) + + m1 = hax.ones((Height, Width, Depth)) + m2 = hax.ones((Depth, Width, Height)) + + assert jnp.all( + jnp.equal( + einsum("{Height Width Depth} -> Height Width", m1, m2).array, jnp.einsum("ijk,kji->ij", m1.array, m2.array) + ) + ) + + assert jnp.all(jnp.equal(einsum(" -> Height Width", m1, m2).array, jnp.einsum("ijk,kji->ij", m1.array, m2.array))) + assert jnp.all( + jnp.equal( + einsum("{Height Width Depth} -> Depth", m1, m2).array, + jnp.einsum("ijk,kji->k", m1.array, m2.array), + ) + ) + assert jnp.all( + jnp.equal( + einsum("-> Depth", m1, m2).array, + jnp.einsum("ijk,kji->k", m1.array, m2.array), + ) + ) + + assert jnp.all( + jnp.equal( + einsum("{Height Width Depth} -> ", m1, m2).array, + jnp.einsum("ijk,kji->", m1.array, m2.array), + ) + ) + + # outer product + assert jnp.all( + jnp.equal( + einsum("{} ->", m1, m2).array, + jnp.einsum("ijk,kji->ijk", m1.array, m2.array), + ) + ) + + assert jnp.all( + jnp.equal( + einsum("{Height Depth} -> ", m1, m2).array, + jnp.einsum("ijk,kji->j", m1.array, m2.array), + ) + ) + + assert jnp.all( + jnp.equal( + einsum("{Height Depth} -> ", m1, m2).array, + jnp.einsum("ijk,kji->j", m1.array, m2.array), + ) + ) + + +def test_einsum_unordered_ellipses(): + Height = Axis("Height", 2) + Width = Axis("Width", 3) + Depth = Axis("Depth", 4) + + m1 = hax.ones((Height, Width, Depth)) + m2 = hax.ones((Depth, Width, Height)) + + # collapse all + assert jnp.all( + jnp.equal( + einsum("{...} ->", m1, m2).array, + jnp.einsum("ijk,kji->", m1.array, m2.array), + ) + ) + + # keep all + assert jnp.all( + jnp.equal( + einsum("{...} -> ...", m1, m2).array, + jnp.einsum("ijk,kji->ijk", m1.array, m2.array), + ) + ) + + assert jnp.all( + jnp.equal( + einsum("{} -> ...", m1, m2).array, + jnp.einsum("ijk,kji->ijk", m1.array, m2.array), + ) + ) + + assert jnp.all( + jnp.equal( + einsum("{Depth} -> Depth ...", m1, m2).array, + jnp.einsum("ijk,kji->kij", m1.array, m2.array), + ) + ) + + assert jnp.all( + jnp.equal( + einsum("{Depth Height} -> Depth ... Height", m1, m2).array, + jnp.einsum("ijk,kji->kji", m1.array, m2.array), + ) + ) + + assert jnp.all( + jnp.equal( + einsum("{Depth} -> ... Depth ...", m1, m2).array, + jnp.einsum("ijk,kji->ijk", m1.array, m2.array), + ) + ) + + +def test_einsum_ordered_ellipsis(): + Height = Axis("Height", 2) + Width = Axis("Width", 3) + Depth = Axis("Depth", 4) + + m1 = hax.ones((Height, Width, Depth)) + m2 = hax.ones((Depth, Width, Height)) + + assert jnp.all( + jnp.equal( + einsum("h ... d,d ... h-> ...", m1, m2).array, + jnp.einsum("ijk,kji->j", m1.array, m2.array), + ) + ) + + assert jnp.all( + jnp.equal( + einsum("h ... d,d ... h-> ... d", m1, m2).array, + jnp.einsum("ijk,kji->jk", m1.array, m2.array), + ) + ) + + +def test_einsum_works_with_same_initial_axis_letter(): + Height = Axis("Height", 2) + Hidth = Axis("Hidth", 3) + Depth = Axis("Depth", 4) + + m1 = hax.ones((Height, Hidth, Depth)) + m2 = hax.ones((Depth, Hidth, Height)) + + assert jnp.all( + jnp.equal( + einsum("h ... d,d ... h-> ...", m1, m2).array, + jnp.einsum("ijk,kji->j", m1.array, m2.array), + ) + ) + + assert jnp.all( + jnp.equal( + einsum("{Height Hidth Depth} -> Hidth", m1, m2).array, + jnp.einsum("ijk,kji->j", m1.array, m2.array), + ) + ) + + +def test_einsum_various_errors(): + Height = Axis("Height", 2) + Hidth = Axis("Hidth", 3) + Depth = Axis("Depth", 4) + + m1 = hax.ones((Height, Hidth, Depth)) + m2 = hax.ones((Depth, Hidth, Height)) + + with pytest.raises(ValueError, match="Can't use ellipsis"): + einsum("-> ...", m1, m2) + + with pytest.raises(ValueError, match="multiple times"): + einsum("-> Height Height", m1, m2) + + with pytest.raises(ValueError, match="does not match number of arrays"): + einsum("x y z, x y z -> x", m1, m2, m1) + + with pytest.raises(ValueError, match="does not match number of arrays"): + einsum("x y z -> x", m1, m2) + + with pytest.raises(ValueError, match="Mismatched number of axes"): + einsum("x y z a b -> x", m1) + + with pytest.raises(ValueError, match="Mismatched number of axes"): + einsum("x y ... a b -> x", m1) + + with pytest.raises(ValueError, match="Mismatched number of axes"): + einsum("x y -> x", m1) + + +def test_einsum_examples(): + + Batch = hax.Axis("batch", 32) + Embed = hax.Axis("embed", 64) + H = hax.Axis("h", 16) + W = hax.Axis("w", 16) + C = hax.Axis("c", 3) + + # for jax + im = jnp.zeros((32, 16, 16, 3)) + w2 = jnp.zeros((3, 64)) + + # for haliax + hax_im = hax.zeros((Batch, H, W, C)) + hax_w2 = hax.zeros((C, Embed)) + + # Tests: + # | [`jnp.einsum("bhwc,ce -> bhwe", im, w2)`][jax.numpy.einsum] | [`hax.einsum("b h w c, c e -> b h w e", im, w2)`][haliax.einsum] | + # | [`jnp.einsum("...c,ce -> ...e", im, w2)`][jax.numpy.einsum] | [`hax.einsum("... c, c e -> ... e", im, w2)`][haliax.einsum] | + # | [`jnp.einsum("bhwc,ce -> bhw", im, w2)`][jax.numpy.einsum] | [`hax.einsum("{c embed} -> embed", im, w2)`][haliax.einsum] | + # | [`jnp.einsum("bhwc,ce -> bhw", im, w2)`][jax.numpy.einsum] | [`hax.einsum("-> batch h w embed", im, w2)`][haliax.einsum] | + + hax_out = hax.einsum("b h w c, c e -> b h w e", hax_im, hax_w2) + jnp_out = jnp.einsum("bhwc,ce -> bhwe", im, w2) + assert jnp.all(jnp.equal(hax_out.array, jnp_out)) + + hax_out = hax.einsum("... c, c e -> ... e", hax_im, hax_w2) + jnp_out = jnp.einsum("...c,ce -> ...e", im, w2) + assert jnp.all(jnp.equal(hax_out.array, jnp_out)) + + hax_out = hax.einsum("{c embed} -> embed", hax_im, hax_w2) + jnp_out = jnp.einsum("bhwc,ce -> bhwe", im, w2) + assert jnp.all(jnp.equal(hax_out.array, jnp_out)) + + hax_out = hax.einsum("-> batch h w embed", hax_im, hax_w2) + jnp_out = jnp.einsum("bhwc,ce -> bhwe", im, w2) + assert jnp.all(jnp.equal(hax_out.array, jnp_out)) + + # | [`jnp.einsum("bhwc,ce -> bhwce", im, w2)`][jax.numpy.einsum] | [`hax.einsum("{...} -> ...", im, w2)`][haliax.einsum] | + # | [`jnp.einsum("bhwc,ce -> ", im, w2)`][jax.numpy.einsum] | [`hax.einsum("{...} -> ", im, w2)`][haliax.einsum] | + + hax_out = hax.einsum("{...} -> ...", hax_im, hax_w2) + jnp_out = jnp.einsum("bhwc,ce -> bhwce", im, w2) + assert jnp.all(jnp.equal(hax_out.array, jnp_out)) + + hax_out = hax.einsum("{...} -> ", hax_im, hax_w2) + jnp_out = jnp.einsum("bhwc,ce -> ", im, w2) + assert jnp.all(jnp.equal(hax_out.array, jnp_out)) diff --git a/tests/test_hof.py b/tests/test_hof.py index 3923837..f97606c 100644 --- a/tests/test_hof.py +++ b/tests/test_hof.py @@ -74,6 +74,19 @@ def test_scan_static_args(): assert jnp.all(jnp.equal(selected.array, named1.take(Width, 2).rearrange(selected.axes).array)) +def test_scan_doesnt_scan_scalars(): + Height = Axis("Height", 10) + named1 = hax.random.uniform(PRNGKey(0), (Height,)) + + def scan_fun(acc, z, x): + return acc + z * x, x * z + + total, selected = hax.scan(scan_fun, Height)(0.0, 4.0, named1) + + assert jnp.all(jnp.isclose(total, jnp.sum(named1.array * 4.0))) + assert jnp.all(jnp.equal(selected.array, named1.array * 4.0)) + + def test_reduce(): Height = Axis("Height", 10) Width = Axis("Width", 3) @@ -118,6 +131,17 @@ def test_reduce_static_args(): assert jnp.all(jnp.isclose(total.rearrange(acc.axes).array, jnp.sum(named1.array, axis=2))) +def test_reduce_doesnt_reduce_scalars(): + Height = Axis("Height", 10) + named1 = hax.random.uniform(PRNGKey(0), (Height,)) + + acc = hax.zeros((Height,)) + + total = hax.fold(lambda x, z, y: x + z * y, Height)(acc, 4.0, named1) + + assert jnp.all(jnp.isclose(total.rearrange(acc.axes).array, jnp.sum(named1.array * 4.0))) + + def test_vmap_unmapped_args(): Batch = Axis("Batch", 10) Width = Axis("Width", 3) @@ -193,10 +217,10 @@ def test_vmap_str_args(): assert selected.axes == expected_names # also ensure that this works when we return a non-haliax array - def vmap_fun(x): + def vmap_fun2(x): return x.sum(Width).array - selected = hax.vmap(vmap_fun, "Batch")(named1) + selected = hax.vmap(vmap_fun2, "Batch")(named1) assert jnp.all(jnp.equal(selected, expected_jax)) diff --git a/tests/test_ops.py b/tests/test_ops.py index 27f4778..dd89736 100644 --- a/tests/test_ops.py +++ b/tests/test_ops.py @@ -203,12 +203,25 @@ def test_mean_respects_where(): named1 = hax.random.uniform(PRNGKey(0), (Height, Width)) where = hax.random.uniform(PRNGKey(1), (Height, Width)) > 0.5 - assert not jnp.all(jnp.isclose(hax.mean(named1).array, hax.mean(named1, where=where).array)) - assert jnp.all(jnp.isclose(hax.mean(named1, where=where).array, jnp.mean(named1.array, where=where.array))) + assert not jnp.all(jnp.isclose(hax.mean(named1), hax.mean(named1, where=where))) + assert jnp.all(jnp.isclose(hax.mean(named1, where=where), jnp.mean(named1.array, where=where.array))) # check broadcasting where = hax.random.uniform(PRNGKey(2), (Height,)) > 0.5 - assert not jnp.all(jnp.isclose(hax.mean(named1).array, hax.mean(named1, where=where).array)) + assert not jnp.all(jnp.isclose(hax.mean(named1), hax.mean(named1, where=where))) assert jnp.all( - jnp.isclose(hax.mean(named1, where=where).array, jnp.mean(named1.array, where=where.array.reshape((-1, 1)))) + jnp.isclose(hax.mean(named1, where=where), jnp.mean(named1.array, where=where.array.reshape((-1, 1)))) ) + + +def test_reductions_produce_scalar_named_arrays_when_None_axis(): + Height = Axis("Height", 10) + Width = Axis("Width", 3) + + named1 = hax.random.uniform(PRNGKey(0), (Height, Width)) + + assert isinstance(hax.mean(named1, axis=None), NamedArray) + + # But if we specify axes, we always get a NamedArray, even if it's a scalar + assert isinstance(hax.mean(named1, axis=("Height", "Width")), NamedArray) + assert hax.mean(named1, axis=("Height", "Width")).axes == () diff --git a/tests/test_parsing.py b/tests/test_parsing.py new file mode 100644 index 0000000..ba9380b --- /dev/null +++ b/tests/test_parsing.py @@ -0,0 +1,182 @@ +import pytest + +from haliax._src.parsing import parse_einsum, parse_rearrangement + + +def _simplify_captures(expr): + def simplify_capture(capture): + if capture == Ellipsis: + return Ellipsis + elif (capture.binding == capture.axes[0] or capture.binding is None) and len(capture.axes) == 1: + return capture.axes[0] + elif capture.binding is None: + return capture.axes + else: + return {capture.binding: capture.axes} + + return [simplify_capture(capture) for capture in expr.captures] + + +def test_parse_rearrangement_simple(): + lhs, rhs = parse_rearrangement("a b c d -> b c a d") + assert lhs.is_ordered + assert _simplify_captures(lhs) == ["a", "b", "c", "d"] + assert rhs.is_ordered + assert _simplify_captures(rhs) == ["b", "c", "a", "d"] + + lhs, rhs = parse_rearrangement("a ... c d -> b c a d") + assert lhs.is_ordered + assert _simplify_captures(lhs) == ["a", Ellipsis, "c", "d"] + assert rhs.is_ordered + assert _simplify_captures(rhs) == ["b", "c", "a", "d"] + + # longer identifiers + lhs, rhs = parse_rearrangement("a_longer b123 c d -> b123 c a_longer d") + assert lhs.is_ordered + assert _simplify_captures(lhs) == ["a_longer", "b123", "c", "d"] + assert rhs.is_ordered + assert _simplify_captures(rhs) == ["b123", "c", "a_longer", "d"] + + +def test_parse_einsum_ordered(): + # We could support this syntax for dot with something like: + # + # support normal einops syntax, including short name-capture: hax.dot("... c h w, h w d -> ... c d", a, b) + # hax.dot("{h, w} -> ", a, b) means "contract h and w", analogous to hax.dot(a, b, axis=("h", "w")) + # hax.dot("{h, w} -> ... channel embed", a, b) means "contract h and w and ensure that the result ends with [channel, embed]" (by transposing/einsum) + # hax.dot(" -> batch channel embed", a, b) could mean "contract all but the named dims". Not entirely sure how I feel about that one, but used situationally it's probably ok + + lhses, rhs = parse_einsum("a b c d, b c e f -> a d e f") + assert lhses is not None + assert len(lhses) == 2 + assert all(lhs.is_ordered for lhs in lhses) + lhs0_captures = _simplify_captures(lhses[0]) + lhs1_captures = _simplify_captures(lhses[1]) + assert lhs0_captures == ["a", "b", "c", "d"] + assert lhs1_captures == ["b", "c", "e", "f"] + assert rhs.is_ordered + assert _simplify_captures(rhs) == ["a", "d", "e", "f"] + + lhses, rhs = parse_einsum("... c h w, h w d -> ... c d") + assert lhses is not None + assert len(lhses) == 2 + assert all(lhs.is_ordered for lhs in lhses) + lhs0_captures = _simplify_captures(lhses[0]) + lhs1_captures = _simplify_captures(lhses[1]) + assert lhs0_captures == [..., "c", "h", "w"] + assert lhs1_captures == ["h", "w", "d"] + assert rhs.is_ordered + assert _simplify_captures(rhs) == [..., "c", "d"] + + lhses, rhs = parse_einsum("{...} -> batch channel embed") + assert lhses is not None + assert len(lhses) == 1 + assert not lhses[0].is_ordered + assert _simplify_captures(lhses[0]) == [...] + assert rhs.is_ordered + assert _simplify_captures(rhs) == ["batch", "channel", "embed"] + + # just lhs + lhses, rhs = parse_einsum("batch channel embed -> ") + assert lhses is not None + assert len(lhses) == 1 + assert lhses[0].is_ordered + assert _simplify_captures(lhses[0]) == ["batch", "channel", "embed"] + assert rhs.is_ordered + assert _simplify_captures(rhs) == [] + + # lhs x 2, empty rhs + lhses, rhs = parse_einsum("batch channel embed, batch channel embed ->") + assert lhses is not None + assert len(lhses) == 2 + assert all(lhs.is_ordered for lhs in lhses) + assert _simplify_captures(lhses[0]) == ["batch", "channel", "embed"] + assert _simplify_captures(lhses[1]) == ["batch", "channel", "embed"] + assert rhs.is_ordered + assert _simplify_captures(rhs) == [] + + +def test_parse_einsum_unordered(): + lhses, rhs = parse_einsum("{a, b} -> ") + assert lhses is not None + assert len(lhses) == 1 + assert not lhses[0].is_ordered + assert _simplify_captures(lhses[0]) == ["a", "b"] + assert rhs.is_ordered + assert _simplify_captures(rhs) == [] + + lhses, rhs = parse_einsum("{...} -> ") + assert lhses is not None + assert len(lhses) == 1 + assert not lhses[0].is_ordered + assert _simplify_captures(lhses[0]) == [...] + assert rhs.is_ordered + assert _simplify_captures(rhs) == [] + + lhses, rhs = parse_einsum("{h, w} -> ... channel embed") + assert lhses is not None + assert len(lhses) == 1 + assert not lhses[0].is_ordered + assert _simplify_captures(lhses[0]) == ["h", "w"] + assert rhs.is_ordered + assert _simplify_captures(rhs) == [..., "channel", "embed"] + + +def test_parse_paren_groups(): + lhs, rhs = parse_rearrangement("a (b c) d -> b c a d") + assert lhs.is_ordered + assert _simplify_captures(lhs) == ["a", ("b", "c"), "d"] + assert rhs.is_ordered + assert _simplify_captures(rhs) == ["b", "c", "a", "d"] + + lhs, rhs = parse_rearrangement("a (b: c) (d: e f) -> b c a d") + assert lhs.is_ordered + assert _simplify_captures(lhs) == ["a", {"b": ("c",)}, {"d": ("e", "f")}] + + +def test_parse_unordered(): + lhs, rhs = parse_rearrangement("{a b c d} -> {b c a d}") + assert not lhs.is_ordered + assert _simplify_captures(lhs) == ["a", "b", "c", "d"] + assert not rhs.is_ordered + assert _simplify_captures(rhs) == ["b", "c", "a", "d"] + + lhs, rhs = parse_rearrangement("{(c: a b) d e} -> (q: a d e) b") + assert not lhs.is_ordered + assert _simplify_captures(lhs) == [{"c": ("a", "b")}, "d", "e"] + assert rhs.is_ordered + assert _simplify_captures(rhs) == [{"q": ("a", "d", "e")}, "b"] + + +def test_parse_quoted_identifiers(): + lhs, rhs = parse_rearrangement("a \"b c\" d -> 'b c' a d") + assert lhs.is_ordered + assert _simplify_captures(lhs) == ["a", "b c", "d"] + assert rhs.is_ordered + assert _simplify_captures(rhs) == ["b c", "a", "d"] + + lhs, rhs = parse_rearrangement("{a \"b c\" (d: 'hello')} -> b c a d") + assert not lhs.is_ordered + assert _simplify_captures(lhs) == ["a", "b c", {"d": ("hello",)}] + assert rhs.is_ordered + assert _simplify_captures(rhs) == ["b", "c", "a", "d"] + + +def test_parse_errors(): + with pytest.raises(ValueError, match="Unexpected end of string"): + parse_rearrangement("a b") + + with pytest.raises(ValueError, match="Expected }"): + parse_rearrangement("{ a -> c") + + with pytest.raises(ValueError, match="Unexpected }"): + parse_rearrangement("a } -> c") + + with pytest.raises(ValueError, match="Unexpected }"): + parse_rearrangement("(a: b } -> c") + + with pytest.raises(ValueError, match="Unexpected character"): + parse_rearrangement("(a b ! -> c d e") + + with pytest.raises(ValueError, match="Identifier expected"): + parse_rearrangement("a b ! -> c d e") diff --git a/tests/test_rearrange.py b/tests/test_rearrange.py index 0b58251..0e0dbf8 100644 --- a/tests/test_rearrange.py +++ b/tests/test_rearrange.py @@ -3,102 +3,7 @@ from jax.random import PRNGKey import haliax as hax from haliax import Axis -from haliax._src.rearrange import einops_rearrange, parse_rearrangement - - -def _simplify_captures(expr): - def simplify_capture(capture): - if capture == Ellipsis: - return Ellipsis - elif (capture.binding == capture.axes[0] or capture.binding is None) and len(capture.axes) == 1: - return capture.axes[0] - elif capture.binding is None: - return capture.axes - else: - return {capture.binding: capture.axes} - - return [simplify_capture(capture) for capture in expr.captures] - - -def test_parse_rearrangement_simple(): - lhs, rhs = parse_rearrangement("a b c d -> b, c, a, d") - assert lhs.is_ordered - assert _simplify_captures(lhs) == ["a", "b", "c", "d"] - assert rhs.is_ordered - assert _simplify_captures(rhs) == ["b", "c", "a", "d"] - - lhs, rhs = parse_rearrangement("a ... c d -> b c a d") - assert lhs.is_ordered - assert _simplify_captures(lhs) == ["a", Ellipsis, "c", "d"] - assert rhs.is_ordered - assert _simplify_captures(rhs) == ["b", "c", "a", "d"] - - # longer identifiers - lhs, rhs = parse_rearrangement("a_longer b123 c d -> b123 c a_longer d") - assert lhs.is_ordered - assert _simplify_captures(lhs) == ["a_longer", "b123", "c", "d"] - assert rhs.is_ordered - assert _simplify_captures(rhs) == ["b123", "c", "a_longer", "d"] - - -def test_parse_paren_groups(): - lhs, rhs = parse_rearrangement("a (b c) d -> b c a d") - assert lhs.is_ordered - assert _simplify_captures(lhs) == ["a", ("b", "c"), "d"] - assert rhs.is_ordered - assert _simplify_captures(rhs) == ["b", "c", "a", "d"] - - lhs, rhs = parse_rearrangement("a (b: c) (d: e f) -> b c a d") - assert lhs.is_ordered - assert _simplify_captures(lhs) == ["a", {"b": ("c",)}, {"d": ("e", "f")}] - - -def test_parse_unordered(): - lhs, rhs = parse_rearrangement("{a b c d} -> {b c a d}") - assert not lhs.is_ordered - assert _simplify_captures(lhs) == ["a", "b", "c", "d"] - assert not rhs.is_ordered - assert _simplify_captures(rhs) == ["b", "c", "a", "d"] - - lhs, rhs = parse_rearrangement("{(c: a b), d e,} -> (q: a d e) b") - assert not lhs.is_ordered - assert _simplify_captures(lhs) == [{"c": ("a", "b")}, "d", "e"] - assert rhs.is_ordered - assert _simplify_captures(rhs) == [{"q": ("a", "d", "e")}, "b"] - - -def test_parse_quoted_identifiers(): - lhs, rhs = parse_rearrangement("a \"b c\" d -> 'b c' a d") - assert lhs.is_ordered - assert _simplify_captures(lhs) == ["a", "b c", "d"] - assert rhs.is_ordered - assert _simplify_captures(rhs) == ["b c", "a", "d"] - - lhs, rhs = parse_rearrangement("{a \"b c\" (d: 'hello')} -> b c a d") - assert not lhs.is_ordered - assert _simplify_captures(lhs) == ["a", "b c", {"d": ("hello",)}] - assert rhs.is_ordered - assert _simplify_captures(rhs) == ["b", "c", "a", "d"] - - -def test_parse_errors(): - with pytest.raises(ValueError, match="Unexpected end of string"): - parse_rearrangement("a b") - - with pytest.raises(ValueError, match="Expected }"): - parse_rearrangement("{ a -> c") - - with pytest.raises(ValueError, match="Unexpected }"): - parse_rearrangement("a } -> c") - - with pytest.raises(ValueError, match="Unexpected }"): - parse_rearrangement("(a: b } -> c") - - with pytest.raises(ValueError, match="Unexpected character"): - parse_rearrangement("(a b ! -> c d e") - - with pytest.raises(ValueError, match="Identifier expected"): - parse_rearrangement("a b ! -> c d e") +from haliax._src.rearrange import einops_rearrange # some axes @@ -108,6 +13,7 @@ C = Axis("C", 3) D = Axis("D", 2) B = Axis("B", 5) Q = hax.Axis("Q", B.size * H.size) +E = Axis("E", H.size * W.size * D.size) z = hax.random.randint(PRNGKey(0), (B, D, H, W, C), 0, 255) zq = hax.random.randint(PRNGKey(0), (Q, D, W, C), 0, 255) @@ -182,16 +88,16 @@ def test_rearrange_with_flattening_unordered(): def test_rearrange_with_unflatten(): - assert einops_rearrange(zq, "(Q: B H) d, w c -> B d H w c", B=5).axes == (B, D, H, W, C) + assert einops_rearrange(zq, "(Q: B H) d w c -> B d H w c", B=5).axes == (B, D, H, W, C) # make sure the values are right too z_t = zq.array.reshape((B.size, H.size, D.size, W.size, C.size)).transpose((0, 2, 1, 3, 4)) - assert (einops_rearrange(zq, "(Q: B H) d, w c -> B d H w c", B=5).array == z_t).all() + assert (einops_rearrange(zq, "(Q: B H) d w c -> B d H w c", B=5).array == z_t).all() # test with explicit axis arg - assert einops_rearrange(zq, "(Q: b H) d, w c -> b d H w c", b=B).axes == (B, D, H, W, C) + assert einops_rearrange(zq, "(Q: b H) d w c -> b d H w c", b=B).axes == (B, D, H, W, C) # make sure the values are right too z_t = zq.array.reshape((B.size, H.size, D.size, W.size, C.size)).transpose((0, 2, 1, 3, 4)) - assert (einops_rearrange(zq, "(Q: b H) d, w c -> b d H w c", b=B).array == z_t).all() + assert (einops_rearrange(zq, "(Q: b H) d w c -> b d H w c", b=B).array == z_t).all() def test_rearrange_with_unflatten_unordered(): @@ -231,6 +137,27 @@ def test_with_unflatten_flatten_unordered(): assert (einops_rearrange(zq, "{ W D C (Q: B H)} -> D (Z: B C) W H", H=H).array == z_t).all() +def test_rearrange_multiple_ellipses(): + z_out = einops_rearrange(z, "b d h w c -> d ... c ... h") + assert z_out.axes == (D, B, C, W, H) + + z_out = einops_rearrange(z, "b d h w c -> d ... (Q: b h) ... w") + assert z_out.axes == (D, Q, C, W) + + z_out = einops_rearrange(z, "b d h w c -> d ... (BB: b) ... w") + assert z_out.axes == (D, B.alias("BB"), H, C, W) + + z_out = einops_rearrange(z, "{H W D} -> ... (E: H W D) ...") + assert z_out.axes == (B, E, C) + + z_out = einops_rearrange(z, "{B H} -> ... (Q: B H) ...") + assert z_out.axes == (Q, D, W, C) + + z_out = einops_rearrange(z, "{B H W} -> ... (Q: B H) ... W") + + assert z_out.axes == (Q, D, C, W) + + def test_semantic_errors(): with pytest.raises(ValueError, match="Too many axes in lhs"): einops_rearrange(z, "b d h w c q -> b d h w c q") @@ -247,9 +174,6 @@ def test_semantic_errors(): with pytest.raises(ValueError, match="Only one ellipsis allowed"): einops_rearrange(z, "b d ... h w c ... -> b d h w c ...") - with pytest.raises(ValueError, match="Only one ellipsis allowed"): - einops_rearrange(z, "b d ... h w c -> ... b d h w c ...") - with pytest.raises(ValueError, match="Capture q is assigned more than once"): einops_rearrange(z, "b d c q q -> b d h w c q") @@ -322,7 +246,7 @@ def test_examples(): # > without rearrange or names: x.reshape((a * b, c, d)) # split a into b and c # * '(a: b c) d -> b c d' - assert einops_rearrange(zq, "(q: b h) d, w, c -> b h d w c", b=B, h="H").axes == (B, H, D, W, C) + assert einops_rearrange(zq, "(q: b h) d w c -> b h d w c", b=B, h="H").axes == (B, H, D, W, C) # > without rearrange or names: x.reshape((b, c, d)) # reorder a and b # * 'a b ... -> b a ...' diff --git a/tests/test_tree_util.py b/tests/test_tree_util.py index c1bb89d..4c93edd 100644 --- a/tests/test_tree_util.py +++ b/tests/test_tree_util.py @@ -33,4 +33,4 @@ def test_resize_axis(): assert module2.name3.axes == (NewA,) # we don't mess with the mean or std of the original array too much - assert jnp.allclose(module2.name1.mean().array, module.name1.mean().array, rtol=1e-1, atol=1e-2) + assert jnp.allclose(module2.name1.mean(), module.name1.mean(), rtol=1e-1, atol=1e-2) commit dcb3ba9f815066f9e705aadec458b8830d0b8947 Date: 2024-03-04T23:52:26-08:00 explicitly shard scalars (#73) diff --git a/src/haliax/partitioning.py b/src/haliax/partitioning.py index 4d04421..2c3690b 100644 --- a/src/haliax/partitioning.py +++ b/src/haliax/partitioning.py @@ -232,6 +232,8 @@ def infer_resource_partitions( # else: # return AUTO return NamedSharding(mesh, PartitionSpec(None)) + elif isinstance(node, (bool, float, complex, int)): + return NamedSharding(mesh, PartitionSpec()) else: return None @@ -279,8 +281,8 @@ class _NamedJitWrapper(eqx.Module): in_axis_resources = self._in_axis_resources out_axis_resources = self._out_axis_resources - if out_axis_resources is None: - out_axis_resources = axis_resources + # if out_axis_resources is None: + # out_axis_resources = axis_resources dynamic_argspec, static_argspec = hashable_partition((args, kwargs), is_jax_array_like) dynamic = (self._dynamic_fun, dynamic_argspec) commit b94cef72e8bafec57e170fceb9ee86bbe2b1bcfa Date: 2024-03-06T23:18:47-08:00 workaround current limitation in jax_metals (#74) diff --git a/src/haliax/jax_utils.py b/src/haliax/jax_utils.py index 9f66d9a..77acd8a 100644 --- a/src/haliax/jax_utils.py +++ b/src/haliax/jax_utils.py @@ -149,3 +149,7 @@ def is_scalarish(x): return x.ndim == 0 else: return jnp.isscalar(x) or x.shape == () + + +def is_on_mac_metal(): + return jax.devices()[0].platform.lower() == "metal" diff --git a/src/haliax/partitioning.py b/src/haliax/partitioning.py index 2c3690b..6842231 100644 --- a/src/haliax/partitioning.py +++ b/src/haliax/partitioning.py @@ -18,7 +18,7 @@ from haliax._src.compile_utils import compile_cache from .axis import Axis, AxisSelection, AxisSelector from .core import NamedArray -from .jax_utils import Static, is_in_jit, is_jax_array_like +from .jax_utils import Static, is_in_jit, is_jax_array_like, is_on_mac_metal from .tree_util import hashable_combine, hashable_partition from .util import StringHolderEnum, ensure_tuple, is_named_array @@ -136,6 +136,9 @@ def shard(x: T, mapping: Optional[ResourceMapping] = None, mesh: Optional[Mesh] if _is_jit_tracer(x.array): pspec = pspec_for_axis(x.axes, mapping) + if is_on_mac_metal(): + warnings.warn("Sharding constraints are not supported in jit on metal", RuntimeWarning) + return x return with_sharding_constraint(x, pspec) elif not is_jax_array_like(x.array): # this happens when we filter out params for things like lora commit 74e024eb4efed73fa41df7b1cf6f555ed11ad0f6 Date: 2024-03-11T14:53:57-07:00 Make an alternative to Stacked with no scanlayers (#76) diff --git a/docs/nn.md b/docs/nn.md index 32a43cf..4203c5b 100644 --- a/docs/nn.md +++ b/docs/nn.md @@ -21,6 +21,8 @@ of the same module (e.g. transformer blocks), which is a common pattern in deep ### Meta +::: haliax.nn.scan.BlockFoldable +::: haliax.nn.BlockSeq ::: haliax.nn.Stacked ::: haliax.nn.MLP diff --git a/src/haliax/nn/__init__.py b/src/haliax/nn/__init__.py index 41e64fa..745575a 100644 --- a/src/haliax/nn/__init__.py +++ b/src/haliax/nn/__init__.py @@ -38,7 +38,7 @@ from .loss import binary_cross_entropy_loss, cross_entropy_loss, cross_entropy_l from .mlp import MLP from .normalization import LayerNorm, log_softmax, logsumexp, softmax, standardize from .pool import max_pool, mean_pool, min_pool -from .scan import Stacked +from .scan import BlockSeq, Stacked # TODO: support where in softmax, etc @@ -85,6 +85,8 @@ __all__ = [ "Linear", "Embedding", "Stacked", + "BlockSeq", + "MLP", "relu", "gelu", "quick_gelu", diff --git a/src/haliax/nn/scan.py b/src/haliax/nn/scan.py index 8d5ecad..e651aff 100644 --- a/src/haliax/nn/scan.py +++ b/src/haliax/nn/scan.py @@ -11,14 +11,130 @@ from haliax.jax_utils import filter_checkpoint from ..axis import Axis -M = TypeVar("M", bound=eqx.Module, covariant=True) +M = TypeVar("M", bound=eqx.Module) +M_co = TypeVar("M_co", bound=eqx.Module, covariant=True) +S = TypeVar("S", bound=eqx.Module) +T = TypeVar("T") -class ModuleInit(Protocol[M]): - def __call__(self, *args, **kwargs) -> M: +class ModuleInit(Protocol[M_co]): + def __call__(self, *args, **kwargs) -> M_co: ... +class BlockFoldable(Protocol[M]): + """ + A superclass for [haliax.nn.Stacked][] and [haliax.nn.BlockSeq][] that exposes the fold and scan methods, as + well as a few other methods that are useful for these modules. + + This is a protocol, so you can use it as a type hint for a function that takes a Stacked or BlockSeq. + Equinox modules can't directly inherit from Protocols, but you can use it as a type hint. + """ + + Block: Axis + + @classmethod + def init( + cls: Type[S], Block: Axis, module: Type[M], *, gradient_checkpointing: bool = False, prevent_cse: bool = False + ) -> ModuleInit[S]: + ... + + def scan(self, init: T, *extra_args, **extra_kwargs): + ... + + def fold(self, init: T, *args, **kwargs) -> T: + ... + + def unstacked(self) -> Sequence[M]: + ... + + +class BlockSeq(eqx.Module, Generic[M]): + """ + A "BlockSeq" wraps another module and produces a "sequential" version of it, where an input is applied + to each instance of the sequential module in sequence. This is useful for e.g. transformers + where you have multiple instances of the same transformer block and the input is applied in a fold/for loop + in sequence. + + It's similar in spirit to an [equinox.nn.Sequential]. Unlike [equinox.nn.Stacked][], BlockSeq does not need to be + homogeneous (though the init method assumes that it is). + """ + + blocks: Sequence[M] + Block: Axis = eqx.static_field() + gradient_checkpointing: bool = eqx.static_field() + + @classmethod + def init( + cls: Type[S], Block: Axis, module: Type[M], *, gradient_checkpointing: bool = False, prevent_cse: bool = False + ) -> ModuleInit[S]: + """ + This is a curried init method that takes the Block and module and returns a function that takes + the arguments to the module's init method. Any NamedArrays in the arguments will be sliced along the + Block axis (if it exists). JAX arrays will be sliced along the first axis. + """ + del prevent_cse # not needed, but kept for compat with Stacked + + @functools.wraps(module) + def fn(*args, **kwargs): + # The only complexity here is that the args and kwargs might have a Block axis in them, + # in which case we need to loop over them them to slice them out. + + def init_block(i): + (block_args, block_kwargs) = haliax.tree_util.tree_map( + functools.partial(BlockSeq._slice_out, Block, i), (args, kwargs) + ) + return module.init(*block_args, **block_kwargs) + + seq = [init_block(i) for i in range(Block.size)] + + return BlockSeq(seq, Block, gradient_checkpointing) + + return fn + + def scan(self, init: T, *extra_args, **extra_kwargs): + out = [] + carry = init + + for i, block in enumerate(self.blocks): + if self.gradient_checkpointing: + block = filter_checkpoint(block) + (block_args, block_kwargs) = haliax.tree_util.tree_map( + functools.partial(BlockSeq._slice_out, self.Block, i), (extra_args, extra_kwargs) + ) + carry, extra = block(carry, *block_args, **block_kwargs) + out.append(extra) + + # TODO: do we want to stack the outputs? + return carry, out + + def fold(self, init: T, *args, **kwargs) -> T: + carry = init + for i, block in enumerate(self.blocks): + if self.gradient_checkpointing: + block = filter_checkpoint(block) + (block_args, block_kwargs) = haliax.tree_util.tree_map( + functools.partial(BlockSeq._slice_out, self.Block, i), (args, kwargs) + ) + carry = block(carry, *block_args, **block_kwargs) + return carry + + def unstacked(self) -> Sequence[M]: + return self.blocks + + @staticmethod + def _slice_out(Block, i, x): + if haliax.is_named_array(x) and haliax.selects_axis(x.axes, Block): + return x[Block, i] + elif haliax.jax_utils.is_jax_array_like(x): + return x[i] + else: + return x + + def _state_dict_key_map(self) -> Dict[str, Optional[str]]: + return {"blocks": None} + + class Stacked(eqx.Module, Generic[M]): """ A "Stacked" wraps another module and produces a "stacked" version of it, where an input is applied @@ -68,9 +184,9 @@ class Stacked(eqx.Module, Generic[M]): gradient_checkpointing: bool = eqx.static_field() prevent_cse: bool = eqx.static_field() - @staticmethod + @classmethod def init( - Block: Axis, module: Type[M], *, gradient_checkpointing: bool = False, prevent_cse: bool = False + cls, Block: Axis, module: Type[M], *, gradient_checkpointing: bool = False, prevent_cse: bool = False ) -> ModuleInit["Stacked[M]"]: """ Initialize a Stacked module. This method is curried: you can pass in the Block and module, and it will return diff --git a/tests/test_scan.py b/tests/test_scan.py index 0120c30..d01896a 100644 --- a/tests/test_scan.py +++ b/tests/test_scan.py @@ -2,7 +2,7 @@ import equinox as eqx import jax import haliax as hax -from haliax.nn.scan import Stacked +from haliax.nn.scan import BlockSeq, Stacked def test_unstacked(): @@ -11,7 +11,7 @@ def test_unstacked(): array: jax.Array static: int = eqx.static_field() - def __call__(self, x): + def __call__(self, x, *, key): return x + self.array + self.static @staticmethod @@ -40,3 +40,31 @@ def test_unstacked(): assert hax.all(module.named == m.stacked.named["block", i]) assert hax.all(module.array == m.stacked.array[i]) + + +def test_seq_and_stacked_give_same_results(): + class Module(eqx.Module): + named: hax.NamedArray + array: jax.Array + static: int = eqx.static_field() + + def __call__(self, x, *, key): + return x + self.array + self.static + hax.random.normal(key, x.axes) + + @staticmethod + def init(named, array, static): + return Module(named=named, array=array, static=static) + + Block = hax.Axis("block", 4) + E = hax.Axis("E", 10) + + initial_named = hax.random.uniform(jax.random.PRNGKey(0), (Block, E)) + + m = Stacked.init(Block, Module)(named=initial_named, array=jax.numpy.ones(Block.size), static=1) + m_seq = BlockSeq.init(Block, Module)(named=initial_named, array=jax.numpy.ones(Block.size), static=1) + + x = hax.random.uniform(jax.random.PRNGKey(1), (E,)) + y = m.fold(x, key=jax.random.split(jax.random.PRNGKey(2), Block.size)) + y_seq = m_seq.fold(x, key=jax.random.split(jax.random.PRNGKey(2), Block.size)) + + assert hax.all(hax.isclose(y, y_seq, atol=1e-5)) commit 27ab675a57f917faf3e6fa5438906766a85fd55b Date: 2024-03-12T10:29:16-07:00 use the default out_axis_resources again because sharding propagation doesn't seem to work diff --git a/src/haliax/partitioning.py b/src/haliax/partitioning.py index 6842231..d7ee32f 100644 --- a/src/haliax/partitioning.py +++ b/src/haliax/partitioning.py @@ -284,8 +284,8 @@ class _NamedJitWrapper(eqx.Module): in_axis_resources = self._in_axis_resources out_axis_resources = self._out_axis_resources - # if out_axis_resources is None: - # out_axis_resources = axis_resources + if out_axis_resources is None: + out_axis_resources = axis_resources dynamic_argspec, static_argspec = hashable_partition((args, kwargs), is_jax_array_like) dynamic = (self._dynamic_fun, dynamic_argspec) commit c43b10ca24b04224643e6540e8a71bfe23c1045d Date: 2024-03-14T14:10:19-07:00 Add FP8 support to Haliax (#77) diff --git a/.github/workflows/run_tests.yaml b/.github/workflows/run_tests.yaml index 1e43042..0c82cc0 100644 --- a/.github/workflows/run_tests.yaml +++ b/.github/workflows/run_tests.yaml @@ -20,7 +20,7 @@ jobs: run: | python -m pip install --upgrade pip pip install flake8 pytest - pip install --upgrade "jax[cpu]==0.4.14" "jaxlib[cpu]==0.4.14" + pip install --upgrade "jax[cpu]==0.4.25" "jaxlib[cpu]==0.4.25" pip install . # - name: Lint with flake8 # run: | diff --git a/docs/fp8.md b/docs/fp8.md new file mode 100644 index 0000000..9318bba --- /dev/null +++ b/docs/fp8.md @@ -0,0 +1,156 @@ +# FP8 Training + +!!! warning + FP8 training in Haliax is currently experimental and may change in the future. + +FP8 refers to 8-bit floating point numbers. FP8 is a massively reduced precision compared to the 32-bit floating point numbers +or 16-bit floating point numbers that are typically used in deep learning: there are only 256 possible values in FP8, compared to +the (almost) 2^32 in 32-bit and 2^16 in 16-bit. However, FP8 is still useful for training deep learning models, especially on +hardware that is optimized for FP8. In particular, it can massively accelerate training on hardware that is optimized for FP8: +H100 has 2x FP8 FLOPS compared to FP16 FLOPS and almost 60x(!) compared to F32 FLOPS. + +The FP8 in Haliax is currently designed to optimize throughput on FP8-enabled devices (currently H100) rather +than to save memory. In particular, Haliax's FP8 support is not designed to quantize a model to FP8 for deployment, +though this shouldn't be that hard to add for models that were trained using this functionality. +We would be happy to accept contributions to add this functionality, +and are happy to work with you to do so. In particular, adding this for models trained using Haliax's FP8 should be easy. + +## TL;DR + +Using FP8 with Haliax is actually pretty straightforward. To enable FP8, do this: + +```python +import haliax.quantization as haxq +# setup +module = haxq.fp8_linear_layers(module) + +# if using optax. This saves a tiny amount of memory so you can skip it if you want +_, trainable_module = haxq.partition_for_grad_overwrite(module) +opt_state = opt.initial_state(trainable_module) + +# train step +grads = eqx.filter_grad(loss_fn)(module, data) +overwrite, grads = haxq.partition_for_grad_overwrite(grads) +updates, opt_state = opt.update(grads, opt_state, params=module) # or however you update your optimizer +module = haxq.apply_updates(module, updates, overwrite) +``` + +And train your model like normal. + +## How to use FP8 + +To use FP8, you need to do two things: + +* Enable FP8 for the layers you want to use FP8 +* Modify your training step to be compatible with FP8 + +Each of these is just a couple of lines of code. + + +```python +import haliax as hax +import equinox as eqx +import jax + +In = hax.Axis("In", 32) +Mid = hax.Axis("Mid", 128) +Out = hax.Axis("Out", 16) +Hidden = hax.Axis("Hidden", 64) + + +class MyModule(eqx.Module): + up_proj: hax.nn.Linear + down_proj: hax.nn.Linear + + @staticmethod + def init(*, key): + super().__init__() + k_up, k_down = jax.random.split(key) + return MyModule( + up_proj=hax.nn.Linear.init(In, Mid, key=k_up), + down_proj=hax.nn.Linear.init(Mid, Out, key=k_down), + ) + + def __call__(self, x): + x = self.up_proj(x) + x = hax.nn.relu(x) + x = self.down_proj(x) + return x + +module = MyModule.init(key=jax.random.PRNGKey(0)) + +# Enable FP8 +module = hax.quantization.fp8_linear_layers(module) + +# Enable FP8 for a specific layer +from haliax.quantization import Fp8Config + +config = Fp8Config(targets=["up_proj"]) +module = hax.quantization.fp8_linear_layers(module, config) + +# Train step +grads = eqx.filter_grad(loss_fn)(module, data) +overwrite, grads = haxq.partition_for_grad_overwrite(grads) +updates, opt_state = opt.update(grads, opt_state, params=module) # or however you update your optimizer +module = hax.quantization.apply_updates(module, updates, grads) +``` + +That's it! Just a few lines of code to enabl e FP8. The `fp8_linear_layers` function will transform your module to use FP8 +for linear layers (or a subset if you want), and the combo of `partition_for_grad_overwrite` and `apply_updates` function will apply the updates to the module +in a way that is compatible with FP8. + +## How FP8 works + +For an overview of the FP8, see the [FP8 Primer](https://docs.nvidia.com/deeplearning/transformer-engine/user-guide/examples/fp8_primer.html). +You don't need to understand it though. Haliax's FP8 integration is more or less plug and play, as shown above. +The implementation of FP8 in Haliax is more or less a straightforward port (including some copy and paste) of the +[FP8 implementation in Flax](https://github.com/google/flax/blob/main/flax/linen/fp8_ops.py). + +FP8 in JAX (as well as INT8) is typically implemented using "`dot_general` injection", where you pass +a custom implementation of `dot_general` to functions and modules like [haliax.dot][] and [haliax.nn.Linear][]. +The `dot_general` for FP8 is implemented by scaling +the inputs, projecting the inputs to FP8, performing the computation in FP8, and then +scaling the result back to the original precision. +The subtle part of FP8 is that the scaling is a parameter that is trained based on a history of the inputs to the layer +(as well as gradients coming in from backward). This means that the FP8 `dot_general` needs to maintain state. +In Equinox, this means that the `dot_general` is actually a `Module` that packages together the state and the +computation. (Unlike [equinox.nn.StatefulLayer][] which returns a state object you pass back into the module, the FP8 `dot_general` +module hijacks the gradient computation to update its state. This is necessary because the FP8 scaling factors +depend on the gradients.) + +The way this happens is by "hijacking" the gradient computation. When you call `eqx.filter_grad(loss_fn)(module, data)`, +you will get the gradient computation as normal, but you'll also get the updated state of the FP8 `dot_general` module. +This updated state needs to directly replace the state in the module (rather than be used for a gradient step), which is +why you need to use the `partition_for_grad_overwrite` + +The FP8 `dot_general` module is implemented in [haliax.quantization.Fp8DotGeneral][]. It's actually not that complicated: + +1) It holds a scaling factor and history of maximum values for each of (lhs, rhs, output) and updates them based on the +gradients. +2) When invoked, it scales the inputs, projects them to FP8, performs the computation, and scales the result back to the +original precision. It remembers the maximum absolute value for each of the inputs. +3) For the gradients, it scales the gradients, projects them to FP8, does the backward computation, +and scales the gradients back to the original precision. It remembers the maximum absolute value for the incoming +gradient and stores it in the gradient. + +# API Reference + +## Functions + +::: haliax.quantization.fp8_linear_layers +::: haliax.quantization.partition_for_grad_overwrite +::: haliax.quantization.apply_updates + + +## Interfaces +::: haliax.quantization.DotGeneralOp +::: haliax.quantization.OverwriteWithGradient + +## Modules + + +::: haliax.quantization.Fp8DotGeneralOp + +## Configuration + +::: haliax.quantization.Fp8Config diff --git a/mkdocs.yml b/mkdocs.yml index 4d52dad..d90c971 100644 --- a/mkdocs.yml +++ b/mkdocs.yml @@ -87,5 +87,6 @@ nav: - Neural Networks: 'nn.md' - Partitioning: 'partitioning.md' - Higher Order Functions: 'hof.md' + - FP8: 'fp8.md' - API Reference: 'api.md' - FAQ: 'faq.md' diff --git a/src/haliax/__init__.py b/src/haliax/__init__.py index 3ca0ed6..6645724 100644 --- a/src/haliax/__init__.py +++ b/src/haliax/__init__.py @@ -12,6 +12,7 @@ except ImportError: import haliax.debug as debug import haliax.nn as nn +import haliax.quantization as quantization import haliax.random as random import haliax.tree_util as tree_util import haliax.util as util diff --git a/src/haliax/_src/dot.py b/src/haliax/_src/dot.py index d17de78..48a0061 100644 --- a/src/haliax/_src/dot.py +++ b/src/haliax/_src/dot.py @@ -17,6 +17,7 @@ from haliax.axis import ( union_axes, ) from haliax.core import NamedArray +from haliax.jax_utils import _jittable_dg_einsum from haliax.types import DTypeLike, PrecisionLike from haliax.util import ensure_tuple @@ -29,6 +30,7 @@ def dot( precision: PrecisionLike = None, preferred_element_type: Optional[DTypeLike] = None, out_axes: Optional[PartialAxisSpec] = ..., + dot_general=jax.lax.dot_general, ) -> NamedArray: ... @@ -40,6 +42,7 @@ def dot( precision: PrecisionLike = None, preferred_element_type: Optional[DTypeLike] = None, out_axes: Optional[PartialAxisSpec] = ..., + dot_general=jax.lax.dot_general, ) -> NamedArray: ... @@ -49,6 +52,7 @@ def dot( precision: PrecisionLike = None, preferred_element_type: Optional[DTypeLike] = None, out_axes: Optional[PartialAxisSpec] = None, + dot_general=jax.lax.dot_general, **kwargs, ) -> NamedArray: """Returns the tensor product of two NamedArrays. The axes `axis` are contracted over, @@ -98,6 +102,9 @@ def dot( _ensure_no_mismatched_axes(*arrays) + # to call dot_general we need two things: + # list of contractions and list of arrays + all_axes: Tuple[Axis, ...] = ft.reduce(union_axes, (a.axes for a in arrays), ()) # type: ignore output_axes: Tuple[Axis, ...] if axis is None: @@ -137,11 +144,12 @@ def dot( jax_str = f"contract {', '.join(axis_name(ax) for ax in axis)} -> {', '.join(a.name for a in output_axes)}" with jax.named_scope(jax_str): - output = jnp.einsum( + output = _jittable_dg_einsum( ", ".join(array_specs) + "-> " + output_spec, *[a.array for a in arrays], precision=precision, preferred_element_type=preferred_element_type, + _dot_general=dot_general, ) out = NamedArray(output, output_axes) diff --git a/src/haliax/_src/einsum.py b/src/haliax/_src/einsum.py index a2e082f..4889d10 100644 --- a/src/haliax/_src/einsum.py +++ b/src/haliax/_src/einsum.py @@ -2,12 +2,14 @@ import functools from types import EllipsisType from typing import Optional, Sequence, Tuple, Union +import jax.lax import jax.numpy as jnp import haliax from ..axis import AxisSelector, axis_name, eliminate_axes, rearrange_for_partial_order, union_axes from ..core import NamedArray +from ..jax_utils import _jittable_dg_einsum from ..types import DTypeLike, PrecisionLike from ..util import ensure_tuple from .parsing import AliasTable, parse_einsum, raise_parse_error @@ -18,6 +20,7 @@ def einsum( *arrays: NamedArray, precision: PrecisionLike = None, preferred_element_type: Optional[DTypeLike] = None, + _dot_general=jax.lax.dot_general, ) -> NamedArray: """Compute the tensor contraction of the input arrays according to Haliax's named variant of the Einstein summation convention. @@ -68,11 +71,16 @@ def einsum( spec, out_axes = _positional_einsum_spec(equation, arrays, lhses, rhs) - out_raw = jnp.einsum( - spec, *[a.array for a in arrays], precision=precision, preferred_element_type=preferred_element_type + out_raw = _jittable_dg_einsum( + spec, + *[a.array for a in arrays], + precision=precision, + preferred_element_type=preferred_element_type, + _dot_general=_dot_general, ) - return haliax.named(out_raw, out_axes) + out = haliax.named(out_raw, out_axes) + return haliax.auto_sharded(out) def _unordered_einsum(arrays, equation, lhses, rhs): diff --git a/src/haliax/_src/fp8.py b/src/haliax/_src/fp8.py new file mode 100644 index 0000000..d0e7ce0 --- /dev/null +++ b/src/haliax/_src/fp8.py @@ -0,0 +1,139 @@ +import warnings +from functools import partial + +from jax import custom_jvp, custom_vjp, lax +from jax import numpy as jnp + + +# All of this is copy paste from flax/linen/fp8_ops.py +# (Until we get to the module) + +# Copyright 2024 The Flax Authors. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + + +def quantize_dequantize(x, q_dtype, scale, compute_dtype): + qx = quantize(x, q_dtype, scale, compute_dtype) + return dequantize(qx, x.dtype, scale) + + +def get_fp8_max(fp8_dtype, out_dtype): + assert fp8_dtype in (jnp.float8_e4m3fn, jnp.float8_e5m2) + return jnp.finfo(fp8_dtype).max.astype(out_dtype) + + +def quantize(x, q_dtype, scale, compute_dtype): + # Explicitly cast the max values to the compute dtype to avoid unnecessary + # casting to FP32 during the subsequent math operations." + dtype_max = get_fp8_max(q_dtype, compute_dtype) + scaled_x = x / jnp.broadcast_to(scale.astype(compute_dtype), x.shape) + clipped_x = jnp.clip(scaled_x, -dtype_max, dtype_max) + return clipped_x.astype(q_dtype) + + +def dequantize(x, dq_dtype, scale): + return x.astype(dq_dtype) * jnp.broadcast_to(scale.astype(dq_dtype), x.shape) + + +def compute_scale(amax, scale, fp8_max, margin=0): + # The algorithm for computing the new scale is sourced from + # https://docs.nvidia.com/deeplearning/transformer-engine/user-guide/api/jax.html#transformer_engine.jax.update_fp8_metas + # wherein the `original_scale` corresponds to the reciprocal of the `scale` + # passed in this function. + scale = 1.0 / scale + + sf = (fp8_max / amax) / (2**margin) + sf = jnp.where(amax > 0.0, sf, scale) + sf = jnp.where(jnp.isfinite(amax), sf, scale) + + return 1.0 / sf + + +def compute_amax_history(x, amax_history): + amax_update = jnp.max(jnp.abs(x)).astype(amax_history.dtype) + new_history = jnp.roll(amax_history, shift=-1, axis=0).at[0].set(amax_update) + return new_history + + +def qdq_and_return(x, q_dtype, scale, amax_history, compute_dtype): + dtype_max = get_fp8_max(q_dtype, jnp.float32) + amax_from_history = jnp.max(amax_history, axis=0) + new_scale = compute_scale(amax_from_history, scale, dtype_max) + + qx = quantize_dequantize(x, q_dtype, new_scale, compute_dtype) + + new_history = compute_amax_history(x, amax_history) + + return qx, new_scale, new_history + + +@partial(custom_vjp, nondiff_argnums=(0,)) +def in_qdq(compute_dtype, inp, scale, amax_history): + qin, _, _ = qdq_and_return(inp, jnp.float8_e4m3fn, scale, amax_history, compute_dtype) + return qin + + +def in_qdq_fwd(compute_dtype, inp, scale, amax_history): + qin, new_scale, new_history = qdq_and_return(inp, jnp.float8_e4m3fn, scale, amax_history, compute_dtype) + return qin, (new_scale, new_history) + + +def in_qdq_bwd(compute_dtype, res, g): + new_scale, new_history = res + q_g = g + return q_g, new_scale, new_history + + +in_qdq.defvjp(in_qdq_fwd, in_qdq_bwd) + + +@partial(custom_vjp, nondiff_argnums=(0,)) +def out_qdq(compute_dtype, out, scale, amax_history): + return out + + +def out_qdq_fwd(compute_dtype, out, scale, amax_history): + return out, (scale, amax_history) + + +def out_qdq_bwd(compute_dtype, res, g): + scale, amax_history = res + q_g, new_scale, new_history = qdq_and_return(g, jnp.float8_e5m2, scale, amax_history, compute_dtype) + return q_g, new_scale, new_history + + +out_qdq.defvjp(out_qdq_fwd, out_qdq_bwd) + + +@partial(custom_jvp, nondiff_argnums=(2, 3, 4)) +def dot_general_with_precision(lhs, rhs, dimension_numbers, precision=None, preferred_element_type=None): + if precision is not None or preferred_element_type is not None: + warnings.warn( + "The function dot_general_with_precision will set the " + "precision/preferred_element_type and disregard any provided " + "values." + ) + return lax.dot_general(lhs, rhs, dimension_numbers, precision=lax.Precision.DEFAULT) + + +@dot_general_with_precision.defjvp +def dot_general_with_precision_jvp(dimension_numbers, precision, preferred_element_type, primals, tangents): + lhs, rhs = primals + lhs_dot, rhs_dot = tangents + + out = lax.dot_general(lhs, rhs, dimension_numbers, precision=lax.Precision.DEFAULT) + grad_out = lax.dot_general(lhs_dot, rhs, dimension_numbers, precision=lax.Precision.HIGHEST) + lax.dot_general( + lhs, rhs_dot, dimension_numbers, precision=lax.Precision.HIGHEST + ) + return out, grad_out diff --git a/src/haliax/core.py b/src/haliax/core.py index 9618394..c08bba6 100644 --- a/src/haliax/core.py +++ b/src/haliax/core.py @@ -415,11 +415,15 @@ class NamedArray: # Deprecated overload @typing.overload - def dot(self, axis: Optional[AxisSelection], *b, precision: PrecisionLike = None) -> "NamedArray": + def dot( + self, axis: Optional[AxisSelection], *b, precision: PrecisionLike = None, dot_general=jax.lax.dot_general + ) -> "NamedArray": ... @typing.overload - def dot(self, *args, axis: Optional[AxisSelection], precision: PrecisionLike = None) -> "NamedArray": + def dot( + self, *args, axis: Optional[AxisSelection], precision: PrecisionLike = None, dot_general=jax.lax.dot_general + ) -> "NamedArray": ... def dot(self, *args, **kwargs) -> "NamedArray": diff --git a/src/haliax/jax_utils.py b/src/haliax/jax_utils.py index 77acd8a..c1876ab 100644 --- a/src/haliax/jax_utils.py +++ b/src/haliax/jax_utils.py @@ -1,15 +1,19 @@ import functools as ft import typing -from typing import Any, Callable, List, Optional, Sequence, Union +from typing import Any, Callable, Optional, Sequence, Union import equinox as eqx import jax import numpy as np +from jax import Array from jax import numpy as jnp from jax import random as jrandom +from jax._src.numpy import lax_numpy +from jax._src.typing import DTypeLike from jaxtyping import PRNGKeyArray import haliax +from haliax.types import PrecisionLike F = typing.TypeVar("F", bound=Callable[..., Any]) @@ -153,3 +157,41 @@ def is_scalarish(x): def is_on_mac_metal(): return jax.devices()[0].platform.lower() == "metal" + + +def _jittable_dg_einsum( + subscripts, + /, + *operands, + out: None = None, + optimize: str = "optimal", + precision: PrecisionLike = None, + preferred_element_type: DTypeLike | None = None, + _dot_general: Callable[..., Array] = jax.lax.dot_general, +) -> Array: + operands = (subscripts, *operands) + if out is not None: + raise NotImplementedError("The 'out' argument to jnp.einsum is not supported.") + spec = operands[0] if isinstance(operands[0], str) else None + optimize = "optimal" if optimize is True else optimize + + import opt_einsum + + # Allow handling of shape polymorphism + non_constant_dim_types = { + type(d) for op in operands if not isinstance(op, str) for d in np.shape(op) if not jax.core.is_constant_dim(d) + } + if not non_constant_dim_types: + contract_path = opt_einsum.contract_path + else: + ty = next(iter(non_constant_dim_types)) + contract_path = lax_numpy._poly_einsum_handlers.get(ty, lax_numpy._default_poly_einsum_handler) + # using einsum_call=True here is an internal api for opt_einsum... sorry + operands, contractions = contract_path(*operands, einsum_call=True, use_blas=True, optimize=optimize) + + contractions = tuple((a, frozenset(b), c) for a, b, c, *_ in contractions) + + einsum = eqx.filter_jit(lax_numpy._einsum, inline=True) + if spec is not None: + einsum = jax.named_call(einsum, name=spec) + return einsum(operands, contractions, precision, preferred_element_type, _dot_general) # type: ignore[operator] diff --git a/src/haliax/nn/linear.py b/src/haliax/nn/linear.py index 0c3e2d5..866a1fe 100644 --- a/src/haliax/nn/linear.py +++ b/src/haliax/nn/linear.py @@ -1,6 +1,7 @@ -from typing import Optional +from typing import Callable, Optional import equinox as eqx +import jax.lax from jaxtyping import PRNGKeyArray import haliax as hax @@ -8,6 +9,7 @@ import haliax as hax from ..axis import AxisSpec from ..core import NamedArray from ..jax_utils import named_call +from ..quantization import DotGeneralOp class Linear(eqx.Module): @@ -19,22 +21,26 @@ class Linear(eqx.Module): In: AxisSpec = eqx.static_field() Out: AxisSpec = eqx.static_field() + dot_general: DotGeneralOp = jax.lax.dot_general @staticmethod - def init(In: AxisSpec, Out: AxisSpec, *, key, use_bias=True, out_first: bool = False) -> "Linear": + def init( + In: AxisSpec, Out: AxisSpec, *, key, use_bias=True, out_first: bool = False, dot_general=jax.lax.dot_general + ) -> "Linear": """ - :param In: Input axes - :param Out: Output axes - :param key: rng key for initialization - :param use_bias: whether to include bias term - :param out_first: whether to put output axes first in the weight matrix. out_first is how PyTorch does it. - :return: + Args: + In: AxisSpec: The input axis spec + Out: AxisSpec: The output axis spec + key: PRNGKeyArray: The PRNG key to use for initialization + use_bias: bool: Whether to use a bias term + out_first: bool: Whether to put output axes first in the weight matrix. out_first is how PyTorch does it. + dot_general: Callable: The dot_general function to use. Defaults to jax.lax.dot_general. For fp8 or int8 """ joint_spec = hax.concat_axis_specs(Out, In) if out_first else hax.concat_axis_specs(In, Out) weight = hax.random.normal(key, joint_spec) * 0.02 bias = hax.zeros(Out) if use_bias else None - return Linear(weight, bias, In, Out) + return Linear(weight, bias, In, Out, dot_general=dot_general) @named_call def __call__(self, inputs, *, key: Optional[PRNGKeyArray] = None): @@ -44,7 +50,7 @@ class Linear(eqx.Module): key: Not used, but there for compat with other modules """ del key - q = inputs.dot(self.weight, axis=self.In) + q = inputs.dot(self.weight, axis=self.In, dot_general=self.dot_general) q = hax.auto_sharded(q) if self.bias is not None: diff --git a/src/haliax/nn/mlp.py b/src/haliax/nn/mlp.py index 06c7504..a79bc7d 100644 --- a/src/haliax/nn/mlp.py +++ b/src/haliax/nn/mlp.py @@ -7,6 +7,7 @@ from jaxtyping import PRNGKeyArray from ..axis import Axis, AxisSpec from ..core import NamedArray from ..jax_utils import maybe_rng_split +from ..quantization import DotGeneralOp from .activations import relu from .linear import Linear @@ -46,6 +47,7 @@ class MLP(eqx.Module): use_bias: bool = True, use_final_bias: bool = True, key: PRNGKeyArray, + dot_general: DotGeneralOp = jax.lax.dot_general, ): Width = _get_width(width) Width2 = Width.alias(Width.name + "2") @@ -56,18 +58,18 @@ class MLP(eqx.Module): if depth == 0: # special case: no hidden layers - layers.append(Linear.init(Input, Output, use_bias=use_final_bias, key=keys[0])) + layers.append(Linear.init(Input, Output, use_bias=use_final_bias, key=keys[0], dot_general=dot_general)) else: # first hidden layer - layers.append(Linear.init(Input, Width, use_bias=use_bias, key=keys[0])) + layers.append(Linear.init(Input, Width, use_bias=use_bias, key=keys[0], dot_general=dot_general)) # middle hidden layers cur = Width next = Width2 for i in range(1, depth): - layers.append(Linear.init(cur, next, use_bias=use_bias, key=keys[i])) + layers.append(Linear.init(cur, next, use_bias=use_bias, key=keys[i], dot_general=dot_general)) cur, next = next, cur # final hidden layer - layers.append(Linear.init(cur, Output, use_bias=use_final_bias, key=keys[-1])) + layers.append(Linear.init(cur, Output, use_bias=use_final_bias, key=keys[-1], dot_general=dot_general)) return MLP( layers=tuple(layers), diff --git a/src/haliax/nn/scan.py b/src/haliax/nn/scan.py index e651aff..2baf888 100644 --- a/src/haliax/nn/scan.py +++ b/src/haliax/nn/scan.py @@ -56,7 +56,7 @@ class BlockSeq(eqx.Module, Generic[M]): where you have multiple instances of the same transformer block and the input is applied in a fold/for loop in sequence. - It's similar in spirit to an [equinox.nn.Sequential]. Unlike [equinox.nn.Stacked][], BlockSeq does not need to be + It's similar in spirit to an [equinox.nn.Sequential][]. Unlike [equinox.nn.Sequential][], BlockSeq does not need to be homogeneous (though the init method assumes that it is). """ diff --git a/src/haliax/quantization.py b/src/haliax/quantization.py new file mode 100644 index 0000000..822a986 --- /dev/null +++ b/src/haliax/quantization.py @@ -0,0 +1,244 @@ +# Support for FP8 +# Much of this is lifted from FLAX +# https://github.com/google/flax/blob/main/flax/linen/fp8_ops.py +import dataclasses +import functools +import warnings +from dataclasses import dataclass +from typing import Optional, Protocol, TypeVar + +import equinox as eqx +import jax +from jax import numpy as jnp +from jax._src.tree_util import BuiltInKeyEntry +from jax.tree_util import DictKey, FlattenedIndexKey, GetAttrKey, SequenceKey +from jax.typing import DTypeLike + +import haliax.nn as hnn +from haliax.types import PrecisionLike + +from ._src.fp8 import dot_general_with_precision, in_qdq, out_qdq +from .axis import Axis +from .hof import vmap + + +T = TypeVar("T") + + +class OverwriteWithGradient(eqx.Module): + """ + Sometimes there is state that must be computed in the backward pass which we want to + persist for subsequent passes. Typically, we see this with quantization, particularly + FP8. This module is a marker that indicates to [haliax.quantization.apply_updates][] that the + gradient should be used to overwrite the state rather than added to it. + + Typically this is used in conjunction with [haliax.quantization.partition_for_grad_overwrite][] + and the types are kinds of DotGeneralOp. + """ + + pass + + +def partition_for_grad_overwrite(grad: T) -> tuple[T, T]: + """ + This function is used to partition the state of a module into two parts: one that will be + overwritten by the gradient and one that will be updated by the gradient. This is used by + [equinox.apply_updates][] to determine which state should be updated and which should + be overwritten. + The usual pattern is something like: + + ```python + grads = jax.grad(loss_fn)(model) + overwrites, grads = partition_for_grad_overwrite(grads) + updates = optimizer.update(grads, params=model) + model = hax.quant.apply_updates(model, updates, overwrites) + ``` + + """ + + def is_overwrite_with_gradient(v): + return isinstance(v, OverwriteWithGradient) + + x, y = eqx.partition(grad, is_overwrite_with_gradient, is_leaf=is_overwrite_with_gradient) + return x, y + + +def apply_updates(tree, updates, overwrites): + """ + A `jax.tree_util.tree_map`-broadcasted version of + ```python + if overwrite is not None: + return overwrite + if update is None: + return model + else: + return model + update + """ + + def _apply_update(tree, update, overwrite): + if overwrite is not None: + return overwrite + + return eqx.apply_updates(tree, update) + + def is_leaf(x): + return x is None or isinstance(x, OverwriteWithGradient) + + return jax.tree_util.tree_map(_apply_update, tree, updates, overwrites, is_leaf=is_leaf) + + +class DotGeneralOp(Protocol): + """ + This protocol is used to define the signature of the `dot_general` function that is + passed to the `Linear` module. This is used to allow for custom dot_general functions + for quantized types. + """ + + def __call__( + self, + lhs, + rhs, + dimension_numbers, + precision: PrecisionLike = None, + preferred_element_type: DTypeLike | None = None, + ) -> jnp.ndarray: + ... + + +class Fp8DotGeneralOp(OverwriteWithGradient): + input_scale: jnp.ndarray + output_grad_scale: jnp.ndarray + kernel_scale: jnp.ndarray + input_amax_history: jnp.ndarray + output_grad_amax_history: jnp.ndarray + kernel_amax_history: jnp.ndarray + compute_dtype: Optional[DTypeLike] = eqx.field(static=True) + + @classmethod + def init(cls, amax_history_length: int = 1024, compute_dtype: DTypeLike = None): + return cls( + input_scale=jnp.ones(1, dtype=jnp.float32), + output_grad_scale=jnp.ones(1, dtype=jnp.float32), + kernel_scale=jnp.ones(1, dtype=jnp.float32), + input_amax_history=jnp.zeros(amax_history_length, dtype=jnp.float32), + output_grad_amax_history=jnp.zeros(amax_history_length, dtype=jnp.float32), + kernel_amax_history=jnp.zeros(amax_history_length, dtype=jnp.float32), + compute_dtype=compute_dtype, + ) + + # copied from flax + def __call__( + self, + lhs, + rhs, + dimension_numbers, + precision: PrecisionLike = None, + preferred_element_type: DTypeLike | None = None, + ): + # Use the `k.dtype` since it aligns with the `dtype` of its layers, + # namely, the computation data type. + if self.compute_dtype is None: + comp_dtype = rhs.dtype + else: + comp_dtype = self.compute_dtype + lhs = jnp.asarray(lhs, comp_dtype) + + x_qdq = in_qdq(comp_dtype, lhs, self.input_scale, self.input_amax_history) + k_qdq = in_qdq(comp_dtype, rhs, self.kernel_scale, self.kernel_amax_history) + y_qdq = dot_general_with_precision(x_qdq, k_qdq, dimension_numbers, precision, preferred_element_type) + y = out_qdq(comp_dtype, y_qdq, self.output_grad_scale, self.output_grad_amax_history) + + return y + + +@dataclass(frozen=True) +class Fp8Config: + amax_history_length: int = 1024 + compute_dtype: DTypeLike = None + targets: Optional[list[str] | str] = dataclasses.field(default=None) + """ + If provided, only modules with names in this list will be quantized. If a single string, will be treated as a regex + """ + + +def fp8_linear_layers(tree: T, config: Fp8Config = Fp8Config()) -> T: + """ + Converts a module tree to use FP8 quantization. + Linear modules that have a name that matches the targets (if provided) will be converted to use FP8. + (If targets is None, all linear modules will be converted.) + + This essentially goes through and adds FP8DotGeneralOp to the Linear modules. + """ + + def _is_special_module(module): + # TODO: add conv? + return isinstance(module, hnn.Linear) or isinstance(module, hnn.Stacked) + + def _batchify_ctor(ctor, batch_dims): + # this is gross but it basically just vmaps the ctor over each batch dimension + return functools.reduce(lambda ctor, batch_axis: vmap(ctor, batch_axis), reversed(batch_dims), ctor) + + # TODO: test scanlayers for dg + def fp8_quantize_module(path_prefix, batch_dims: tuple[Axis, ...], path, module: T) -> T: + path = path_prefix + path + if isinstance(module, hnn.Stacked): + new_inner = jax.tree_util.tree_map_with_path( + functools.partial(fp8_quantize_module, path_prefix + (GetAttrKey("stacked"),), batch_dims + (module.Block,)), # type: ignore + module.stacked, + is_leaf=_is_special_module, + ) + return dataclasses.replace(module, stacked=new_inner) # type: ignore + elif isinstance(module, hnn.Linear): + if _matches_target_fp8(path, config): + vmapped_dg = _batchify_ctor(Fp8DotGeneralOp.init, batch_dims)( + config.amax_history_length, config.compute_dtype + ) + module = dataclasses.replace(module, dot_general=vmapped_dg) # type: ignore + return module + else: + return module + + return jax.tree_util.tree_map_with_path( + lambda p, m: fp8_quantize_module((), (), p, m), tree, is_leaf=_is_special_module + ) + + +def _matches_target_fp8(key_path, config: Fp8Config) -> bool: + if not key_path: + key = "" + else: + key = _key_path_to_str(key_path[-1:]) + + if config.targets is None: + return True + if isinstance(config.targets, list): + return key in config.targets + + import re + + key_path_str = _key_path_to_str(key_path) + return re.match(config.targets, key_path_str) is not None + + +def _key_path_to_str(key_path: tuple[BuiltInKeyEntry, ...]) -> str: + out = "" + for k in key_path: + match k: + case SequenceKey(i): # type: ignore + out = _join_key(out, str(i)) + case GetAttrKey(name): # type: ignore + out = _join_key(out, name) + case DictKey(key): # type: ignore + out = _join_key(out, key) + case FlattenedIndexKey(i): # type: ignore + out = _join_key(out, str(i)) + case _: + warnings.warn(f"Unsupported key type {k}") + out = _join_key(out, str(k)) + return out + + +def _join_key(prefix: str, key: str) -> str: + if prefix: + return f"{prefix}.{key}" + return key diff --git a/tests/test_fp8.py b/tests/test_fp8.py new file mode 100644 index 0000000..1721009 --- /dev/null +++ b/tests/test_fp8.py @@ -0,0 +1,207 @@ +import equinox as eqx +import jax.numpy as jnp +import jax.random as jrandom +import jax.tree_util +import numpy as np + +import haliax as hax +from haliax._src.fp8 import compute_scale +from haliax.nn import Linear +from haliax.quantization import ( + Fp8Config, + Fp8DotGeneralOp, + apply_updates, + fp8_linear_layers, + partition_for_grad_overwrite, +) + + +def test_fp8_is_reasonable(): + In = hax.Axis("In", 8) + Out = hax.Axis("Out", 8) + linear = Linear.init(In, Out, key=jrandom.PRNGKey(0)) + + fp8_linear = Linear.init(In, Out, key=jrandom.PRNGKey(0), dot_general=hax.quantization.Fp8DotGeneralOp.init()) + + input = hax.random.normal(jrandom.PRNGKey(0), In) * 10 + output = linear(input) + fp8_output = fp8_linear(input) + + assert output.shape == fp8_output.shape + assert output.dtype == fp8_output.dtype + + assert jnp.allclose(output.array, fp8_output.array, atol=1e-1, rtol=1e-1) + + +# https://github.com/google/flax/blob/6f2b08e024c2fd2f8cec42a6c82408cb35412319/tests/linen/linen_test.py#L1222 +def test_fp_loop(): + key, init_key, random_key = jrandom.split(jrandom.PRNGKey(seed=123), 3) + Batch = hax.Axis("Batch", 16) + In = hax.Axis("In", 16) + Out = hax.Axis("Out", 32) + linear = Linear.init(In, Out, key=init_key, dot_general=Fp8DotGeneralOp.init()) + + def _roll_and_update(amax_h, update): + return jnp.roll(amax_h, shift=-1, axis=0).at[0].set(update) + + lr = 1e-3 + + def apply_gradients(model, grads): + overwrites, grads = partition_for_grad_overwrite(grads) + updates = jax.tree_util.tree_map(lambda g: -lr * g, grads) + model = apply_updates(model, updates, overwrites) + return model + + def _train_step(model, x, dy): + def loss_fn(lin): + y = lin(x) + loss = y * dy.astype(y.dtype) + return hax.sum(loss).scalar() + + grad_fn = eqx.filter_grad(loss_fn) + grads = grad_fn(model) + return apply_gradients(model, grads) + + train_fn = eqx.filter_jit(_train_step) + + scale_x, amax_history_x = jnp.ones(()), jnp.zeros((1024,)) + scale_k, amax_history_k = jnp.ones(()), jnp.zeros((1024,)) + scale_g, amax_history_g = jnp.ones(()), jnp.zeros((1024,)) + e4m3_max = jnp.finfo(jnp.float8_e4m3fn).max.astype(jnp.float32) + e5m2_max = jnp.finfo(jnp.float8_e5m2).max.astype(jnp.float32) + + for _ in range(5): + key, random_key = jrandom.split(key, 2) + # x = jrandom.normal(random_key, (16, 16), dtype=jnp.float32) + # g = jrandom.normal(random_key, (16, 32), dtype=jnp.float32) + x = hax.random.normal( + random_key, + ( + Batch, + In, + ), + ) + g = hax.random.normal( + random_key, + ( + Batch, + Out, + ), + ) + + # Manually compute the expected amax history and scaling factors. + amax_from_history_x = jnp.max(amax_history_x, axis=0) + amax_from_history_k = jnp.max(amax_history_k, axis=0) + amax_from_history_g = jnp.max(amax_history_g, axis=0) + scale_x = compute_scale(amax_from_history_x, scale_x, e4m3_max) + scale_k = compute_scale(amax_from_history_k, scale_k, e4m3_max) + scale_g = compute_scale(amax_from_history_g, scale_g, e5m2_max) + amax_history_x = _roll_and_update(amax_history_x, jnp.max(jnp.abs(x.array))) + amax_history_k = _roll_and_update(amax_history_k, jnp.max(jnp.abs(linear.weight.array))) + amax_history_g = _roll_and_update(amax_history_g, jnp.max(jnp.abs(g.array))) + + linear = train_fn(linear, x, g) + + rtol, atol = 0.001, 0.001 + np.testing.assert_allclose( + linear.dot_general.input_amax_history, # type: ignore + amax_history_x, + rtol=rtol, + atol=atol, + ) + np.testing.assert_allclose( + linear.dot_general.kernel_amax_history, # type: ignore + amax_history_k, + rtol=rtol, + atol=atol, + ) + np.testing.assert_allclose( + linear.dot_general.output_grad_amax_history, # type: ignore + amax_history_g, + rtol=rtol, + atol=atol, + ) + + np.testing.assert_allclose(linear.dot_general.input_scale, scale_x, rtol=rtol, atol=atol) # type: ignore + np.testing.assert_allclose(linear.dot_general.kernel_scale, scale_k, rtol=rtol, atol=atol) # type: ignore + np.testing.assert_allclose(linear.dot_general.output_grad_scale, scale_g, rtol=rtol, atol=atol) # type: ignore + + +def test_layer_splicing(): + key, init_key, random_key = jrandom.split(jrandom.PRNGKey(seed=123), 3) + Input = hax.Axis("Input", 16) + Hidden = hax.Axis("Hidden", 16) + Output = hax.Axis("Output", 32) + mlp = hax.nn.MLP.init(Input, Output, Hidden, 3, key=init_key) + + mlp_q = fp8_linear_layers(mlp, Fp8Config()) + for layer in mlp_q.layers: + assert isinstance(layer.dot_general, Fp8DotGeneralOp) + + input = hax.random.normal(jrandom.PRNGKey(0), Input) * 10 # 10 so we don't underflow + output = mlp(input) + output_q = mlp_q(input) + assert jnp.allclose(output.array, output_q.array, atol=1e-3, rtol=1e-3) + assert not jnp.allclose(output_q.array, 0) # don't want them to all underflow + + mlp_q = fp8_linear_layers(mlp, Fp8Config(targets="layers.0")) + for i, layer in enumerate(mlp_q.layers): + if i == 0: + assert isinstance(layer.dot_general, Fp8DotGeneralOp) + else: + assert not isinstance(layer.dot_general, Fp8DotGeneralOp) + + mlp_q = fp8_linear_layers(mlp, Fp8Config(targets=["0", "1"])) + for i, layer in enumerate(mlp_q.layers): + if i < 2: + assert isinstance(layer.dot_general, Fp8DotGeneralOp) + else: + assert not isinstance(layer.dot_general, Fp8DotGeneralOp) + + +def test_fp8ize_stacking(): + class Block(eqx.Module): + up_proj: hax.nn.Linear + down_proj: hax.nn.Linear + + @staticmethod + def init(In, Out, key): + up_proj = hax.nn.Linear.init(In, Out, key=key) + down_proj = hax.nn.Linear.init(Out, In, key=key) + return Block(up_proj, down_proj) + + def __call__(self, x): + return self.down_proj(self.up_proj(x)) + + Layer = hax.Axis("Layer", 3) + + class Tformer(eqx.Module): + blocks: hax.nn.Stacked[Block] + + @staticmethod + def init(In, Out, key): + blocks = hax.nn.Stacked.init(Layer, Block)(In, Out, key=jax.random.split(key, Layer.size)) + return Tformer(blocks) + + def __call__(self, x): + return self.blocks.fold(x) + + In = hax.Axis("In", 16) + Out = hax.Axis("Out", 32) + tformer = Tformer.init(In, Out, key=jrandom.PRNGKey(0)) + tformer_q = fp8_linear_layers(tformer, Fp8Config()) + + # want to be sure this vmaps the dot_general to the right places + dg = tformer_q.blocks.stacked.up_proj.dot_general + assert isinstance(dg, Fp8DotGeneralOp) + assert dg.input_scale.shape == (Layer.size, 1) + assert dg.input_amax_history.shape == (Layer.size, 1024) + dg = tformer_q.blocks.stacked.down_proj.dot_general + assert isinstance(dg, Fp8DotGeneralOp) + + # just stack the up_proj + tformer_q = fp8_linear_layers(tformer, Fp8Config(targets=["up_proj"])) + dg = tformer_q.blocks.stacked.up_proj.dot_general + assert isinstance(dg, Fp8DotGeneralOp) + dg = tformer_q.blocks.stacked.down_proj.dot_general + assert not isinstance(dg, Fp8DotGeneralOp) commit 87bb63197c32f42faa7f2e74edf262a6ea1782de Date: 2024-03-15T23:57:31-07:00 better named_call for haliax diff --git a/src/haliax/jax_utils.py b/src/haliax/jax_utils.py index c1876ab..c24e1d0 100644 --- a/src/haliax/jax_utils.py +++ b/src/haliax/jax_utils.py @@ -131,7 +131,10 @@ def named_call(f=_UNSPECIFIED, name: Optional[str] = None): else: name = f.__qualname__ - return jax.named_scope(name)(f) + # because of https://github.com/google/jax/issues/7029 it seems like we need to use jax.named_scope + # AND jax.profiler.annotate_function + + return jax.profiler.annotate_function(jax.named_scope(name)(f), name=name) def is_in_jit(): commit 2a696a0c971901ff93afdaa965959d8e3b982ba9 Date: 2024-03-16T00:49:44-07:00 Revert "better named_call for haliax" This reverts commit 87bb63197c32f42faa7f2e74edf262a6ea1782de. diff --git a/src/haliax/jax_utils.py b/src/haliax/jax_utils.py index c24e1d0..c1876ab 100644 --- a/src/haliax/jax_utils.py +++ b/src/haliax/jax_utils.py @@ -131,10 +131,7 @@ def named_call(f=_UNSPECIFIED, name: Optional[str] = None): else: name = f.__qualname__ - # because of https://github.com/google/jax/issues/7029 it seems like we need to use jax.named_scope - # AND jax.profiler.annotate_function - - return jax.profiler.annotate_function(jax.named_scope(name)(f), name=name) + return jax.named_scope(name)(f) def is_in_jit(): commit b6ecf159f4912ba89e714c552ee1a476e2248e6e Date: 2024-03-18T00:13:55-07:00 make it less likely we end up with non arrays diff --git a/docs/fp8.md b/docs/fp8.md index 9318bba..fac3dd9 100644 --- a/docs/fp8.md +++ b/docs/fp8.md @@ -149,6 +149,7 @@ gradient and stores it in the gradient. ## Modules +::: haliax.quantization.DefaultDotGeneralOp ::: haliax.quantization.Fp8DotGeneralOp ## Configuration diff --git a/src/haliax/_src/fp8.py b/src/haliax/_src/fp8.py index d0e7ce0..b89e4ab 100644 --- a/src/haliax/_src/fp8.py +++ b/src/haliax/_src/fp8.py @@ -119,11 +119,13 @@ out_qdq.defvjp(out_qdq_fwd, out_qdq_bwd) @partial(custom_jvp, nondiff_argnums=(2, 3, 4)) def dot_general_with_precision(lhs, rhs, dimension_numbers, precision=None, preferred_element_type=None): if precision is not None or preferred_element_type is not None: - warnings.warn( - "The function dot_general_with_precision will set the " - "precision/preferred_element_type and disregard any provided " - "values." - ) + # einsum sets preferred_element_type and so this is just noisy + # warnings.warn( + # "The function dot_general_with_precision will set the " + # "precision/preferred_element_type and disregard any provided " + # "values." + # ) + pass return lax.dot_general(lhs, rhs, dimension_numbers, precision=lax.Precision.DEFAULT) diff --git a/src/haliax/nn/linear.py b/src/haliax/nn/linear.py index 866a1fe..fccbfb7 100644 --- a/src/haliax/nn/linear.py +++ b/src/haliax/nn/linear.py @@ -21,11 +21,11 @@ class Linear(eqx.Module): In: AxisSpec = eqx.static_field() Out: AxisSpec = eqx.static_field() - dot_general: DotGeneralOp = jax.lax.dot_general + dot_general: DotGeneralOp = eqx.field(default_factory=DotGeneralOp.default) @staticmethod def init( - In: AxisSpec, Out: AxisSpec, *, key, use_bias=True, out_first: bool = False, dot_general=jax.lax.dot_general + In: AxisSpec, Out: AxisSpec, *, key, use_bias=True, out_first: bool = False, dot_general=None ) -> "Linear": """ @@ -40,6 +40,10 @@ class Linear(eqx.Module): joint_spec = hax.concat_axis_specs(Out, In) if out_first else hax.concat_axis_specs(In, Out) weight = hax.random.normal(key, joint_spec) * 0.02 bias = hax.zeros(Out) if use_bias else None + + if dot_general is None: + dot_general = DotGeneralOp.default() + return Linear(weight, bias, In, Out, dot_general=dot_general) @named_call diff --git a/src/haliax/nn/mlp.py b/src/haliax/nn/mlp.py index a79bc7d..9ce7b40 100644 --- a/src/haliax/nn/mlp.py +++ b/src/haliax/nn/mlp.py @@ -1,4 +1,4 @@ -from typing import Callable, Sequence +from typing import Callable, Optional, Sequence import equinox as eqx import jax @@ -47,7 +47,7 @@ class MLP(eqx.Module): use_bias: bool = True, use_final_bias: bool = True, key: PRNGKeyArray, - dot_general: DotGeneralOp = jax.lax.dot_general, + dot_general: Optional[DotGeneralOp] = None, ): Width = _get_width(width) Width2 = Width.alias(Width.name + "2") diff --git a/src/haliax/quantization.py b/src/haliax/quantization.py index 822a986..9a3edcc 100644 --- a/src/haliax/quantization.py +++ b/src/haliax/quantization.py @@ -104,6 +104,39 @@ class DotGeneralOp(Protocol): ) -> jnp.ndarray: ... + @staticmethod + def default(): + return DefaultDotGeneralOp.init() + + +class DefaultDotGeneralOp(eqx.Module): + """ + The default dot_general function that is used by the `Linear` module. This is the + standard JAX `jax.lax.dot_general` function. + + Notes: + We could have used `jax.lax.dot_general` directly, but we use this class so that we don't + unnecessarily have functions as leaves in the module tree. + """ + + def __call__( + self, + lhs, + rhs, + dimension_numbers, + precision: PrecisionLike = None, + preferred_element_type: DTypeLike | None = None, + ) -> jnp.ndarray: + return jax.lax.dot_general(lhs, rhs, dimension_numbers, precision, preferred_element_type) + + # not really necessary, but it's nice to have a singleton + @staticmethod + def init(): + if not hasattr(DefaultDotGeneralOp, "_instance"): + DefaultDotGeneralOp._instance = DefaultDotGeneralOp() + + return DefaultDotGeneralOp._instance + class Fp8DotGeneralOp(OverwriteWithGradient): input_scale: jnp.ndarray diff --git a/tests/test_nn.py b/tests/test_nn.py index 18a9b0c..83e91f3 100644 --- a/tests/test_nn.py +++ b/tests/test_nn.py @@ -1,3 +1,5 @@ +from typing import Callable + import equinox as eqx import jax.nn import jax.random as jrandom @@ -145,3 +147,13 @@ def test_mlp(depth): else: assert hax_mlp.layers[i].In == M assert hax_mlp.layers[i].Out == M.alias("M2") + + +def test_linear_has_no_function_leaves_by_default(): + H = Axis("H", 10) + C = Axis("C", 12) + W = Axis("W", 14) + E = Axis("E", 16) + + hax_linear = hax.nn.Linear.init((H, C, W), E, key=jrandom.PRNGKey(0)) + assert all(not isinstance(v, Callable) for v in jax.tree_util.tree_leaves(hax_linear)) # type: ignore commit 2147a6e256e1bfe9ff6e54e588aacbe6d6ec5bcc Date: 2024-03-26T00:04:14-07:00 Simplify hax.shard (#79) diff --git a/src/haliax/nn/__init__.py b/src/haliax/nn/__init__.py index 745575a..3617e2b 100644 --- a/src/haliax/nn/__init__.py +++ b/src/haliax/nn/__init__.py @@ -58,7 +58,9 @@ def one_hot(x: NamedArray | int, class_axis: Axis, *, dtype=None) -> NamedArray: """ if isinstance(x, NamedArray): array = jnn.one_hot(x.array, num_classes=class_axis.size, dtype=dtype) - return hax.auto_sharded(hax.named(array, x.axes + (class_axis,))) + # Disabling this to prevent a crash in XLA on GPU + # return hax.auto_sharded(hax.named(array, x.axes + (class_axis,))) + return hax.named(array, x.axes + (class_axis,)) else: assert isinstance(x, int) assert class_axis.size > x >= -class_axis.size diff --git a/src/haliax/partitioning.py b/src/haliax/partitioning.py index d7ee32f..922ac92 100644 --- a/src/haliax/partitioning.py +++ b/src/haliax/partitioning.py @@ -101,13 +101,10 @@ def auto_sharded(x: T, mesh: Optional[Mesh] = None) -> T: def shard(x: T, mapping: Optional[ResourceMapping] = None, mesh: Optional[Mesh] = None) -> T: """ Shard a PyTree using the provided axis mapping. NamedArrays in the PyTree are sharded using the axis mapping. - Other arrays are not sharded (unless they're already sharded). + Other arrays (i.e. plain JAX arrays) are left alone. - Inside of a jit context, this method grounds out in calls to `with_sharding_constraint`. Outside of a jit - context, this method grounds out in either device_put or make_array_from_callback, depending on whether the - resulting sharding spans more than one host. - - Outside of jit, this method will warn if there is no resource mapping found. + This is basically a fancy wrapper around `with_sharding_constraint` that uses the axis mapping to determine + the sharding. """ if mapping is None: @@ -116,7 +113,6 @@ def shard(x: T, mapping: Optional[ResourceMapping] = None, mesh: Optional[Mesh] if mapping is None: if not is_in_jit(): warnings.warn("No resource mapping found. Not sharding.", RuntimeWarning) - return x assert not isinstance(mesh, dict) @@ -125,44 +121,24 @@ def shard(x: T, mapping: Optional[ResourceMapping] = None, mesh: Optional[Mesh] mesh = _get_mesh() if mesh.empty: - mesh = None + return x - if mesh is None: + if is_on_mac_metal(): + warnings.warn("Sharding constraints are not supported in jit on metal", RuntimeWarning) return x def _do_device_put(x): if not is_named_array(x): return x - if _is_jit_tracer(x.array): - pspec = pspec_for_axis(x.axes, mapping) - if is_on_mac_metal(): - warnings.warn("Sharding constraints are not supported in jit on metal", RuntimeWarning) - return x - return with_sharding_constraint(x, pspec) - elif not is_jax_array_like(x.array): - # this happens when we filter out params for things like lora + if not is_jax_array_like(x.array): + # this happens when we filter out params for things like lora. + # could use eqx.partition to avoid this, but eh return x - else: - raw_x = x.array - current_sharding = raw_x.sharding - - desired_sharding = infer_resource_partitions( - x, mapping, mesh=mesh, preserve_existing_shardings=False - ).array - - if current_sharding.is_equivalent_to(desired_sharding, ndim=raw_x.ndim): - return x - elif desired_sharding.is_fully_addressable: - raw_x = jax.device_put(raw_x, desired_sharding) - return NamedArray(raw_x, x.axes) - else: - # if the sharding is not fully addressable, we can't use device_put, so we use this hacky workaround. - # TODO: we lose "src" information, but i think that's only for autodiff, and this isn't an autodiff - # context, I think? - shape = raw_x.shape - raw_x = jax.make_array_from_callback(shape, desired_sharding, lambda index: raw_x[index]) - return NamedArray(raw_x, x.axes) + + sharding = infer_resource_partitions(x, mapping, mesh=mesh, preserve_existing_shardings=False) + + return with_sharding_constraint(x, sharding) return htu.tree_map(_do_device_put, x) @@ -214,10 +190,10 @@ def infer_resource_partitions( current_sharding = None if current_sharding is not None: - return NamedArray(current_sharding, node.axes) # type: ignore + return current_sharding else: sharding = NamedSharding(mesh, pspec_for_axis(node.axes, resource_mapping)) - return NamedArray(sharding, node.axes) # type: ignore + return sharding elif is_jax_array_like(node): sharding = getattr(node, "sharding", None) # TODO: these are usually replicated. Is there a better way to tell? @@ -617,7 +593,7 @@ def round_axis_for_partitioning(axis: Axis, mapping: Optional[ResourceMapping] = return Axis(axis.name, new_size) -def _get_mesh(): +def _get_mesh() -> Mesh: from jax.experimental.maps import thread_resources return thread_resources.env.physical_mesh diff --git a/tests/test_partitioning.py b/tests/test_partitioning.py index 55b1fb5..9790654 100644 --- a/tests/test_partitioning.py +++ b/tests/test_partitioning.py @@ -36,7 +36,7 @@ def test_infer_named_axes(): spec = PartitionSpec(None, ResourceAxis.DATA, ResourceAxis.MODEL) - assert axes.named.array == NamedSharding(mesh, spec) + assert axes.named == NamedSharding(mesh, spec) assert axes.unnamed1.is_fully_replicated commit 958fe2879300353484bcbd5baaa8a1246c5d0026 Date: 2024-03-29T14:12:19-07:00 Fix cross-backend shard (#80) diff --git a/src/haliax/partitioning.py b/src/haliax/partitioning.py index 922ac92..ba0fff9 100644 --- a/src/haliax/partitioning.py +++ b/src/haliax/partitioning.py @@ -123,12 +123,12 @@ def shard(x: T, mapping: Optional[ResourceMapping] = None, mesh: Optional[Mesh] if mesh.empty: return x - if is_on_mac_metal(): + if is_in_jit() and is_on_mac_metal(): warnings.warn("Sharding constraints are not supported in jit on metal", RuntimeWarning) return x def _do_device_put(x): - if not is_named_array(x): + if not isinstance(x, NamedArray): return x if not is_jax_array_like(x.array): @@ -137,8 +137,12 @@ def shard(x: T, mapping: Optional[ResourceMapping] = None, mesh: Optional[Mesh] return x sharding = infer_resource_partitions(x, mapping, mesh=mesh, preserve_existing_shardings=False) - - return with_sharding_constraint(x, sharding) + assert isinstance(sharding, NamedSharding) + if is_in_jit(): + return with_sharding_constraint(x, sharding) + else: + sharded_array = jax.device_put(x.array, sharding) + return NamedArray(sharded_array, x.axes) return htu.tree_map(_do_device_put, x) diff --git a/tests/test_partitioning.py b/tests/test_partitioning.py index 9790654..3b13ba7 100644 --- a/tests/test_partitioning.py +++ b/tests/test_partitioning.py @@ -280,3 +280,21 @@ def test_jit_lower_doesnt_blow_up(): assert lowered lowered.cost_analysis() lowered.as_text() + + +def test_cross_device_sharding(): + # this doesn't actually do anything interesting on CPU + cpu_device = jax.local_devices(backend="cpu")[0] + with jax.default_device(cpu_device): + x = hax.ones((Dim1, Dim2)) + + with axis_mapping(resource_map), Mesh( + np.array(jax.devices()).reshape(-1, 1), (ResourceAxis.DATA, ResourceAxis.MODEL) + ): + x = hax.shard(x, resource_map) + z = hax.ones((Dim1, Dim3)) + + x_devices = x.array.devices() + z_devices = z.array.devices() + + assert set(d.platform for d in x_devices) == set(d.platform for d in z_devices) commit aa6fb36887bada1b1c711c1ee582cb684425cfe2 Date: 2024-04-05T21:50:00-07:00 Poetry + Dev Builds (#81) diff --git a/.github/workflows/publish_dev.yaml b/.github/workflows/publish_dev.yaml new file mode 100644 index 0000000..31b45d0 --- /dev/null +++ b/.github/workflows/publish_dev.yaml @@ -0,0 +1,42 @@ +name: Publish Dev Build + +on: + workflow_run: + workflows: ["Run Tests"] + types: + - completed + branches: [main] + +jobs: + build-and-publish: + runs-on: ubuntu-latest + if: ${{ github.event.workflow_run.conclusion == 'success' }} + steps: + - uses: actions/checkout@v2 + - name: Set up Python + uses: actions/setup-python@v2 + with: + python-version: '3.x' + + - name: Install Poetry + run: pip install poetry + + - name: Calculate Version and Build Number + run: | + PROJECT_VERSION=$(poetry version | cut -d ' ' -f2) + BUILD_NUMBER=$(git rev-list --count HEAD) + FULL_VERSION="${PROJECT_VERSION}.dev${BUILD_NUMBER}" + echo "FULL_VERSION=${FULL_VERSION}" >> $GITHUB_ENV + echo "Calculated version with build number: $FULL_VERSION" + - name: Update pyproject.toml version + run: | + poetry version ${{ env.FULL_VERSION }} + + - name: Build package + run: poetry build + + - name: Publish package + uses: actions/upload-artifact@v2 + with: + name: package + path: dist/* diff --git a/pyproject.toml b/pyproject.toml index fd1fd9f..8349d13 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -1,16 +1,14 @@ [build-system] -requires = ["setuptools>=58.0.4", "wheel"] -build-backend = "setuptools.build_meta" +requires = ["poetry-core>=1.0.0"] +build-backend = "poetry.core.masonry.api" -[project] +[tool.poetry] name = "haliax" -version = "1.2" -authors = [ - { name="David Hall", email="dlwh@cs.stanford.edu" }, -] +version = "1.2.0" description = "Named Tensors for Legible Deep Learning in JAX" +authors = ["David Hall <dlwh@stanford.edu>"] +license = "Apache-2.0" readme = "README.md" -requires-python = ">=3.10" classifiers = [ "Programming Language :: Python :: 3", "License :: OSI Approved :: Apache Software License", @@ -19,29 +17,32 @@ classifiers = [ "Development Status :: 4 - Beta", "Intended Audience :: Science/Research", ] -dependencies = [ - # we require that you install jax yourself, since the extras vary by system. - # jax = {version = ">=0.4.19,<0.5.0"} - "equinox>=0.10.6", - "jaxtyping>=0.2.20", - "safetensors[numpy]", - "jmp" -] -[project.optional-dependencies] -dev=["pytest >= 7.4.0", "mypy >= 0.910", "mkdocs >= 1.4.3", "mkdocs-material >= 7.3.3", "mkdocstrings >= 0.22.0", - "mkdocs-literate-nav >= 0.6.0", "mkdocs-macros-plugin >= 0.7.0", "mkdocstrings-python >= 1.1.2", - "mkdocs-include-markdown-plugin", - "pymdown-extensions", - "pygments", - "pymdown-extensions", -] +[project.urls] +"Homepage" = "https://github.com/stanford-crfm/haliax" +"Bug Tracker" = "https://github.com/stanford-crfm/haliax/issues/" -[options] -packages = ["haliax", "haliax.*"] +[tool.poetry.dependencies] +python = ">=3.10,<4.0" +equinox = "^0.10.6" +jaxtyping = "^0.2.20" +#safetensors = {extras = ["numpy"], version = "^0.1"} +jmp = "^0.0.4" -[options.package_data] -haliax = ["src/haliax/*"] +[tool.poetry.dev-dependencies] +pytest = "^7.4.0" +mypy = "^0.910" +mkdocs = "^1.4.3" +mkdocs-material = "^7.3.3" +mkdocstrings = "^0.22.0" +mkdocs-literate-nav = "^0.6.0" +mkdocs-macros-plugin = "^0.7.0" +mkdocstrings-python = "^1.1.2" +mkdocs-include-markdown-plugin = "*" +pymdown-extensions = "^9.0" +pygments = "^2.10.0" +black = {version = "^22.3.0", allow-prereleases = true} +isort = "^5.9.3" [tool.black] line-length = 119 @@ -58,7 +59,3 @@ use_parentheses = true ensure_newline_before_comments = true line_length = 119 src_paths = ["src", "tests"] - -[project.urls] -"Homepage" = "https://github.com/stanford-crfm/haliax" -"Bug Tracker" = "https://github.com/stanford-crfm/haliax/issues/" commit 2e894c2163545cbe18644ff1ec82f5a73a464cb4 Date: 2024-04-05T22:14:56-07:00 let's try actually publishing diff --git a/.github/workflows/publish_dev.yaml b/.github/workflows/publish_dev.yaml index 31b45d0..beee3ae 100644 --- a/.github/workflows/publish_dev.yaml +++ b/.github/workflows/publish_dev.yaml @@ -6,13 +6,18 @@ on: types: - completed branches: [main] + workflow_dispatch: jobs: - build-and-publish: + build-package: runs-on: ubuntu-latest - if: ${{ github.event.workflow_run.conclusion == 'success' }} + # if workflow_run.conclusion is not 'success', the job will not run + # if it's workflow_dispatch, it will run regardless + if: ${{ github.event_name == 'workflow_dispatch' || github.event.workflow_run.conclusion == 'success'}} steps: - uses: actions/checkout@v2 + with: + depth: 0 # for rev-list to work. - name: Set up Python uses: actions/setup-python@v2 with: @@ -35,8 +40,27 @@ jobs: - name: Build package run: poetry build - - name: Publish package + - name: Upload package uses: actions/upload-artifact@v2 with: name: package - path: dist/* + path: dist/ + + + publish-dev: + runs-on: ubuntu-latest + permissions: + id-token: write + steps: + - name: Retrieve release distributions + uses: actions/download-artifact@v4 + with: + name: package + path: dist/ + + - name: Publish release distributions to PyPI Test + uses: pypa/gh-action-pypi-publish@release/v1 + with: + repository-url: https://test.pypi.org/legacy/ + + commit a2e6c326d1867e83909d2d0dc878881af7deb273 Date: 2024-04-05T23:35:07-07:00 forgot a needs diff --git a/.github/workflows/publish_dev.yaml b/.github/workflows/publish_dev.yaml index beee3ae..1e0a2f9 100644 --- a/.github/workflows/publish_dev.yaml +++ b/.github/workflows/publish_dev.yaml @@ -47,8 +47,11 @@ jobs: path: dist/ + # cf https://test.pypi.org/manage/project/haliax/settings/publishing/ publish-dev: runs-on: ubuntu-latest + needs: + - build-package permissions: id-token: write steps: commit 947b01359b3711ad513ea00c4231c47d76b6fd25 Date: 2024-04-05T23:43:24-07:00 grrr diff --git a/.github/workflows/publish_dev.yaml b/.github/workflows/publish_dev.yaml index 1e0a2f9..2b9b64d 100644 --- a/.github/workflows/publish_dev.yaml +++ b/.github/workflows/publish_dev.yaml @@ -15,7 +15,8 @@ jobs: # if it's workflow_dispatch, it will run regardless if: ${{ github.event_name == 'workflow_dispatch' || github.event.workflow_run.conclusion == 'success'}} steps: - - uses: actions/checkout@v2 + - name: Checkout code + uses: actions/checkout@v2 with: depth: 0 # for rev-list to work. - name: Set up Python commit 9c87b856ca055a2932d064692bb184bc1768c3e8 Date: 2024-04-05T23:48:03-07:00 sigh diff --git a/.github/workflows/publish_dev.yaml b/.github/workflows/publish_dev.yaml index 2b9b64d..2114806 100644 --- a/.github/workflows/publish_dev.yaml +++ b/.github/workflows/publish_dev.yaml @@ -42,7 +42,7 @@ jobs: run: poetry build - name: Upload package - uses: actions/upload-artifact@v2 + uses: actions/upload-artifact@v4 with: name: package path: dist/ commit 22bab05094d47a4fee36a8f1dccb2977d76992e3 Date: 2024-04-06T00:54:06-07:00 bump version: diff --git a/pyproject.toml b/pyproject.toml index 8349d13..c59a6ea 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -4,7 +4,7 @@ build-backend = "poetry.core.masonry.api" [tool.poetry] name = "haliax" -version = "1.2.0" +version = "1.3" description = "Named Tensors for Legible Deep Learning in JAX" authors = ["David Hall <dlwh@stanford.edu>"] license = "Apache-2.0" commit 6304dd4da873949e93a300e74e0b89a8872000e6 Date: 2024-04-06T22:37:51-07:00 ok, let's do hatch instead. this might work diff --git a/.github/workflows/publish_dev.yaml b/.github/workflows/publish_dev.yaml index 2114806..3abd8fc 100644 --- a/.github/workflows/publish_dev.yaml +++ b/.github/workflows/publish_dev.yaml @@ -18,28 +18,28 @@ jobs: - name: Checkout code uses: actions/checkout@v2 with: - depth: 0 # for rev-list to work. + depth: 1000 # for rev-list to work. - name: Set up Python uses: actions/setup-python@v2 with: python-version: '3.x' - - name: Install Poetry - run: pip install poetry - - name: Calculate Version and Build Number run: | - PROJECT_VERSION=$(poetry version | cut -d ' ' -f2) + PROJECT_VERSION=$(sed -n 's/__version__ = "\(.*\)"/\1/p' src/haliax/__about__.py) BUILD_NUMBER=$(git rev-list --count HEAD) FULL_VERSION="${PROJECT_VERSION}.dev${BUILD_NUMBER}" echo "FULL_VERSION=${FULL_VERSION}" >> $GITHUB_ENV echo "Calculated version with build number: $FULL_VERSION" - name: Update pyproject.toml version run: | - poetry version ${{ env.FULL_VERSION }} - + # replace the version in __about__.py + sed -i "s/__version__ = \".*\"/__version__ = \"$FULL_VERSION\"/g" src/haliax/__about__.py - name: Build package - run: poetry build + run: | + python -m pip install --upgrade pip + pip install build + python -m build - name: Upload package uses: actions/upload-artifact@v4 @@ -62,9 +62,10 @@ jobs: name: package path: dist/ - - name: Publish release distributions to PyPI Test - uses: pypa/gh-action-pypi-publish@release/v1 - with: - repository-url: https://test.pypi.org/legacy/ +# temporarily disabled for testing +# - name: Publish release distributions to PyPI Test +# uses: pypa/gh-action-pypi-publish@release/v1 +# with: +# repository-url: https://test.pypi.org/legacy/ diff --git a/.github/workflows/run_pre_commit.yaml b/.github/workflows/run_pre_commit.yaml index 153feb4..113b337 100644 --- a/.github/workflows/run_pre_commit.yaml +++ b/.github/workflows/run_pre_commit.yaml @@ -8,7 +8,7 @@ jobs: runs-on: ubuntu-latest strategy: matrix: - python-version: ["3.10"] + python-version: ["3.10.11"] steps: - uses: actions/checkout@v3 diff --git a/.github/workflows/run_tests.yaml b/.github/workflows/run_tests.yaml index 0c82cc0..a6472f2 100644 --- a/.github/workflows/run_tests.yaml +++ b/.github/workflows/run_tests.yaml @@ -8,7 +8,7 @@ jobs: runs-on: ubuntu-latest strategy: matrix: - python-version: ["3.10"] + python-version: ["3.10.11"] steps: - uses: actions/checkout@v3 diff --git a/pyproject.toml b/pyproject.toml index c59a6ea..4f523ed 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -1,14 +1,17 @@ [build-system] -requires = ["poetry-core>=1.0.0"] -build-backend = "poetry.core.masonry.api" +requires = ["hatchling"] +build-backend = "hatchling.build" -[tool.poetry] +[project] name = "haliax" -version = "1.3" +# Set for release builds +#version = "1.3" +authors = [ + { name="David Hall", email="dlwh@cs.stanford.edu" }, +] description = "Named Tensors for Legible Deep Learning in JAX" -authors = ["David Hall <dlwh@stanford.edu>"] -license = "Apache-2.0" readme = "README.md" +requires-python = ">=3.10" classifiers = [ "Programming Language :: Python :: 3", "License :: OSI Approved :: Apache Software License", @@ -17,32 +20,31 @@ classifiers = [ "Development Status :: 4 - Beta", "Intended Audience :: Science/Research", ] +dependencies = [ + # we require that you install jax yourself, since the extras vary by system. + # jax = {version = ">=0.4.19,<0.5.0"} + "equinox>=0.10.6", + "jaxtyping>=0.2.20", + "jmp>=0.0.4", +] -[project.urls] -"Homepage" = "https://github.com/stanford-crfm/haliax" -"Bug Tracker" = "https://github.com/stanford-crfm/haliax/issues/" +[project.optional-dependencies] +dev=["pytest >= 7.4.0", "mypy >= 0.910", "mkdocs >= 1.4.3", "mkdocs-material >= 7.3.3", "mkdocstrings >= 0.22.0", + "mkdocs-literate-nav >= 0.6.0", "mkdocs-macros-plugin >= 0.7.0", "mkdocstrings-python >= 1.1.2", + "mkdocs-include-markdown-plugin", + "pymdown-extensions", + "pygments", + "pymdown-extensions", +] -[tool.poetry.dependencies] -python = ">=3.10,<4.0" -equinox = "^0.10.6" -jaxtyping = "^0.2.20" -#safetensors = {extras = ["numpy"], version = "^0.1"} -jmp = "^0.0.4" - -[tool.poetry.dev-dependencies] -pytest = "^7.4.0" -mypy = "^0.910" -mkdocs = "^1.4.3" -mkdocs-material = "^7.3.3" -mkdocstrings = "^0.22.0" -mkdocs-literate-nav = "^0.6.0" -mkdocs-macros-plugin = "^0.7.0" -mkdocstrings-python = "^1.1.2" -mkdocs-include-markdown-plugin = "*" -pymdown-extensions = "^9.0" -pygments = "^2.10.0" -black = {version = "^22.3.0", allow-prereleases = true} -isort = "^5.9.3" +[tool.hatch.version] +path = "src/haliax/__about__.py" + +[options] +packages = ["haliax", "haliax.*"] + +[options.package_data] +haliax = ["src/haliax/*"] [tool.black] line-length = 119 @@ -59,3 +61,7 @@ use_parentheses = true ensure_newline_before_comments = true line_length = 119 src_paths = ["src", "tests"] + +[project.urls] +"Homepage" = "https://github.com/stanford-crfm/haliax" +"Bug Tracker" = "https://github.com/stanford-crfm/haliax/issues/" diff --git a/src/haliax/__about__.py b/src/haliax/__about__.py new file mode 100644 index 0000000..9f6cc16 --- /dev/null +++ b/src/haliax/__about__.py @@ -0,0 +1 @@ +__version__ = "1.3" commit 34feaf05ae509414d69abd97731274280ca0d9ad Date: 2024-04-06T22:42:19-07:00 akldmlad diff --git a/pyproject.toml b/pyproject.toml index 4f523ed..9228205 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -5,7 +5,7 @@ build-backend = "hatchling.build" [project] name = "haliax" # Set for release builds -#version = "1.3" +version = "1.3" authors = [ { name="David Hall", email="dlwh@cs.stanford.edu" }, ] commit 9a3d08b0a0d684f4a001d856d911a58357fc535c Date: 2024-04-06T23:12:23-07:00 fix revision number calculation for auto-publishing (#82) diff --git a/.github/workflows/publish_dev.yaml b/.github/workflows/publish_dev.yaml index 3abd8fc..86400ce 100644 --- a/.github/workflows/publish_dev.yaml +++ b/.github/workflows/publish_dev.yaml @@ -11,14 +11,12 @@ on: jobs: build-package: runs-on: ubuntu-latest - # if workflow_run.conclusion is not 'success', the job will not run - # if it's workflow_dispatch, it will run regardless if: ${{ github.event_name == 'workflow_dispatch' || github.event.workflow_run.conclusion == 'success'}} steps: - name: Checkout code - uses: actions/checkout@v2 + uses: actions/checkout@v4 with: - depth: 1000 # for rev-list to work. + fetch-depth: 1000 - name: Set up Python uses: actions/setup-python@v2 with: @@ -26,6 +24,7 @@ jobs: - name: Calculate Version and Build Number run: | + echo "We are commit $GITHUB_SHA" PROJECT_VERSION=$(sed -n 's/__version__ = "\(.*\)"/\1/p' src/haliax/__about__.py) BUILD_NUMBER=$(git rev-list --count HEAD) FULL_VERSION="${PROJECT_VERSION}.dev${BUILD_NUMBER}" @@ -62,10 +61,9 @@ jobs: name: package path: dist/ -# temporarily disabled for testing -# - name: Publish release distributions to PyPI Test -# uses: pypa/gh-action-pypi-publish@release/v1 -# with: -# repository-url: https://test.pypi.org/legacy/ + - name: Publish release distributions to PyPI Test + uses: pypa/gh-action-pypi-publish@release/v1 + with: + repository-url: https://test.pypi.org/legacy/ commit 98233204cf4ba5437e28753f1c607736595d18f9 Date: 2024-04-07T21:50:55-07:00 ok, we're just gonna publish dev builds to pypi diff --git a/.github/workflows/publish_dev.yaml b/.github/workflows/publish_dev.yaml index 86400ce..7464e57 100644 --- a/.github/workflows/publish_dev.yaml +++ b/.github/workflows/publish_dev.yaml @@ -16,7 +16,7 @@ jobs: - name: Checkout code uses: actions/checkout@v4 with: - fetch-depth: 1000 + fetch-depth: 0 - name: Set up Python uses: actions/setup-python@v2 with: @@ -24,7 +24,6 @@ jobs: - name: Calculate Version and Build Number run: | - echo "We are commit $GITHUB_SHA" PROJECT_VERSION=$(sed -n 's/__version__ = "\(.*\)"/\1/p' src/haliax/__about__.py) BUILD_NUMBER=$(git rev-list --count HEAD) FULL_VERSION="${PROJECT_VERSION}.dev${BUILD_NUMBER}" @@ -64,6 +63,6 @@ jobs: - name: Publish release distributions to PyPI Test uses: pypa/gh-action-pypi-publish@release/v1 with: - repository-url: https://test.pypi.org/legacy/ + repository-url: https://pypi.org/legacy/ commit 274e1389bf36c1866ed6584fa45021fb73d8e6c7 Date: 2024-04-07T22:25:02-07:00 try this diff --git a/.github/workflows/publish_dev.yaml b/.github/workflows/publish_dev.yaml index 7464e57..a2cf56c 100644 --- a/.github/workflows/publish_dev.yaml +++ b/.github/workflows/publish_dev.yaml @@ -62,7 +62,7 @@ jobs: - name: Publish release distributions to PyPI Test uses: pypa/gh-action-pypi-publish@release/v1 - with: - repository-url: https://pypi.org/legacy/ +# with: +# repository-url: https://pypi.org/legacy/ commit 2ee26e955f2a51d7a4171e6ad068ffdfc0acf5a8 Date: 2024-04-07T22:37:38-07:00 sigh diff --git a/.github/workflows/publish_dev.yaml b/.github/workflows/publish_dev.yaml index a2cf56c..add3e20 100644 --- a/.github/workflows/publish_dev.yaml +++ b/.github/workflows/publish_dev.yaml @@ -32,6 +32,7 @@ jobs: - name: Update pyproject.toml version run: | # replace the version in __about__.py + echo "Updating version in __about__.py to $FULL_VERSION" sed -i "s/__version__ = \".*\"/__version__ = \"$FULL_VERSION\"/g" src/haliax/__about__.py - name: Build package run: | @@ -60,8 +61,8 @@ jobs: name: package path: dist/ - - name: Publish release distributions to PyPI Test - uses: pypa/gh-action-pypi-publish@release/v1 +# - name: Publish release distributions to PyPI Test +# uses: pypa/gh-action-pypi-publish@release/v1 # with: # repository-url: https://pypi.org/legacy/ diff --git a/pyproject.toml b/pyproject.toml index 9228205..4f523ed 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -5,7 +5,7 @@ build-backend = "hatchling.build" [project] name = "haliax" # Set for release builds -version = "1.3" +#version = "1.3" authors = [ { name="David Hall", email="dlwh@cs.stanford.edu" }, ] commit c1ce8140c7c73d9e8e71b767eb42bdc7987c95d6 Date: 2024-04-07T22:47:01-07:00 mfklamlf diff --git a/pyproject.toml b/pyproject.toml index 4f523ed..d1420b0 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -27,6 +27,7 @@ dependencies = [ "jaxtyping>=0.2.20", "jmp>=0.0.4", ] +dynamic =[ "version" ] [project.optional-dependencies] dev=["pytest >= 7.4.0", "mypy >= 0.910", "mkdocs >= 1.4.3", "mkdocs-material >= 7.3.3", "mkdocstrings >= 0.22.0", commit e8199cd76363be1d69cc1b3177792720605651b2 Date: 2024-04-07T22:52:24-07:00 re-enable build publishing diff --git a/.github/workflows/publish_dev.yaml b/.github/workflows/publish_dev.yaml index add3e20..a323213 100644 --- a/.github/workflows/publish_dev.yaml +++ b/.github/workflows/publish_dev.yaml @@ -61,9 +61,9 @@ jobs: name: package path: dist/ -# - name: Publish release distributions to PyPI Test -# uses: pypa/gh-action-pypi-publish@release/v1 -# with: -# repository-url: https://pypi.org/legacy/ + - name: Publish release distributions to PyPI Test + uses: pypa/gh-action-pypi-publish@release/v1 + with: + repository-url: https://pypi.org/legacy/ commit 02c353cd19819b21e1365d29e3cdbf6f419258d9 Date: 2024-04-07T22:55:19-07:00 once more diff --git a/.github/workflows/publish_dev.yaml b/.github/workflows/publish_dev.yaml index a323213..9899637 100644 --- a/.github/workflows/publish_dev.yaml +++ b/.github/workflows/publish_dev.yaml @@ -63,7 +63,5 @@ jobs: - name: Publish release distributions to PyPI Test uses: pypa/gh-action-pypi-publish@release/v1 - with: - repository-url: https://pypi.org/legacy/ commit dd92ee87e107809d576971bbd456386b363668f4 Date: 2024-04-07T23:13:30-07:00 start 1.4 diff --git a/src/haliax/__about__.py b/src/haliax/__about__.py index 9f6cc16..e992399 100644 --- a/src/haliax/__about__.py +++ b/src/haliax/__about__.py @@ -1 +1 @@ -__version__ = "1.3" +__version__ = "1.4" commit 5599b78b9f6504e57e35057d1c582a45809a6db8 Date: 2024-04-13T19:33:39-07:00 allow einsum to accept aliases similar to rearrange (#84) diff --git a/docs/matmul.md b/docs/matmul.md index 6f7303e..531e326 100644 --- a/docs/matmul.md +++ b/docs/matmul.md @@ -3,7 +3,10 @@ Haliax has two ways to do matrix multiplication (and tensor contractions more generally): [haliax.dot][] and [haliax.einsum][]. [haliax.dot][] and [haliax.einsum][] can both express any tensor contraction, though in different situations one or the other may be -more suitable for expressing a particular contraction. +more suitable for expressing a particular contraction In general: + +- Use [haliax.dot][] when you want to express a simple matrix multiplication over one or a few axes. +- Use [haliax.einsum][] when you want to express a more complex tensor contraction. See also the API reference for [haliax.dot][] and [haliax.einsum][] and the [cheat sheet section](cheatsheet.md#matrix-multiplication). @@ -68,6 +71,9 @@ Haliax's version of `einsum` comes in three modes: "ordered", "unordered", and " These modes are all accessible through the same function without any flags: the syntax of the `einsum` string determines which mode is used. +The syntax for Haliax's `einsum` is similar to [`haliax.rearrange`](rearrange.md), which +is in turn similar to [einops.rearrange](https://einops.rocks/api/rearrange/). + #### Ordered Mode Haliax's `einsum` has an "ordered" mode that is similar to `einops.einsum`'s behavior. @@ -119,6 +125,22 @@ y = hax.einsum("{H ...} -> ...", x) # shape is (W, D) This mode is most similar to [haliax.dot][]'s behavior, though it's a bit more expressive. +You can also use axis aliases in the `einsum` string, which can be useful for expressing contractions +in library code or just for shortening the string: + +```python +Height = hax.Axis("Height", 3) +Width = hax.Axis("Width", 4) +Depth = hax.Axis("Depth", 5) + +x = hax.ones((Height, Width, Depth)) +w = hax.ones((Depth,)) + +y = hax.einsum("{H W D} -> H W", x, H=Height, W=Width, D=Depth) # shape is (Height, Width) +y = hax.einsum("{D} -> ", w, D=Depth) # shape is (Height, Width) +``` + + #### Output Axes Mode In "output axes" mode, you only specify the axes that should be in the output. All other @@ -142,3 +164,16 @@ y = hax.einsum("-> D", w) # shape is (D,) We don't recommend using this mode except in cases when you're sure of the full shape of the input arrays or you are sure you don't want to let users implicitly batch over any axes. + +Output axes mode also supports axis aliases: + +```python +Height = hax.Axis("Height", 3) +Width = hax.Axis("Width", 4) +Depth = hax.Axis("Depth", 5) + +x = hax.ones((Height, Width, Depth)) +w = hax.ones((Depth,)) +y = hax.einsum("-> Height Width", x, Height=Height, Width=Width, Depth=Depth) # shape is (Height, Width) +y = hax.einsum("-> Depth", w, Depth=Depth) # shape is (Depth,) +``` diff --git a/src/haliax/_src/einsum.py b/src/haliax/_src/einsum.py index 4889d10..6a65f44 100644 --- a/src/haliax/_src/einsum.py +++ b/src/haliax/_src/einsum.py @@ -1,13 +1,12 @@ import functools from types import EllipsisType -from typing import Optional, Sequence, Tuple, Union +from typing import Optional, Tuple import jax.lax -import jax.numpy as jnp import haliax -from ..axis import AxisSelector, axis_name, eliminate_axes, rearrange_for_partial_order, union_axes +from ..axis import Axis, AxisSelector, axis_name, eliminate_axes, rearrange_for_partial_order, union_axes from ..core import NamedArray from ..jax_utils import _jittable_dg_einsum from ..types import DTypeLike, PrecisionLike @@ -21,6 +20,7 @@ def einsum( precision: PrecisionLike = None, preferred_element_type: Optional[DTypeLike] = None, _dot_general=jax.lax.dot_general, + **axis_aliases, ) -> NamedArray: """Compute the tensor contraction of the input arrays according to Haliax's named variant of the Einstein summation convention. @@ -38,12 +38,16 @@ def einsum( >>> hax.einsum("{H W D} -> H W", a, b) >>> hax.einsum("{D} -> ", a, b) # same as the previous example >>> hax.einsum("-> H W", a, b) # same as the first example + >>> # axis aliases, useful for generic code + >>> hax.einsum("{x y} -> y", a, b, x=H, y=W) Args: equation: The einsum equation. arrays: The input arrays. precision: The precision of the computation. preferred_element_type: The preferred element type of the computation. + _dot_general: The dot_general function to use. + axis_aliases: The axis aliases to use. Returns: The result of the einsum. @@ -59,17 +63,17 @@ def einsum( # NB: we're using JAX's einsum which only supports one letter names for dims if len(lhses) == 1 and len(lhses[0].captures) == 0 and lhses[0].is_ordered: # case 3: get the output axes, contract the others - spec, out_axes = _output_only_named_einsum(equation, arrays, rhs) + spec, out_axes = _output_only_named_einsum(equation, arrays, rhs, axis_aliases) elif len(lhses) == 1 and not lhses[0].is_ordered: # case 2: some axes are named. Those named only on the lhs are contracted, the others are kept # subcase: if there's an ellipsis on the lhs, we contract all the axes that are not named on the rhs - spec, out_axes = _unordered_einsum(arrays, equation, lhses, rhs) + spec, out_axes = _unordered_einsum(arrays, equation, lhses[0], rhs, axis_aliases) else: # general case: we have a normal einsum. we don't allow unordered axes here if any(not lhs.is_ordered for lhs in lhses): raise_parse_error("Cannot have multiple unordered axes in an einsum", equation, None) - spec, out_axes = _positional_einsum_spec(equation, arrays, lhses, rhs) + spec, out_axes = _positional_einsum_spec(equation, arrays, lhses, rhs, axis_aliases) out_raw = _jittable_dg_einsum( spec, @@ -83,12 +87,14 @@ def einsum( return haliax.auto_sharded(out) -def _unordered_einsum(arrays, equation, lhses, rhs): - used_letters: set[str] = set() - name_mappings_for_einsum: dict[str, str] = {} - lhs = lhses[0] - candidate_axes, has_ellipsis_lhs = _captures_to_axis_names(equation, lhs) - rhs_axes, has_ellipsis_rhs = _captures_to_axis_names(equation, rhs) +def _unordered_einsum(arrays, equation, lhs, rhs, axis_aliases): + candidate_axes, has_ellipsis_lhs, covered_lhs = _captures_to_axis_names(equation, lhs, axis_aliases) + rhs_axes, has_ellipsis_rhs, covered_rhs = _captures_to_axis_names(equation, rhs, axis_aliases) + + for alias_name in axis_aliases: + if alias_name not in covered_lhs and alias_name not in covered_rhs: + raise_parse_error(f"Axis alias {alias_name} not used in the einsum", equation, None) + all_input_axes = _all_input_axes(arrays) if has_ellipsis_rhs: out_axes = rearrange_for_partial_order(rhs_axes, all_input_axes) @@ -105,15 +111,17 @@ def _unordered_einsum(arrays, equation, lhses, rhs): # what people expect rhs_axes = [Ellipsis] + rhs_axes # type: ignore out_axes = rearrange_for_partial_order(rhs_axes, almost_out_axes) - spec = _make_einsum_spec(name_mappings_for_einsum, used_letters, arrays, out_axes) + spec = _make_einsum_spec(arrays, out_axes) return spec, out_axes -def _output_only_named_einsum(equation, arrays, rhs): - used_letters: set[str] = set() - name_mappings_for_einsum: dict[str, str] = {} - +def _output_only_named_einsum(equation, arrays, rhs, axis_aliases): out_axes = [] + used_axes = set() + used_aliases = set() + + input_axis_names = set(ax.name for ax in _all_input_axes(arrays)) + for capture in rhs.captures: if capture is Ellipsis: raise_parse_error("Can't use ellipsis on the rhs of an einsum without an lhs", equation, None) @@ -125,23 +133,51 @@ def _output_only_named_einsum(equation, arrays, rhs): ) else: name = capture.binding + used_aliases.add(name) + + if name in axis_aliases: + # this could be axis or a name. if an axis, need to assert the size + axis = axis_aliases[name] + if isinstance(axis, Axis): + _check_axis_size_consistency(arrays, axis, name) + ax_name = axis_name(axis) + + if ax_name in used_axes: + raise_parse_error( + f"Axis {name} occurs multiple times on the rhs. Probably because of multiple aliasing?", + equation, + capture.char_range, + ) + + name = ax_name + used_axes.add(name) if name in out_axes: - raise_parse_error(f"Axis name {name} occurs multiple times on the rhs", equation, capture.char_range) + raise_parse_error( + f"Axis capture {name} occurs multiple times on the rhs", equation, capture.char_range + ) + + if name not in input_axis_names: + raise_parse_error(f"Axis {name} not found in any of the input arrays", equation, capture.char_range) out_axes.append(name) - spec = _make_einsum_spec(name_mappings_for_einsum, used_letters, arrays, out_axes) + _check_for_unused_aliases(axis_aliases, used_aliases, equation) + + spec = _make_einsum_spec(arrays, out_axes) return spec, out_axes -def _positional_einsum_spec(equation, arrays, lhses, rhs): +def _positional_einsum_spec(equation, arrays, lhses, rhs, axis_aliases): used_letters: set[str] = set() name_mappings_for_einsum: dict[str, str] = {} + used_aliases = set() if len(lhses) != len(arrays): raise ValueError(f"Number of lhses ({len(lhses)}) does not match number of arrays ({len(arrays)})") - table = AliasTable() + + # For this function, axis_aliases exists entirely for checking axis sizes against what's in the arrays + table = AliasTable(axis_aliases) # ok, we're going to lead pretty heavily on einsum here. We just need to figure out the names of the axes # and do any error checking (that there are no mismatched names) # once we do that, we can pass a slightly modified spec to einsum (namely that we shorten the names of the axes) @@ -164,6 +200,9 @@ def _positional_einsum_spec(equation, arrays, lhses, rhs): raise_parse_error("Parenthesized axes are not currently supported", equation, capture.char_range) else: name = capture.binding + if name in axis_aliases: + used_aliases.add(name) + if axis_off >= len(a.axes): raise ValueError("Mismatched number of axes in einsum") table.bind_alias(name, a.axes[axis_off], equation, capture.char_range) @@ -184,6 +223,9 @@ def _positional_einsum_spec(equation, arrays, lhses, rhs): break else: name = capture.binding + if name in axis_aliases: + used_aliases.add(name) + if axis_off < final_lhs_axis_off: raise ValueError("Mismatched number of axes in einsum") table.bind_alias(name, a.axes[axis_off], equation, capture.char_range) @@ -230,6 +272,8 @@ def _positional_einsum_spec(equation, arrays, lhses, rhs): spec += letter out_axes.append(axis) + _check_for_unused_aliases(axis_aliases, used_aliases, equation) + if has_ellipsis_rhs: all_input_axes = _all_input_axes(arrays) # eliminate the axes that are contracted @@ -244,7 +288,8 @@ def _all_input_axes(arrays): return ensure_tuple(functools.reduce(union_axes, (a.axes for a in arrays), ())) # type: ignore -def _captures_to_axis_names(equation, lhs) -> Tuple[list[str | EllipsisType], bool]: +def _captures_to_axis_names(equation, lhs, aliases) -> Tuple[list[str | EllipsisType], bool, set[str]]: + covered_aliases = set() candidate_axes: list[str | EllipsisType] = [] has_ellipsis = False for capture in lhs.captures: @@ -255,11 +300,17 @@ def _captures_to_axis_names(equation, lhs) -> Tuple[list[str | EllipsisType], bo raise_parse_error("Parenthesized axes are not currently supported", equation, capture.char_range) else: name = capture.binding + if name in aliases: + covered_aliases.add(name) + axis = aliases[name] + name = axis_name(axis) candidate_axes.append(name) - return candidate_axes, has_ellipsis + return candidate_axes, has_ellipsis, covered_aliases -def _make_einsum_spec(name_mappings_for_einsum, used_letters, arrays, out_axes): +def _make_einsum_spec(arrays, out_axes): + name_mappings_for_einsum: dict[str, str] = {} + used_letters: set[str] = set() spec = "" for operand in arrays: if len(spec): @@ -289,3 +340,30 @@ def _assign_letter_to_name(name, name_mappings_for_einsum, used_letters): name_mappings_for_einsum[name] = letter used_letters.add(letter) return letter + + +def _check_axis_size_consistency(arrays, axis, name_in_spec): + # ensure the size is correct and the axis is present + found = False + ax_name = axis_name(axis) + for array_index, array in enumerate(arrays): + try: + resolved = array.resolve_axis(ax_name) + except ValueError: + pass + else: + found = True + if resolved.size != axis.size: + raise ValueError( + f"Size mismatch for axis {ax_name}. In array {array_index}," + f" {axis} has size {resolved.size} but expected {axis.size}," + f"because of the alias {name_in_spec}={axis}" + ) + if not found: + raise ValueError(f"Axis {ax_name} not found in any of the input arrays") + + +def _check_for_unused_aliases(axis_aliases, used_aliases, equation): + if any(alias not in used_aliases for alias in axis_aliases): + unused_aliases_str = ", ".join([alias for alias in axis_aliases if alias not in used_aliases]) + raise_parse_error(f"Unused aliases from kwargs: {unused_aliases_str}", equation, None) diff --git a/src/haliax/_src/parsing.py b/src/haliax/_src/parsing.py index 98c0267..4bce2d3 100644 --- a/src/haliax/_src/parsing.py +++ b/src/haliax/_src/parsing.py @@ -225,8 +225,9 @@ class AliasTable: def __init__(self, bindings=None): if bindings is None: - bindings = {} - self.bindings = bindings + self.bindings = {} + else: + self.bindings = {**bindings} def dealias_binding(self, binding: str) -> Optional[AxisSelector]: return self.bindings.get(binding, None) @@ -235,6 +236,15 @@ class AliasTable: if axis.name in self.bindings: if self.bindings[alias] != axis: raise_parse_error(f"Alias {alias} is assigned to more than one axis", expr, char_range) + elif alias in self.bindings: + current = self.bindings[alias] + if isinstance(current, Axis): + if current != axis: + raise_parse_error(f"Alias {alias} is assigned to more than one axis", expr, char_range) + elif current != axis.name: + raise_parse_error(f"Alias {alias} is assigned to more than one axis", expr, char_range) + else: + self.bindings[alias] = axis else: self.bindings[alias] = axis diff --git a/src/haliax/core.py b/src/haliax/core.py index c08bba6..c61c572 100644 --- a/src/haliax/core.py +++ b/src/haliax/core.py @@ -184,6 +184,8 @@ class NamedArray: """ Returns the axes corresponding to the given axis selection. That is, it return the [haliax.Axis][] values themselves, not just their names. + + Raises a ValueError if any of the axes are not found. """ indices = self._lookup_indices(axes) if isinstance(indices, int): diff --git a/tests/test_einsum.py b/tests/test_einsum.py index e73031f..992bf6c 100644 --- a/tests/test_einsum.py +++ b/tests/test_einsum.py @@ -37,6 +37,28 @@ def test_einsum_basic_positional(): ) +def test_einsum_positional_aliases(): + Height = Axis("Height", 2) + Width = Axis("Width", 3) + Depth = Axis("Depth", 4) + + m1 = NamedArray(jnp.ones((Height.size, Width.size, Depth.size)), (Height, Width, Depth)) + m2 = NamedArray(jnp.ones((Depth.size, Width.size, Height.size)), (Depth, Width, Height)) + + assert jnp.all( + jnp.equal(einsum("i j k,k j i-> j k", m1, m2, i=Height).array, jnp.einsum("ijk,kji->jk", m1.array, m2.array)) + ) + + with pytest.raises(ValueError): + einsum("i j k,k j i-> j k", m1, m2, i=Width) + + with pytest.raises(ValueError): + einsum("i j k,q j i-> j k", m1, m2, i=Height, q=Height) + + with pytest.raises(ValueError): + einsum("i j k,k j i-> j k", m1, m2, i=Height, q=Height) + + def test_einsum_basic_named(): Height = Axis("Height", 2) Width = Axis("Width", 3) @@ -148,6 +170,32 @@ def test_einsum_unordered_ellipses(): ) +def test_einsum_unordered_aliases(): + Height = Axis("Height", 2) + Width = Axis("Width", 3) + Depth = Axis("Depth", 4) + + m1 = hax.ones((Height, Width, Depth)) + m2 = hax.ones((Depth, Width, Height)) + + assert jnp.all( + jnp.equal( + einsum("{h w d} -> h w", m1, m2, h=Height, w=Width, d=Depth).array, + jnp.einsum("ijk,kji->ij", m1.array, m2.array), + ) + ) + + # test error cases: + + # Missing alias + with pytest.raises(ValueError, match="Axis d not present"): + einsum("{h w d} -> h w", m1, m2, h=Height, w=Width) + + # Extra alias + with pytest.raises(ValueError, match="Axis alias d not used"): + einsum("{h w} -> h w", m1, m2, h=Height, w=Width, d=Depth) + + def test_einsum_ordered_ellipsis(): Height = Axis("Height", 2) Width = Axis("Width", 3) @@ -272,3 +320,35 @@ def test_einsum_examples(): hax_out = hax.einsum("{...} -> ", hax_im, hax_w2) jnp_out = jnp.einsum("bhwc,ce -> ", im, w2) assert jnp.all(jnp.equal(hax_out.array, jnp_out)) + + +def test_einsum_output_only_mode(): + # tests "-> out axes" + Height = Axis("Height", 2) + Width = Axis("Width", 3) + Depth = Axis("Depth", 4) + + m1 = hax.ones((Height, Width, Depth)) + m2 = hax.ones((Depth, Width, Height)) + m3 = hax.ones((Height, Depth)) + + assert jnp.all(jnp.equal(einsum("-> Height Width", m1, m2).array, jnp.einsum("ijk,kji->ij", m1.array, m2.array))) + assert jnp.all(jnp.equal(einsum("-> Height", m1).array, jnp.einsum("ijk->i", m1.array))) + + with pytest.raises(ValueError): + einsum("-> Q Width", m1) + + with pytest.raises(ValueError, match=".*Unused aliases from kwargs: Q$"): + einsum("-> Height Width", m1, m2, Q=Axis("Q", 2)) + + assert jnp.all(jnp.equal(einsum("-> h w", m1, h=Height, w=Width).array, jnp.einsum("ijk->ij", m1.array))) + + assert jnp.all( + jnp.equal(einsum("-> h w", m1, m3, h=Height, w=Width).array, jnp.einsum("ijk,ik->ij", m1.array, m3.array)) + ) + + with pytest.raises(ValueError, match=".*Size mismatch.*"): + einsum("-> h w", m1, h=Height.resize(4), w=Width) + + with pytest.raises(ValueError, match=".*not found in any of the input arrays.*"): + einsum("-> h w", m3, h=Height, w=Width.resize(4)) commit 864a615f30e8eb397a1d7bc4447f2829980c1dd2 Date: 2024-04-14T01:31:08-07:00 add in-place mutation ops for NamedArrays, support lists/1-d JAX Arrays for indexing (#85) diff --git a/docs/fp8.md b/docs/fp8.md index fac3dd9..99fc762 100644 --- a/docs/fp8.md +++ b/docs/fp8.md @@ -1,7 +1,8 @@ # FP8 Training !!! warning - FP8 training in Haliax is currently experimental and may change in the future. + + FP8 training in Haliax is currently experimental and may change in the future. FP8 refers to 8-bit floating point numbers. FP8 is a massively reduced precision compared to the 32-bit floating point numbers or 16-bit floating point numbers that are typically used in deep learning: there are only 256 possible values in FP8, compared to @@ -123,7 +124,7 @@ you will get the gradient computation as normal, but you'll also get the updated This updated state needs to directly replace the state in the module (rather than be used for a gradient step), which is why you need to use the `partition_for_grad_overwrite` -The FP8 `dot_general` module is implemented in [haliax.quantization.Fp8DotGeneral][]. It's actually not that complicated: +The FP8 `dot_general` module is implemented in [haliax.quantization.Fp8DotGeneralOp][]. It's actually not that complicated: 1) It holds a scaling factor and history of maximum values for each of (lhs, rhs, output) and updates them based on the gradients. diff --git a/docs/indexing.md b/docs/indexing.md index cd57b7b..60a7488 100644 --- a/docs/indexing.md +++ b/docs/indexing.md @@ -37,12 +37,42 @@ Otherwise, the idea is pretty straightforward: any unspecified axes are treated slices are kept in reduced dimensions, and integers eliminate dimensions. If all dimensions are eliminated, a scalar JAX ndarray is returned. +The following types are supported for indexing: + +* Integers, including scalar JAX arrays +* Slices +* [haliax.dslice][] objects (See [Dynamic Slices](#dynamic-slices) below.) +* Lists of integers +* Named arrays (See [Advanced Indexing](#advanced-indexing) below.) +* 1-D JAX Arrays of integers + +1-D JAX Arrays are interpreted as NamedArrays with a single axis with the same name as +the one they are slicing. That is: + +```python +import haliax as hax +import jax +import jax.numpy as jnp + +X = hax.Axis("X", 10) +Y = hax.Axis("Y", 20) + +a = hax.random.uniform(jax.random.PRNGKey(0), (X, Y)) + +sliced = a["X", jnp.array([1, 2, 3])] + +# same as +a.array[jnp.array([1, 2, 3]), :] +``` + +Note that boolean arrays are not supported, as JAX does not support them in JIT-compiled code. You +can use [haliax.where][] for most of the same functionality, though. ### Shapes in JAX -Before we continue note on shapes in JAX. Most JAX code will be used inside `jit`, which means that the sizes of all arrays -must be determined at compile time (i.e. when JAX interprets your functions abstractly). This is a hard requirement in -XLA. +Before we continue, a note on shapes in JAX. Most JAX code will be used inside `jit`, which means that the sizes of all +arrays must be determined at compile time (i.e. when JAX interprets your functions abstractly). This is a hard +requirement in XLA. It might worked around one day, but it's the way things are for now. A consequence of this restriction is that certain indexing patterns aren't allowed in `jit`-ed JAX code: @@ -177,3 +207,60 @@ a[{"Y": ind1}] # error, "X" is not eliminated by the indexing operation a[{"X": ind2, "Y": ind1}] # ok, because X and Y are eliminated by the indexing operation ``` + +## Index Update + +JAX is a functional version of NumPy, so it doesn't directly support in-place updates. It does +however [provide an `at` syntax](https://jax.readthedocs.io/en/latest/_autosummary/jax.numpy.ndarray.at.html#jax.numpy.ndarray.at) +to express the same logic (and that will typically be optimized to be as efficient as an in-place update). Haliax +provides a similar syntax for updating arrays. + +```python +import haliax as hax + +X = hax.Axis("X", 10) +Y = hax.Axis("Y", 20) +Z = hax.Axis("Z", 30) + +a = hax.zeros((X, Y, Z)) + +a.at[{"X": 1, "Y": 2, "Z": 3}].set(1.0) # sets a[1, 2, 3] to 1.0 +a.at["X", 1].set(2.0) # sets a[1, :, :] to 2.0 + +a.at[{"X": 1, "Y": hax.ds(3, 5), "Z": 3}].add(1.0) # adds 1.0 to a[1, 3:8, 3] +``` + +Haliax supports the same `at` functionality as JAX, just with named arrays and additionally dslices. A summary of the +`at` syntax is as follows: + +| Alternate Syntax | Equivalent In-Place Operation | +|------------------------------|-------------------------------| +| `x = x.at[idx].set(y)` | `x[idx] = y` | +| `x = x.at[idx].add(y)` | `x[idx] += y` | +| `x = x.at[idx].multiply(y)` | `x[idx] *= y` | +| `x = x.at[idx].divide(y)` | `x[idx] /= y` | +| `x = x.at[idx].power(y)` | `x[idx] **= y` | +| `x = x.at[idx].min(y)` | `x[idx] = minimum(x[idx], y)` | +| `x = x.at[idx].max(y)` | `x[idx] = maximum(x[idx], y)` | +| `x = x.at[idx].apply(ufunc)` | `ufunc.at(x, idx)` | +| `x = x.at[idx].get()` | `x = x[idx]` | + +These methods also have options to control out-of-bounds behavior, as well as allowing you +to specify that the indices are sorted or unique. (If they are, XLA can sometimes optimize the +operation more effectively.) + +!!! note + + These named arguments are not passed to `at`, but to the next method in the chain. + +(This is copied from the JAX documentation:) + +* `mode`: One of `"promise_in_bounds"`, `"clip"`, `"drop"`, or `"fill"`. See [JAX's documentation](https://jax.readthedocs.io/en/latest/_autosummary/jax.lax.GatherScatterMode.html#jax.lax.GatherScatterMode) for more details. +* `indices_are_sorted`: If `True`, the implementation will assume that the indices passed to `at` are sorted in ascending order, which can lead to more efficient execution on some backends. +* `unique_indices`: If `True`, the implementation will assume that the indices passed to `at` are unique, which can result in more efficient execution on some backends. +* `fill_value`: Only applies to the `get()` method: the fill value to return for out-of-bounds slices when mode is 'fill'. Ignored otherwise. Defaults to NaN for inexact types, the largest negative value for signed types, the largest positive value for unsigned types, and True for booleans. + +!!! tip + + It's worth emphasizing that these functions are typically compiled to scatter-add and friends (as appropriate). + This is the preferred way to do scatter/gather operations in JAX, as well as in Haliax. diff --git a/docs/rearrange.md b/docs/rearrange.md index 80f8ec9..51dd205 100644 --- a/docs/rearrange.md +++ b/docs/rearrange.md @@ -54,6 +54,7 @@ If you're used to einops, the syntax should be familiar, with the main differenc and the additional "unordered" syntax for selecting dimensions by name. !!! warning + This syntax is fairly new. It is pretty well-tested, but it is possible that there are bugs. ### Examples diff --git a/src/haliax/core.py b/src/haliax/core.py index c61c572..a1c359d 100644 --- a/src/haliax/core.py +++ b/src/haliax/core.py @@ -9,7 +9,6 @@ from typing import Any, Callable, Dict, List, Mapping, Optional, Sequence, Tuple import jax import jax.numpy as jnp -import numpy import numpy as np import haliax @@ -18,22 +17,21 @@ from haliax.jax_utils import is_jax_array_like, is_pallas_dslice from haliax.util import ensure_tuple from ._src.util import index_where, py_slice, slice_t -from .axis import ( - Axis, - AxisSelection, - AxisSelector, - AxisSpec, - axis_name, - dslice, - eliminate_axes, - selects_axis, - union_axes, -) -from .types import DTypeLike, IntScalar, PrecisionLike, Scalar +from .axis import Axis, AxisSelection, AxisSelector, AxisSpec, axis_name, dslice, eliminate_axes, selects_axis +from .types import GatherScatterModeStr, IntScalar, PrecisionLike, Scalar NamedOrNumeric = Union[Scalar, "NamedArray"] -NamedIndex = Union[int, slice_t, "NamedArray", dslice] +NamedIndex = Union[int, slice_t, "NamedArray", dslice, list[int], jnp.ndarray] + +SliceSpec = Union[ + tuple[AxisSelector, NamedIndex], + tuple[AxisSelector, NamedIndex, AxisSelector, NamedIndex], + tuple[AxisSelector, NamedIndex, AxisSelector, NamedIndex, AxisSelector, NamedIndex], + tuple[AxisSelector | NamedOrNumeric, ...], + Mapping[AxisSelector, NamedIndex], +] + _ENABLE_SHAPE_CHECKS = True @@ -330,19 +328,47 @@ class NamedArray: def take(self, axis: AxisSelector, index: Union[int, "NamedArray"]) -> "NamedArray": return haliax.take(self, axis=axis, index=index) - @overload - def __getitem__(self, item: Tuple[AxisSelector, NamedIndex]) -> "NamedArray": - ... + @property + def at(self) -> "_NamedIndexUpdateHelper": + """ + Named analog of [jax's at method](https://jax.readthedocs.io/en/latest/_autosummary/jax.numpy.ndarray.at.html). - @overload - def __getitem__(self, item: Tuple[AxisSelector, NamedIndex, AxisSelector, NamedIndex]) -> "NamedArray": - ... + Docs from the JAX docs: - @overload - def __getitem__(self, item: Mapping[AxisSelector, NamedIndex]) -> "NamedArray": - ... + The at property provides a functionally pure equivalent of in-place array modifications. + + In particular: + + | Alternate syntax | Equivalent In-place expression | + |------------------|-------------------------------| + | `x = x.at[idx].set(y)` | `x[idx] = y` | + | `x[idx] = y` | `x = x.at[idx].set(y)` | + | `x = x.at[idx].add(y)` | `x[idx] += y`| + | `x = x.at[idx].multiply(y)` | `x[idx] *= y`| + | `x = x.at[idx].divide(y)` | `x[idx] /= y`| + | `x = x.at[idx].power(y)` | `x[idx] **= y`| + | `x = x.at[idx].min(y)` | `x[idx] = minimum(x[idx], y)`| + | `x = x.at[idx].max(y)` | `x[idx] = maximum(x[idx], y)`| + | `x = x.at[idx].apply(ufunc)` | `ufunc.at(x, idx)`| + + x = x.at[idx].get() + + + x = x[idx] + + None of the x.at expressions modify the original x; instead they return a modified copy of x. However, inside a jit() compiled function, expressions like x = x.at[idx].set(y) are guaranteed to be applied in-place. + + Unlike NumPy in-place operations such as x[idx] += y, if multiple indices refer to the same location, all updates will be applied (NumPy would only apply the last update, rather than applying all updates.) The order in which conflicting updates are applied is implementation-defined and may be nondeterministic (e.g., due to concurrency on some hardware platforms). + + By default, JAX assumes that all indices are in-bounds. Alternative out-of-bound index semantics can be specified via the mode parameter (see below). + + + Returns: - def __getitem__(self, idx) -> "NamedArray": + """ + return _NamedIndexUpdateHelper(self) + + def __getitem__(self, idx: SliceSpec) -> "NamedArray": """Syntactic sugar for [haliax.index][], which is the actual implementation. Supports indexing like: @@ -366,17 +392,8 @@ class NamedArray: This returns a NamedArray if any axes remain, or a scalar (0-dimensional) jnp.ndarray if all axes are indexed out. """ - if isinstance(idx, tuple): - if len(idx) == 1: - idx = idx[0] - else: - if len(idx) % 2 != 0: - raise ValueError( - "Must provide an even number of arguments to __getitem__ when using the shorthand syntax." - ) - idx = {idx[i]: idx[i + 1] for i in range(0, len(idx), 2)} - - return index(self, idx) + idx_dict = _convert_index_expr_to_dict(idx) + return index(self, idx_dict) # np.ndarray methods: def all(self, axis: Optional[AxisSelection] = None, *, where: Optional["NamedArray"] = None) -> "NamedArray": @@ -886,28 +903,60 @@ def index(array: NamedArray, slices: Mapping[AxisSelector, NamedIndex]) -> Named you might use `array[{"batch": slice(0, 10)}]` or `array["batch", 0:10]` to select the first 10 elements of the 'batch' axis. + See Also: + * [haliax.NamedArray.at][] for a functional equivalent of in-place array modifications. + Returns: NamedArray or jnp.ndarray: A NamedArray is returned if there are any axes remaining after selection, otherwise a scalar (0-dimensional) jnp.ndarray is returned if all axes are indexed out. """ # indices where we have array args - array_slice_indices = [] - dslice_indices = [] + new_axes, ordered_slices = _compute_new_axes_and_slices_for_index(array, slices) + sliced, ordered_slices = _handle_dynamic_slices(array.array, ordered_slices) + sliced = sliced[tuple(ordered_slices)] + + return haliax.named(sliced, new_axes) + + +def _compute_new_axes_and_slices_for_index( + array, slices +) -> tuple[AxisSpec, list[py_slice | dslice | jnp.ndarray | int | list[int]]]: ordered_slices: list = [py_slice(None, None, None)] * len(array.axes) # type: ignore kept_axes = [True] * len(array.axes) + array_slice_indices = [] + for axis, slice_ in slices.items(): axis_index = array._lookup_indices(axis) if axis_index is None: raise ValueError(f"axis {axis} not found in {array}") - ordered_slices[axis_index] = slice_ - - kept_axes[axis_index] = isinstance(slice_, py_slice) or isinstance(slice_, dslice) or is_pallas_dslice(slice_) - - if isinstance(slice_, NamedArray): + if isinstance(slice_, py_slice) or isinstance(slice_, dslice) or is_pallas_dslice(slice_): + ordered_slices[axis_index] = slice_ + kept_axes[axis_index] = True + elif isinstance(slice_, int): + ordered_slices[axis_index] = slice_ + kept_axes[axis_index] = False + elif isinstance(slice_, NamedArray): + ordered_slices[axis_index] = slice_ array_slice_indices.append(axis_index) - - if isinstance(slice_, dslice) or is_pallas_dslice(slice_): - dslice_indices.append(axis_index) + kept_axes[axis_index] = False + elif isinstance(slice_, list): + # we'll let JAX complain if this is wrong + ordered_slices[axis_index] = slice_ + elif isinstance(slice_, jnp.ndarray): + # we allow this if it's a 0-d or 1-d array + if slice_.ndim == 0: + ordered_slices[axis_index] = slice_ + elif slice_.ndim == 1: + # we allow this if it's a 1-d array, in which case we treat it as sugar for NamedArray(slice_, sliced-axis) + ordered_slices[axis_index] = haliax.named(slice_, axis_name(axis)) + kept_axes[axis_index] = False + array_slice_indices.append(axis_index) + else: + raise ValueError( + f"Only 0-d or 1-d unnamed arrays can be used for indexing. Got {slice_} for axis {axis}" + ) + else: + raise ValueError(f"Only NamedArrays can be used for advanced indexing. Got {slice_} for axis {axis}") # advanced indexing if len(array_slice_indices) > 0: @@ -958,23 +1007,39 @@ def index(array: NamedArray, slices: Mapping[AxisSelector, NamedIndex]) -> Named # the advanced indices are not contiguous, so we need to insert the new axes at the front new_axes = broadcasted_axes + tuple(ax for i, ax in enumerate(array.axes) if kept_axes[i]) else: - new_axes = tuple(axis.name for axis, keep in zip(array.axes, kept_axes) if keep) + new_axes = tuple(axis for axis, keep in zip(array.axes, kept_axes) if keep) - sliced = array.array + new_axes = tuple(axis_name(ax) for ax in new_axes) + return new_axes, ordered_slices - if len(dslice_indices) > 0: - # dynamic slice out the dslices - indices = [0] * len(array.axes) - lengths = [ax.size for ax in array.axes] - for i in dslice_indices: - indices[i] = ordered_slices[i].start - lengths[i] = ordered_slices[i].size - sliced = jax.lax.dynamic_slice(sliced, indices, lengths) - for i in dslice_indices: - ordered_slices[i] = py_slice(None, None, None) - sliced = sliced[tuple(ordered_slices)] - return haliax.named(sliced, new_axes) +def _handle_dynamic_slices(array: jnp.ndarray, slices): + """ + Helper function to handle dynamic slices in the array. These have to be handled with jax.lax.dynamic_slice, + which is for when the start index is not known at compile time. (Sizes must always be known at compile time.) + + Notes: + **MUTATES `slices` IN PLACE** + + Returns: + array.array: the sliced array + + """ + indices_for_dslice = [0] * array.ndim + lengths_for_dslice = list(array.shape) + dslice_indices = [] + need_to_slice = False + for axis_index, slice_ in enumerate(slices): + if isinstance(slice_, dslice) or is_pallas_dslice(slice_): + dslice_indices.append(axis_index) + indices_for_dslice[axis_index] = slice_.start + lengths_for_dslice[axis_index] = slice_.size + need_to_slice = True + if need_to_slice: + array = jax.lax.dynamic_slice(array, indices_for_dslice, lengths_for_dslice) + for i in dslice_indices: + slices[i] = py_slice(None, None, None) + return array, slices def split(a: NamedArray, axis: AxisSelector, new_axes: Sequence[Axis]) -> Sequence[NamedArray]: @@ -1445,6 +1510,208 @@ def flatten_all_axes_but( return result, unflatten +class _NamedIndexUpdateHelper: + def __init__(self, array: NamedArray): + self.array = array + + def __getitem__(self, slices: SliceSpec) -> "_NamedIndexUpdateRef": + return _NamedIndexUpdateRef(self.array, _convert_index_expr_to_dict(slices)) + + +class _NamedIndexUpdateRef: + def __init__(self, array: NamedArray, slices: SliceSpec): + self._array = array + self._slices = slices + + def get( + self, + *, + indices_are_sorted: bool = False, + unique_indices: bool = False, + mode: Optional[GatherScatterModeStr] = None, + fill_value: Optional[Scalar] = None, + ) -> NamedArray: + slices, sliced_axes = _raw_indices_for_at(self._array, self._slices) + new_array = self._array.array.at[tuple(slices)].get( + indices_are_sorted=indices_are_sorted, unique_indices=unique_indices, mode=mode, fill_value=fill_value + ) + return NamedArray(new_array, sliced_axes) + + def set( + self, + update: NamedOrNumeric, + *, + indices_are_sorted: bool = False, + unique_indices: bool = False, + mode: Optional[GatherScatterModeStr] = None, + ) -> NamedArray: + slices, sliced_axes = _raw_indices_for_at(self._array, self._slices) + update = haliax.broadcast_to(update, sliced_axes, enforce_no_extra_axes=True) + new_array = self._array.array.at[tuple(slices)].set( + update.array, indices_are_sorted=indices_are_sorted, unique_indices=unique_indices, mode=mode + ) + return NamedArray(new_array, self._array.axes) + + def add( + self, + update: NamedOrNumeric, + *, + indices_are_sorted: bool = False, + unique_indices: bool = False, + mode: Optional[GatherScatterModeStr] = None, + ) -> NamedArray: + slices, sliced_axes = _raw_indices_for_at(self._array, self._slices) + update = haliax.broadcast_to(update, sliced_axes, enforce_no_extra_axes=True) + new_array = self._array.array.at[tuple(slices)].add( + update.array, indices_are_sorted=indices_are_sorted, unique_indices=unique_indices, mode=mode + ) + return NamedArray(new_array, self._array.axes) + + def multiply( + self, + update: NamedOrNumeric, + *, + indices_are_sorted: bool = False, + unique_indices: bool = False, + mode: Optional[GatherScatterModeStr] = None, + ) -> NamedArray: + slices, sliced_axes = _raw_indices_for_at(self._array, self._slices) + update = haliax.broadcast_to(update, sliced_axes, enforce_no_extra_axes=True) + new_array = self._array.array.at[tuple(slices)].multiply( + update.array, indices_are_sorted=indices_are_sorted, unique_indices=unique_indices, mode=mode + ) + return NamedArray(new_array, self._array.axes) + + def divide( + self, + update: NamedOrNumeric, + *, + indices_are_sorted: bool = False, + unique_indices: bool = False, + mode: Optional[GatherScatterModeStr] = None, + ) -> NamedArray: + slices, sliced_axes = _raw_indices_for_at(self._array, self._slices) + update = haliax.broadcast_to(update, sliced_axes, enforce_no_extra_axes=True) + new_array = self._array.array.at[tuple(slices)].divide( + update.array, indices_are_sorted=indices_are_sorted, unique_indices=unique_indices, mode=mode + ) + return NamedArray(new_array, self._array.axes) + + def max( + self, + update: NamedOrNumeric, + *, + indices_are_sorted: bool = False, + unique_indices: bool = False, + mode: Optional[GatherScatterModeStr] = None, + ) -> NamedArray: + slices, sliced_axes = _raw_indices_for_at(self._array, self._slices) + update = haliax.broadcast_to(update, sliced_axes, enforce_no_extra_axes=True) + new_array = self._array.array.at[tuple(slices)].max( + update.array, indices_are_sorted=indices_are_sorted, unique_indices=unique_indices, mode=mode + ) + return NamedArray(new_array, self._array.axes) + + def min( + self, + update: NamedOrNumeric, + *, + indices_are_sorted: bool = False, + unique_indices: bool = False, + mode: Optional[GatherScatterModeStr] = None, + ) -> NamedArray: + slices, sliced_axes = _raw_indices_for_at(self._array, self._slices) + update = haliax.broadcast_to(update, sliced_axes, enforce_no_extra_axes=True) + new_array = self._array.array.at[tuple(slices)].min( + update.array, indices_are_sorted=indices_are_sorted, unique_indices=unique_indices, mode=mode + ) + return NamedArray(new_array, self._array.axes) + + def power( + self, + update: NamedOrNumeric, + *, + indices_are_sorted: bool = False, + unique_indices: bool = False, + mode: Optional[GatherScatterModeStr] = None, + ) -> NamedArray: + slices, sliced_axes = _raw_indices_for_at(self._array, self._slices) + update = haliax.broadcast_to(update, sliced_axes, enforce_no_extra_axes=True) + new_array = self._array.array.at[tuple(slices)].power( + update.array, indices_are_sorted=indices_are_sorted, unique_indices=unique_indices, mode=mode + ) + return NamedArray(new_array, self._array.axes) + + def apply( + self, + func, + *, + indices_are_sorted: bool = False, + unique_indices: bool = False, + mode: Optional[GatherScatterModeStr] = None, + ) -> NamedArray: + # It's not really documented, but func can be any callable that takes a scalar array and returns a scalar array + slices, sliced_axes = _raw_indices_for_at(self._array, self._slices) + new_array = self._array.array.at[tuple(slices)].apply( + func, indices_are_sorted=indices_are_sorted, unique_indices=unique_indices, mode=mode + ) + return NamedArray(new_array, self._array.axes) + + +def _raw_indices_for_at(array, indexes): + sliced_axes, ordered_slices = _compute_new_axes_and_slices_for_index(array, indexes) + del sliced_axes + # this isn't the fastest (it does the _compute_new_axes_and_slices_for_index twice) + # but it's easy + _sliced = index(array, indexes) + # we have to handle dslices differently than for normal indexing, because we can't use + # extra dynamic_slices... + # we'd like to just replace these with iota, but we have account for broadcasting semantics + # for the other arrays + dslice_sizes = tuple(x.size for x in ordered_slices if isinstance(x, dslice) or is_pallas_dslice(x)) # type: ignore + current_array_slice_shape = next((x.shape for x in ordered_slices if is_jax_array_like(x)), None) # type: ignore + dims_to_expand = list(range(len(dslice_sizes))) + if current_array_slice_shape is not None: + iota_shape = dslice_sizes + current_array_slice_shape + else: + iota_shape = dslice_sizes + + def iota_for_dslice(dslice, cur_dynamic_slice): + return jax.lax.broadcasted_iota(int, iota_shape, cur_dynamic_slice) + dslice.start + + if len(dslice_sizes) > 0: + cur_dynamic_slice = 0 + for i in range(len(ordered_slices)): + if isinstance(ordered_slices[i], dslice) or is_pallas_dslice(ordered_slices[i]): + ordered_slices[i] = iota_for_dslice(ordered_slices[i], cur_dynamic_slice) + cur_dynamic_slice += 1 + elif is_jax_array_like(ordered_slices[i]): + # prepend array slices with one 1 for each dynamic slice + ordered_slices[i] = jnp.expand_dims(ordered_slices[i], axis=dims_to_expand) + + assert cur_dynamic_slice == len(dslice_sizes) + + # ok the ordered slices are now correct + return ordered_slices, _sliced.axes + + +def _convert_index_expr_to_dict(idx) -> dict[AxisSelector, NamedIndex]: + if isinstance(idx, tuple): + if len(idx) == 1: + idx = idx[0] + else: + if len(idx) % 2 != 0: + raise ValueError( + "Must provide an even number of arguments to __getitem__ when using the shorthand syntax." + ) + idx = {idx[i]: idx[i + 1] for i in range(0, len(idx), 2)} + elif isinstance(idx, dict): + pass + else: + raise ValueError(f"Invalid index type {type(idx)}") + return idx + + __all__ = [ "NamedArray", "named", diff --git a/src/haliax/types.py b/src/haliax/types.py index f4b0ea3..2d326ae 100644 --- a/src/haliax/types.py +++ b/src/haliax/types.py @@ -1,4 +1,4 @@ -from typing import Any, Protocol, Tuple, TypeAlias, Union +from typing import Any, Literal, Protocol, Tuple, TypeAlias, Union import jax.numpy as jnp import numpy as np @@ -28,3 +28,5 @@ Scalar = Union[float, int, jnp.ndarray] # ndarray b/c array(1) is a scalar IntScalar = Union[int, jnp.ndarray] PrecisionLike = Union[None, str, Precision, Tuple[str, str], Tuple[Precision, Precision]] + +GatherScatterModeStr = Literal["promise_in_bounds", "clip", "drop", "fill"] diff --git a/tests/core_test.py b/tests/core_test.py index e20bb08..4e6dec9 100644 --- a/tests/core_test.py +++ b/tests/core_test.py @@ -649,6 +649,34 @@ def test_slice_nd_array_present_dims(): assert jnp.all(jnp.equal(named1[{"H": index2}].array, named1.array[index2.array, :, :])) +def test_slice_nd_array_unnamed_slice(): + # tests slicing with arrays that are already present in the named array, which is sometimes ok + H = Axis("H", 10) + W = Axis("W", 20) + D = Axis("D", 30) + + named1 = hax.random.uniform(PRNGKey(0), (H, W, D)) + + index1 = jax.random.randint(PRNGKey(1), (4,), 0, H.size) + assert jnp.all(jnp.equal(named1[{"H": index1}].array, named1.array[index1, :, :])) + + # hidden behavior: if we also pass in an H index to e.g. D, it is zipped together + index2 = hax.random.randint(PRNGKey(2), Axis("H", 4), 0, D.size) + assert jnp.all(jnp.equal(named1[{"H": index1, "D": index2}].array, named1.array[index1, :, index2.array])) + + # this is different though: + index2r = index2.array + assert jnp.all( + jnp.equal( + named1[{"H": index1, "D": index2r}].array, named1.array[index1.reshape(1, -1), :, index2r.reshape(-1, 1)] + ) + ) + assert named1[{"H": index1, "D": index2r}].shape != named1[{"H": index1, "D": index2}].shape + + index1 = list(index1) + assert jnp.all(jnp.equal(named1[{"H": index1}].array, named1.array[index1, :, :])) + + def test_full_indexing_returns_named_array(): H = Axis("H", 10) W = Axis("W", 20) @@ -847,3 +875,82 @@ def test_named_arrays_work_in_eqxi_while_loop(): grad_fun = eqx.filter_value_and_grad(loss_fun) grad_fun(named1) + + +def test_at_for_in_placeish(): + H = Axis("H", 10) + W = Axis("W", 20) + + named1 = hax.random.uniform(PRNGKey(0), (H, W)) + + named1_at = named1.at[H, 0].set(0) + + assert jnp.all(jnp.equal(named1_at[H, 0].array, 0)) + assert jnp.all(named1_at[H, 1:].array == named1[H, 1:].array) + + # test add, multiply, power, etc. + named1_at = named1.at[H, 0].add(1) + assert jnp.all(named1_at.array == named1.array.at[0].add(1)) + + named1_at = named1.at[H, 0].multiply(2) + assert jnp.all(named1_at.array == named1.array.at[0].multiply(2)) + + named1_at = named1.at[H, 0].power(2) + assert jnp.all(named1_at.array == named1.array.at[0].power(2)) + + named1_at = named1.at[H, 0].divide(2) + assert jnp.all(named1_at.array == named1.array.at[0].divide(2)) + + named1_at = named1.at[H, 0].apply(hax.square) + assert jnp.all(named1_at.array == named1.array.at[0].apply(jnp.square)) + + named1_at = named1.at[H, 0].max(0.5) + assert jnp.all(named1_at.array == named1.array.at[0].max(0.5)) + + named1_at = named1.at[H, 0].min(0.5) + assert jnp.all(named1_at.array == named1.array.at[0].min(0.5)) + + +def test_at_with_fancy_indexing(): + H = Axis("H", 10) + W = Axis("W", 20) + I0 = Axis("I0", 5) + I1 = Axis("I1", 5) + + named1 = hax.random.uniform(PRNGKey(0), (H, W)) + ind1 = hax.random.randint(PRNGKey(0), (I0,), 0, H.size) + ind2 = hax.random.randint(PRNGKey(0), (I1,), 0, W.size) + + named1_at = named1.at[H, ind1].set(0) + assert jnp.all(named1_at.array == named1.array.at[ind1.array].set(0)) + + named1_at = named1.at[H, ind1].add(1, mode="clip") + assert jnp.all(named1_at.array == named1.array.at[ind1.array].add(1, mode="clip")) + + named1_at = named1.at[H, ind1, W, ind2].set(0) + assert jnp.all(named1_at.array == named1.array.at[ind1.array.reshape(-1, 1), ind2.array.reshape(1, -1)].set(0)) + + # dslices + from haliax import ds + + named1_at = named1.at[H, ds(3, 5)].set(0) + assert jnp.all(named1_at.array == named1.array.at[3:8].set(0)) + + named1_at = named1.at[H, ds(3, 5), W, ind2].power(2) + assert jnp.all(named1_at.array == named1.array.at[3:8, ind2.array].power(2)) + + +def test_slice_dslice_and_array(): + H = Axis("H", 10) + W = Axis("W", 20) + I0 = Axis("I0", 5) + + named1 = hax.random.uniform(PRNGKey(0), (H, W)) + ind2 = hax.random.randint(PRNGKey(0), (I0,), 0, W.size) + + from haliax import ds + + named1.array.at[3:8, ind2.array].add(jnp.full((5, 5), 2)) + + named1_at = named1.at[H, ds(3, 5), W, ind2].add(2) + assert jnp.all(named1_at.array == named1.array.at[3:8, ind2.array].add(2)) commit 1006f84b11bf079ac3d217a37a46687ddc8fb842 Date: 2024-04-16T16:34:48-07:00 fix hax.where in the presence of scalars (#86) diff --git a/src/haliax/ops.py b/src/haliax/ops.py index da92654..fb23f8d 100644 --- a/src/haliax/ops.py +++ b/src/haliax/ops.py @@ -5,7 +5,7 @@ import jax import jax.numpy as jnp from .axis import Axis, AxisSelector -from .core import NamedArray, NamedOrNumeric, broadcast_arrays, broadcast_arrays_and_return_axes +from .core import NamedArray, NamedOrNumeric, broadcast_arrays, broadcast_arrays_and_return_axes, named from .jax_utils import is_scalarish @@ -70,9 +70,21 @@ def where( for idx in jnp.where(condition.array, size=new_axis.size, fill_value=fill_value) ) + # if x or y is a NamedArray, the other must be as well. wrap as needed for scalars + if is_scalarish(condition): - if x is None: + if x is None or y is None: raise ValueError("Must specify x and y when condition is a scalar") + + if isinstance(x, NamedArray) and not isinstance(y, NamedArray): + if not is_scalarish(y): + raise ValueError("y must be a NamedArray or scalar if x is a NamedArray") + y = named(y, ()) + elif isinstance(y, NamedArray) and not isinstance(x, NamedArray): + if not is_scalarish(x): + raise ValueError("x must be a NamedArray or scalar if y is a NamedArray") + x = named(x, ()) + x, y = broadcast_arrays(x, y) return jax.lax.cond(condition, lambda _: x, lambda _: y, None) condition, x, y = broadcast_arrays(condition, x, y) # type: ignore diff --git a/tests/test_ops.py b/tests/test_ops.py index dd89736..0a1e28d 100644 --- a/tests/test_ops.py +++ b/tests/test_ops.py @@ -1,3 +1,5 @@ +from typing import Callable + import jax.numpy as jnp import pytest from jax.random import PRNGKey @@ -105,19 +107,27 @@ def test_add_no_overlap(): # TODO: tests for other ops: -def test_where(): +@pytest.mark.parametrize("use_jit", [False, True]) +def test_where(use_jit): Height = Axis("Height", 10) Width = Axis("Width", 3) Depth = Axis("Depth", 4) + hax_where: Callable = hax.where + if use_jit: + hax_where = hax.named_jit(hax_where) + named1 = hax.random.uniform(PRNGKey(0), (Height, Width, Depth)) named2 = hax.random.uniform(PRNGKey(1), (Height, Width, Depth)) - named3 = hax.where(named1 > named2, named1, named2) + hax_where(0.0, named1, 0.0) + + named3 = hax_where(named1 > named2, named1, named2) + assert jnp.all(jnp.isclose(named3.array, jnp.where(named1.array > named2.array, named1.array, named2.array))) named2_reorder = named2.rearrange((Width, Height, Depth)) - named4 = hax.where(named1 > named2_reorder, named1, named2_reorder) + named4 = hax_where(named1 > named2_reorder, named1, named2_reorder) named4 = named4.rearrange((Height, Width, Depth)) assert jnp.all(jnp.isclose(named4.array, jnp.where(named1.array > named2.array, named1.array, named2.array))) @@ -125,7 +135,7 @@ def test_where(): named5 = hax.random.uniform(PRNGKey(1), (Height, Width)) named6 = hax.random.uniform(PRNGKey(2), Width) - named7 = hax.where(named5 > named6, named5, named6) + named7 = hax_where(named5 > named6, named5, named6) named7 = named7.rearrange((Height, Width)) assert jnp.all(jnp.isclose(named7.array, jnp.where(named5.array > named6.array, named5.array, named6.array))) @@ -134,12 +144,12 @@ def test_where(): named6 = hax.random.uniform(PRNGKey(2), (Width, Depth)) with pytest.raises(ValueError): - _ = hax.where(named5 > named6, named5, named6) + _ = hax_where(named5 > named6, named5, named6) # now single argument mode Volume = hax.Axis("Volume", Height.size * Width.size * Depth.size) named7 = hax.random.uniform(PRNGKey(0), (Height, Width, Depth)) - named8, named9, named10 = hax.where(named7 > 0.5, fill_value=-1, new_axis=Volume) + named8, named9, named10 = hax_where(named7 > 0.5, fill_value=-1, new_axis=Volume) assert jnp.all((named7[{"Height": named8, "Width": named9, "Depth": named10}] > 0.5).array) commit d4098b8e7404a06ad4a09a6adeaa0cad5b765f06 Date: 2024-04-18T12:46:05-07:00 update indexing docs diff --git a/docs/indexing.md b/docs/indexing.md index 60a7488..d9669da 100644 --- a/docs/indexing.md +++ b/docs/indexing.md @@ -153,9 +153,11 @@ It's not a huge improvement, but it's a bit more convenient. ## Advanced Indexing NumPy's [Advanced Indexing](https://numpy.org/doc/stable/user/basics.indexing.html#advanced-indexing) is supported, though we use named arrays for the indices instead of normal arrays. -In NumPy, the indexed arrays much be broadcastable to the same shape.Advanced indexing in Haliax is similar, except that -they follow Haliax's broadcasting rules, meaning that the axis names determine broadcasting.Axes with the same name must -have the same size. +(Though, as noted above, you can use 1-D JAX arrays of integers as well.) +In NumPy, the indexed arrays must be broadcastable to the same shape. Advanced indexing in Haliax is similar, +except that it follows Haliax's broadcasting rules, meaning that shared names are broadcasted together, +while non-shared names are treated as separate axes and are cross-producted. +In particular, axes with the same name must have the same size. ```python import haliax as hax commit fcd51ea185d3a37be7887b413b971493b45717a4 Date: 2024-05-13T12:57:33-07:00 Add replica axes (#87) diff --git a/src/haliax/partitioning.py b/src/haliax/partitioning.py index ba0fff9..4b9e99c 100644 --- a/src/haliax/partitioning.py +++ b/src/haliax/partitioning.py @@ -38,6 +38,7 @@ class ResourceAxis(StringHolderEnum): MODEL = "model" DATA = "data" + REPLICA = "replica" class _ResourceMappingHolder: commit aa1ab879ab5c233609b9c218c5a0cc32cce6705c Date: 2024-05-15T20:40:30-07:00 Fix pspec method for levanter (#88) diff --git a/src/haliax/partitioning.py b/src/haliax/partitioning.py index 4b9e99c..0770414 100644 --- a/src/haliax/partitioning.py +++ b/src/haliax/partitioning.py @@ -3,6 +3,7 @@ import functools import threading import typing import warnings +from itertools import chain from math import prod from typing import Callable, ContextManager, Mapping, Optional, ParamSpec, Sequence, TypeVar, Union @@ -585,7 +586,17 @@ def sharding_for_axis( def pspec_for_axis(axis: AxisSelection, mapping: Optional[ResourceMapping] = None) -> PartitionSpec: """Get the PartitionSpec for a single axis""" axis = ensure_tuple(axis) - return PartitionSpec(*(physical_axis_name(a, mapping) for a in axis)) + phys_axes = [] + for a in axis: + pa = physical_axis_name(a, mapping) + if pa is None or isinstance(pa, str): + phys_axes.append(pa) + else: + # I have no way to resolve the mypy check :) + for i in pa: + phys_axes.append(i) + + return PartitionSpec(*phys_axes) def round_axis_for_partitioning(axis: Axis, mapping: Optional[ResourceMapping] = None) -> Axis: commit 2acd71430787478124644344a4c68953bba5ddd2 Date: 2024-05-15T20:42:37-07:00 fix README diff --git a/README.md b/README.md index 9a700f9..a91db2e 100644 --- a/README.md +++ b/README.md @@ -35,8 +35,6 @@ please see the [Haliax tutorial](https://colab.research.google.com/drive/1TiTcQQ (We use the excellent [Equinox](https://github.com/patrick-kidger/equinox) library for its module system and tree transformations.) ```python -import haliax.nn.normalization -import haliax.nn.activations import equinox as eqx import jax import jax.numpy as jnp @@ -58,7 +56,7 @@ def attention_scores(Key, KPos, query, key, mask): scores -= 1E9 * (1.0 - mask) # convert to probabilities - scores = haliax.nn.normalization.softmax(scores, KPos) + scores = haliax.nn.softmax(scores, KPos) return scores commit be15ceb0cd59cc16cbbd66c816423dc3d28337dc Date: 2024-05-17T15:22:27-07:00 revert previous PR (#89) diff --git a/src/haliax/partitioning.py b/src/haliax/partitioning.py index 0770414..4b9e99c 100644 --- a/src/haliax/partitioning.py +++ b/src/haliax/partitioning.py @@ -3,7 +3,6 @@ import functools import threading import typing import warnings -from itertools import chain from math import prod from typing import Callable, ContextManager, Mapping, Optional, ParamSpec, Sequence, TypeVar, Union @@ -586,17 +585,7 @@ def sharding_for_axis( def pspec_for_axis(axis: AxisSelection, mapping: Optional[ResourceMapping] = None) -> PartitionSpec: """Get the PartitionSpec for a single axis""" axis = ensure_tuple(axis) - phys_axes = [] - for a in axis: - pa = physical_axis_name(a, mapping) - if pa is None or isinstance(pa, str): - phys_axes.append(pa) - else: - # I have no way to resolve the mypy check :) - for i in pa: - phys_axes.append(i) - - return PartitionSpec(*phys_axes) + return PartitionSpec(*(physical_axis_name(a, mapping) for a in axis)) def round_axis_for_partitioning(axis: Axis, mapping: Optional[ResourceMapping] = None) -> Axis: commit 3d83ed20ff0167516133afcf0d2778fe0021437a Date: 2024-06-03T18:28:52-04:00 Expose the filter_checkpoint helper: it's useful for custom training loops. (#91) diff --git a/src/haliax/__init__.py b/src/haliax/__init__.py index 6645724..f7898f4 100644 --- a/src/haliax/__init__.py +++ b/src/haliax/__init__.py @@ -55,6 +55,7 @@ from .core import ( unflatten_axis, updated_slice, ) +from .jax_utils import filter_checkpoint from .hof import fold, map, scan, vmap from .ops import clip, isclose, pad_left, trace, tril, triu, where from .partitioning import auto_sharded, axis_mapping, fsdp, named_jit, shard, shard_with_axis_mapping commit a32db8a98a8f5e313f8ef23167d534e8d522e6ea Date: 2024-06-07T20:23:39-07:00 Use sqrt(fan_in) as default init and truncated_normal (#93) diff --git a/.github/workflows/run_tests.yaml b/.github/workflows/run_tests.yaml index a6472f2..fbfccde 100644 --- a/.github/workflows/run_tests.yaml +++ b/.github/workflows/run_tests.yaml @@ -21,13 +21,7 @@ jobs: python -m pip install --upgrade pip pip install flake8 pytest pip install --upgrade "jax[cpu]==0.4.25" "jaxlib[cpu]==0.4.25" - pip install . -# - name: Lint with flake8 -# run: | -# # stop the build if there are Python syntax errors or undefined names -# flake8 . --count --select=E9,F63,F7,F82 --show-source --statistics -# # exit-zero treats all errors as warnings. The GitHub editor is 127 chars wide -# flake8 . --count --exit-zero --max-complexity=50 --max-line-length=127 --statistics + pip install .[dev] - name: Test with pytest run: | XLA_FLAGS=--xla_force_host_platform_device_count=8 PYTHONPATH=tests:src:. pytest tests diff --git a/pyproject.toml b/pyproject.toml index d1420b0..4b1d0f7 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -36,8 +36,10 @@ dev=["pytest >= 7.4.0", "mypy >= 0.910", "mkdocs >= 1.4.3", "mkdocs-material >= "pymdown-extensions", "pygments", "pymdown-extensions", + "chex>=0.1.86" ] + [tool.hatch.version] path = "src/haliax/__about__.py" diff --git a/src/haliax/__init__.py b/src/haliax/__init__.py index f7898f4..2ad1750 100644 --- a/src/haliax/__init__.py +++ b/src/haliax/__init__.py @@ -26,6 +26,7 @@ from .axis import ( AxisSelector, AxisSpec, axis_name, + axis_size, concat_axes, dblock, ds, diff --git a/src/haliax/axis.py b/src/haliax/axis.py index 736c8aa..0c80228 100644 --- a/src/haliax/axis.py +++ b/src/haliax/axis.py @@ -1,5 +1,6 @@ import typing from dataclasses import dataclass +from math import prod from types import EllipsisType from typing import Dict, List, Mapping, Optional, Sequence, Tuple, Union, overload @@ -354,6 +355,17 @@ def axis_name(ax: AxisSelection) -> Union[str, Tuple[str, ...]]: return tuple(_ax_name(x) for x in ax) +def axis_size(ax: AxisSpec) -> int: + """ + Returns the size of the axis or the product of the sizes of the axes in the axis spec + """ + + if isinstance(ax, Axis): + return ax.size + else: + return prod(axis.size for axis in ensure_tuple(ax)) # type: ignore + + class dslice(eqx.Module): """ Dynamic slice, comprising a (start, length) pair. Also aliased as ds. @@ -524,6 +536,7 @@ __all__ = [ "PartialShapeDict", "ShapeDict", "axis_name", + "axis_size", "concat_axes", "union_axes", "axis_spec_to_shape_dict", diff --git a/src/haliax/core.py b/src/haliax/core.py index a1c359d..57550ed 100644 --- a/src/haliax/core.py +++ b/src/haliax/core.py @@ -441,7 +441,11 @@ class NamedArray: @typing.overload def dot( - self, *args, axis: Optional[AxisSelection], precision: PrecisionLike = None, dot_general=jax.lax.dot_general + self, + *args: "NamedArray", + axis: Optional[AxisSelection], + precision: PrecisionLike = None, + dot_general=jax.lax.dot_general, ) -> "NamedArray": ... @@ -1143,7 +1147,7 @@ def flatten_axes(array: NamedArray, old_axes: AxisSelection, new_axis: AxisSelec """ old_axes = ensure_tuple(old_axes) old_axes = array.resolve_axis(old_axes) - total_axis_size = prod(array.axis_size(ax) for ax in old_axes) + total_axis_size = haliax.axis_size(old_axes) if isinstance(new_axis, Axis): if new_axis.size != total_axis_size: diff --git a/src/haliax/nn/embedding.py b/src/haliax/nn/embedding.py index 39169d3..54a121f 100644 --- a/src/haliax/nn/embedding.py +++ b/src/haliax/nn/embedding.py @@ -1,4 +1,6 @@ import dataclasses +import math +import warnings from typing import Optional import equinox as eqx @@ -21,9 +23,14 @@ class Embedding(eqx.Module): Embed: AxisSpec = eqx.static_field() @staticmethod - def init(Vocab: Axis, Embed: AxisSpec, initializer_range: float = 0.02, *, key): + def init(Vocab: Axis, Embed: AxisSpec, *, init_scale: float = 1, key, initializer_range: Optional[float] = None): + if initializer_range is not None: + warnings.warn("initializer_range is deprecated. Use init_std instead.", DeprecationWarning) + init_scale = initializer_range + all_axes = (Vocab,) + ensure_tuple(Embed) - weight = hax.random.normal(key, all_axes) * initializer_range + output_size = hax.axis_size(Embed) + weight = hax.random.truncated_normal(key, all_axes, -3, 3) * (init_scale / math.sqrt(output_size)) return Embedding(weight=weight, Vocab=Vocab, Embed=Embed) def __call__(self, input_ids, *, key: Optional[PRNGKeyArray] = None): diff --git a/src/haliax/nn/linear.py b/src/haliax/nn/linear.py index fccbfb7..ffba87c 100644 --- a/src/haliax/nn/linear.py +++ b/src/haliax/nn/linear.py @@ -1,3 +1,4 @@ +import math from typing import Callable, Optional import equinox as eqx @@ -25,7 +26,14 @@ class Linear(eqx.Module): @staticmethod def init( - In: AxisSpec, Out: AxisSpec, *, key, use_bias=True, out_first: bool = False, dot_general=None + In: AxisSpec, + Out: AxisSpec, + *, + key, + use_bias=True, + out_first: bool = False, + dot_general=None, + init_scale: float = 1.0, ) -> "Linear": """ @@ -36,9 +44,11 @@ class Linear(eqx.Module): use_bias: bool: Whether to use a bias term out_first: bool: Whether to put output axes first in the weight matrix. out_first is how PyTorch does it. dot_general: Callable: The dot_general function to use. Defaults to jax.lax.dot_general. For fp8 or int8 + init_scale: float: The scale to use for initialization. We scale init by 1/sqrt(Input.size)*init_scale """ joint_spec = hax.concat_axis_specs(Out, In) if out_first else hax.concat_axis_specs(In, Out) - weight = hax.random.normal(key, joint_spec) * 0.02 + input_size = hax.axis_size(In) + weight = hax.random.truncated_normal(key, joint_spec, -3, 3) * (init_scale / math.sqrt(input_size)) bias = hax.zeros(Out) if use_bias else None if dot_general is None: diff --git a/src/haliax/nn/mlp.py b/src/haliax/nn/mlp.py index 9ce7b40..587f7b0 100644 --- a/src/haliax/nn/mlp.py +++ b/src/haliax/nn/mlp.py @@ -48,6 +48,7 @@ class MLP(eqx.Module): use_final_bias: bool = True, key: PRNGKeyArray, dot_general: Optional[DotGeneralOp] = None, + init_scale: float = 1.0, ): Width = _get_width(width) Width2 = Width.alias(Width.name + "2") @@ -58,18 +59,34 @@ class MLP(eqx.Module): if depth == 0: # special case: no hidden layers - layers.append(Linear.init(Input, Output, use_bias=use_final_bias, key=keys[0], dot_general=dot_general)) + layers.append( + Linear.init( + Input, Output, use_bias=use_final_bias, key=keys[0], dot_general=dot_general, init_scale=init_scale + ) + ) else: # first hidden layer - layers.append(Linear.init(Input, Width, use_bias=use_bias, key=keys[0], dot_general=dot_general)) + layers.append( + Linear.init( + Input, Width, use_bias=use_bias, key=keys[0], dot_general=dot_general, init_scale=init_scale + ) + ) # middle hidden layers cur = Width next = Width2 for i in range(1, depth): - layers.append(Linear.init(cur, next, use_bias=use_bias, key=keys[i], dot_general=dot_general)) + layers.append( + Linear.init( + cur, next, use_bias=use_bias, key=keys[i], dot_general=dot_general, init_scale=init_scale + ) + ) cur, next = next, cur # final hidden layer - layers.append(Linear.init(cur, Output, use_bias=use_final_bias, key=keys[-1], dot_general=dot_general)) + layers.append( + Linear.init( + cur, Output, use_bias=use_final_bias, key=keys[-1], dot_general=dot_general, init_scale=init_scale + ) + ) return MLP( layers=tuple(layers), diff --git a/tests/test_fp8.py b/tests/test_fp8.py index 1721009..3c47f60 100644 --- a/tests/test_fp8.py +++ b/tests/test_fp8.py @@ -1,8 +1,10 @@ +import chex import equinox as eqx import jax.numpy as jnp import jax.random as jrandom import jax.tree_util import numpy as np +from chex import assert_trees_all_close import haliax as hax from haliax._src.fp8 import compute_scale @@ -19,18 +21,20 @@ from haliax.quantization import ( def test_fp8_is_reasonable(): In = hax.Axis("In", 8) Out = hax.Axis("Out", 8) - linear = Linear.init(In, Out, key=jrandom.PRNGKey(0)) + linear = Linear.init(In, Out, key=jrandom.PRNGKey(0), init_scale=0.1) - fp8_linear = Linear.init(In, Out, key=jrandom.PRNGKey(0), dot_general=hax.quantization.Fp8DotGeneralOp.init()) + fp8_linear = Linear.init( + In, Out, key=jrandom.PRNGKey(0), dot_general=hax.quantization.Fp8DotGeneralOp.init(), init_scale=0.1 + ) - input = hax.random.normal(jrandom.PRNGKey(0), In) * 10 + input = hax.random.normal(jrandom.PRNGKey(3), In) output = linear(input) fp8_output = fp8_linear(input) assert output.shape == fp8_output.shape assert output.dtype == fp8_output.dtype - assert jnp.allclose(output.array, fp8_output.array, atol=1e-1, rtol=1e-1) + assert_trees_all_close(output.array, fp8_output.array, atol=1e-2, rtol=5e-2) # https://github.com/google/flax/blob/6f2b08e024c2fd2f8cec42a6c82408cb35412319/tests/linen/linen_test.py#L1222 @@ -130,9 +134,9 @@ def test_fp_loop(): def test_layer_splicing(): key, init_key, random_key = jrandom.split(jrandom.PRNGKey(seed=123), 3) Input = hax.Axis("Input", 16) - Hidden = hax.Axis("Hidden", 16) + Hidden = hax.Axis("Hidden", 64) Output = hax.Axis("Output", 32) - mlp = hax.nn.MLP.init(Input, Output, Hidden, 3, key=init_key) + mlp = hax.nn.MLP.init(Input, Output, Hidden, 3, key=init_key, init_scale=0.1) mlp_q = fp8_linear_layers(mlp, Fp8Config()) for layer in mlp_q.layers: @@ -141,7 +145,7 @@ def test_layer_splicing(): input = hax.random.normal(jrandom.PRNGKey(0), Input) * 10 # 10 so we don't underflow output = mlp(input) output_q = mlp_q(input) - assert jnp.allclose(output.array, output_q.array, atol=1e-3, rtol=1e-3) + chex.assert_trees_all_close(output.array, output_q.array, atol=1e-3, rtol=1e-3) assert not jnp.allclose(output_q.array, 0) # don't want them to all underflow mlp_q = fp8_linear_layers(mlp, Fp8Config(targets="layers.0")) diff --git a/tests/test_hof.py b/tests/test_hof.py index f97606c..dfde01f 100644 --- a/tests/test_hof.py +++ b/tests/test_hof.py @@ -87,6 +87,38 @@ def test_scan_doesnt_scan_scalars(): assert jnp.all(jnp.equal(selected.array, named1.array * 4.0)) +def test_scan_doesnt_scan_init(): + Height = Axis("Height", 10) + named1 = hax.random.uniform(PRNGKey(0), (Height,)) + + init = jnp.arange(Height.size, dtype=jnp.float32) + + def scan_fun(acc, z, x): + out = acc + z * x, x * z + return out + + total, selected = hax.scan(scan_fun, Height)(init, 4.0, named1) + + assert jnp.all(jnp.isclose(total, init + jnp.sum(named1.array * 4.0))) + + # double check with named array init + total, selected = hax.scan(scan_fun, Height)(hax.named(init, "Height"), 4.0, named1) + + assert jnp.all(jnp.isclose(total.array, init + jnp.sum(named1.array * 4.0))) + + # now do fold + def fold_fun(acc, z, x): + return acc + z * x + + total = hax.fold(fold_fun, Height)(init, 4.0, named1) + + assert jnp.all(jnp.isclose(total, init + jnp.sum(named1.array * 4.0))) + + total = hax.fold(fold_fun, Height)(hax.named(init, "Height"), 4.0, named1) + + assert jnp.all(jnp.isclose(total.array, init + jnp.sum(named1.array * 4.0))) + + def test_reduce(): Height = Axis("Height", 10) Width = Axis("Width", 3) diff --git a/tests/test_partitioning.py b/tests/test_partitioning.py index 3b13ba7..7ab5440 100644 --- a/tests/test_partitioning.py +++ b/tests/test_partitioning.py @@ -108,26 +108,21 @@ def test_pjit_class_init_with_args(): def test_infer_resource_partition_gda_bug(): devices = jax.devices() with Mesh(np.array(devices).reshape(-1, 1), (ResourceAxis.DATA, ResourceAxis.MODEL)): - jax.config.update("jax_parallel_functions_output_gda", True) - try: - def foo(): - return hax.zeros((Dim1, Dim2, Dim3)) + def foo(): + return hax.zeros((Dim1, Dim2, Dim3)) - pjit_foo = named_jit(foo, resource_map) - r = pjit_foo() - assert r.axes == (Dim1, Dim2, Dim3) + pjit_foo = named_jit(foo, resource_map) + r = pjit_foo() + assert r.axes == (Dim1, Dim2, Dim3) - def bar(x): - return x - - # this won't work with GDAs - pjit_bar = named_jit(bar, resource_map) - r = pjit_bar(r) - assert r.axes == (Dim1, Dim2, Dim3) + def bar(x): + return x - finally: - jax.config.update("jax_parallel_functions_output_gda", False) + # this won't work with GDAs + pjit_bar = named_jit(bar, resource_map) + r = pjit_bar(r) + assert r.axes == (Dim1, Dim2, Dim3) @skip_if_not_enough_devices(4) commit 2c88c4c35b101e438d77c0f8717ebd8dc7f19886 Date: 2024-06-08T23:40:40-07:00 fix precommit diff --git a/src/haliax/__init__.py b/src/haliax/__init__.py index 2ad1750..7aea845 100644 --- a/src/haliax/__init__.py +++ b/src/haliax/__init__.py @@ -56,8 +56,8 @@ from .core import ( unflatten_axis, updated_slice, ) -from .jax_utils import filter_checkpoint from .hof import fold, map, scan, vmap +from .jax_utils import filter_checkpoint from .ops import clip, isclose, pad_left, trace, tril, triu, where from .partitioning import auto_sharded, axis_mapping, fsdp, named_jit, shard, shard_with_axis_mapping from .specialized_fns import top_k commit 072fc9e7df7a257fda8a97870cb5067f5d9fcffd Date: 2024-06-11T21:24:27-07:00 Run levanter tests on PR (#95) diff --git a/.github/workflows/run_pre_commit.yaml b/.github/workflows/run_pre_commit.yaml index 113b337..88b59fb 100644 --- a/.github/workflows/run_pre_commit.yaml +++ b/.github/workflows/run_pre_commit.yaml @@ -1,6 +1,6 @@ name: Pre-Commit -on: [push] +on: [push, pull_request] jobs: build: diff --git a/.github/workflows/run_quick_levanter_tests.yaml b/.github/workflows/run_quick_levanter_tests.yaml new file mode 100644 index 0000000..82f748f --- /dev/null +++ b/.github/workflows/run_quick_levanter_tests.yaml @@ -0,0 +1,36 @@ +name: Run Levanter Tests + +on: [pull_request] + +jobs: + build: + + runs-on: ubuntu-latest + + steps: + - uses: actions/checkout@v3 + - name: Set up Python 3.10.11 + uses: actions/setup-python@v4 + with: + python-version: 3.10.11 + - name: Install dependencies + run: | + python -m pip install --upgrade pip + pip install flake8 pytest + pip install --upgrade "jax[cpu]==0.4.26" "jaxlib[cpu]==0.4.26" + + - name: Install Levanter from source + run: | + cd .. + git clone https://github.com/stanford-crfm/levanter.git + cd levanter + pip install -e . + - name: Install Haliax on top + run: | + # install second since levanter will install a built version of haliax + cd ../haliax + pip install .[dev] + - name: Test levanter with pytest + run: | + cd ../levanter + XLA_FLAGS=--xla_force_host_platform_device_count=8 PYTHONPATH=tests:src:../src pytest tests -m "not entry and not slow" diff --git a/.github/workflows/run_tests.yaml b/.github/workflows/run_tests.yaml index fbfccde..e0c759c 100644 --- a/.github/workflows/run_tests.yaml +++ b/.github/workflows/run_tests.yaml @@ -1,21 +1,18 @@ name: Run Tests -on: [push] +on: [push, pull_request] jobs: build: runs-on: ubuntu-latest - strategy: - matrix: - python-version: ["3.10.11"] steps: - uses: actions/checkout@v3 - - name: Set up Python ${{ matrix.python-version }} + - name: Set up Python 3.10.11 uses: actions/setup-python@v4 with: - python-version: ${{ matrix.python-version }} + python-version: 3.10.11 - name: Install dependencies run: | python -m pip install --upgrade pip commit ac6dcae5f9db5e3c2f21064e7cfdc191e7432360 Date: 2024-06-11T23:17:51-07:00 No default in_resources (#94) diff --git a/src/haliax/partitioning.py b/src/haliax/partitioning.py index 4b9e99c..2d0c08d 100644 --- a/src/haliax/partitioning.py +++ b/src/haliax/partitioning.py @@ -310,8 +310,6 @@ class _NamedJitWrapper(eqx.Module): my_pjit_args = dict(**self._pjit_args) if in_axis_resources is not None or axis_resources is not None: - if in_axis_resources is None: - in_axis_resources = axis_resources in_resources = infer_resource_partitions( (dynamic_donated, dynamic_reserved), in_axis_resources, diff --git a/tests/test_partitioning.py b/tests/test_partitioning.py index 7ab5440..c1768ee 100644 --- a/tests/test_partitioning.py +++ b/tests/test_partitioning.py @@ -99,7 +99,7 @@ def test_pjit_class_init_with_args(): devices = jax.devices() with Mesh(np.array(devices).reshape(-1, 1), (ResourceAxis.DATA, ResourceAxis.MODEL)): - mod = named_jit(ModWithArgs)(hax.ones((Dim1, Dim2))) + mod = named_jit(ModWithArgs)(hax.shard(hax.ones((Dim1, Dim2)))) assert isinstance(mod, ModWithArgs) assert mod.array.array.shape == (Dim1.size, Dim2.size) assert mod.array2.array.shape == (Dim3.size,) @@ -173,7 +173,7 @@ def test_shard_with_axis_mapping_inside_jit(): jax.debug.inspect_array_sharding(arr.array, callback=lambda x: assert_eq(x, expected)) - @named_jit(in_axis_resources={}, out_axis_resources=resource_map) + @named_jit(out_axis_resources=resource_map) def do_shard(x, y): x = hax.shard(x, resource_map) assert_inside_pjit(x, NamedSharding(mesh, PartitionSpec(None, ResourceAxis.DATA))) @@ -293,3 +293,25 @@ def test_cross_device_sharding(): z_devices = z.array.devices() assert set(d.platform for d in x_devices) == set(d.platform for d in z_devices) + + +def test_named_jit_no_in_axis_resources(): + mesh = Mesh(np.array(jax.devices()).reshape(-1, 1), (ResourceAxis.DATA, ResourceAxis.MODEL)) + with axis_mapping(resource_map), mesh: + + class MyModule(eqx.Module): + array: NamedArray + + def __init__(self): + self.array = hax.ones((Dim1, Dim2)) + + data = hax.ones((Dim1, Dim2)) + data = hax.shard(data, {}) + + @named_jit(axis_resources=resource_map) + def fn(data): + mod = MyModule() + return mod.array + + r = fn(data) + assert r.array.sharding.device_set == set(jax.devices()) commit 2cc15c8a938fe4c0f72d31755fe9ab6f46a31769 Date: 2024-06-12T13:33:58-07:00 fix sharding outside jit on multiprocess diff --git a/src/haliax/partitioning.py b/src/haliax/partitioning.py index 2d0c08d..10260b5 100644 --- a/src/haliax/partitioning.py +++ b/src/haliax/partitioning.py @@ -141,9 +141,13 @@ def shard(x: T, mapping: Optional[ResourceMapping] = None, mesh: Optional[Mesh] assert isinstance(sharding, NamedSharding) if is_in_jit(): return with_sharding_constraint(x, sharding) - else: + elif sharding.is_fully_addressable: sharded_array = jax.device_put(x.array, sharding) return NamedArray(sharded_array, x.axes) + else: + # sharded_array = jax.device_put(x.array, sharding) + ret = eqx.filter_jit(lambda x: with_sharding_constraint(x, sharding))(x) + return ret return htu.tree_map(_do_device_put, x) commit 9dc3490442045d9edccf75258fb08aceac8b495c Date: 2024-06-13T01:19:36+00:00 Revert "fix sharding outside jit on multiprocess" This reverts commit 2cc15c8a938fe4c0f72d31755fe9ab6f46a31769. diff --git a/src/haliax/partitioning.py b/src/haliax/partitioning.py index 10260b5..2d0c08d 100644 --- a/src/haliax/partitioning.py +++ b/src/haliax/partitioning.py @@ -141,13 +141,9 @@ def shard(x: T, mapping: Optional[ResourceMapping] = None, mesh: Optional[Mesh] assert isinstance(sharding, NamedSharding) if is_in_jit(): return with_sharding_constraint(x, sharding) - elif sharding.is_fully_addressable: + else: sharded_array = jax.device_put(x.array, sharding) return NamedArray(sharded_array, x.axes) - else: - # sharded_array = jax.device_put(x.array, sharding) - ret = eqx.filter_jit(lambda x: with_sharding_constraint(x, sharding))(x) - return ret return htu.tree_map(_do_device_put, x) commit edb9fa4a77ff0bd40910970c3692c059363b8321 Date: 2024-06-12T21:42:15-07:00 Revert "Revert "fix sharding outside jit on multiprocess"" This reverts commit 9dc3490442045d9edccf75258fb08aceac8b495c. diff --git a/src/haliax/partitioning.py b/src/haliax/partitioning.py index 2d0c08d..10260b5 100644 --- a/src/haliax/partitioning.py +++ b/src/haliax/partitioning.py @@ -141,9 +141,13 @@ def shard(x: T, mapping: Optional[ResourceMapping] = None, mesh: Optional[Mesh] assert isinstance(sharding, NamedSharding) if is_in_jit(): return with_sharding_constraint(x, sharding) - else: + elif sharding.is_fully_addressable: sharded_array = jax.device_put(x.array, sharding) return NamedArray(sharded_array, x.axes) + else: + # sharded_array = jax.device_put(x.array, sharding) + ret = eqx.filter_jit(lambda x: with_sharding_constraint(x, sharding))(x) + return ret return htu.tree_map(_do_device_put, x) commit 2296aafce69befd6f568386a625f810ffc616bd6 Date: 2024-06-12T21:44:20-07:00 dumb diff --git a/src/haliax/partitioning.py b/src/haliax/partitioning.py index 10260b5..903e4ff 100644 --- a/src/haliax/partitioning.py +++ b/src/haliax/partitioning.py @@ -313,7 +313,7 @@ class _NamedJitWrapper(eqx.Module): output_shape = _cached_filter_eval_shape(self._fn, *args, **kwargs) my_pjit_args = dict(**self._pjit_args) - if in_axis_resources is not None or axis_resources is not None: + if in_axis_resources is not None: in_resources = infer_resource_partitions( (dynamic_donated, dynamic_reserved), in_axis_resources, commit 99d81fb7057371cf68c147aea1716f346e2c6fae Date: 2024-06-15T00:21:46-07:00 more helpful error message for take diff --git a/src/haliax/core.py b/src/haliax/core.py index 57550ed..9545522 100644 --- a/src/haliax/core.py +++ b/src/haliax/core.py @@ -684,6 +684,8 @@ def take(array: NamedArray, axis: AxisSelector, index: Union[int, NamedArray]) - new_axes = array.axes[:axis_index] + array.axes[axis_index + 1 :] return NamedArray(new_array, new_axes) else: + if not jnp.issubdtype(index.dtype, jnp.integer): + raise ValueError(f"Index must be an integer array, got {index.dtype}") # #13: should broadcast/autobatch take remaining_axes = eliminate_axes(array.axes, axis) # axis order is generally [array.axes[:axis_index], index.axes, array.axes[axis_index + 1 :]] commit 4879011a05e1e6904a3c17bc02fc1f3910184aea Date: 2024-06-27T14:42:27-07:00 Another attempt at shard (#96) * fix shard again? this time with input from yash * fix for new numpy? * hnadjklhnad diff --git a/.github/workflows/run_tests.yaml b/.github/workflows/run_tests.yaml index e0c759c..90e979c 100644 --- a/.github/workflows/run_tests.yaml +++ b/.github/workflows/run_tests.yaml @@ -17,7 +17,7 @@ jobs: run: | python -m pip install --upgrade pip pip install flake8 pytest - pip install --upgrade "jax[cpu]==0.4.25" "jaxlib[cpu]==0.4.25" + pip install --upgrade "jax[cpu]==0.4.30" "jaxlib[cpu]==0.4.30" pip install .[dev] - name: Test with pytest run: | diff --git a/src/haliax/partitioning.py b/src/haliax/partitioning.py index 903e4ff..48e8b49 100644 --- a/src/haliax/partitioning.py +++ b/src/haliax/partitioning.py @@ -128,25 +128,26 @@ def shard(x: T, mapping: Optional[ResourceMapping] = None, mesh: Optional[Mesh] warnings.warn("Sharding constraints are not supported in jit on metal", RuntimeWarning) return x - def _do_device_put(x): - if not isinstance(x, NamedArray): - return x + def _do_device_put(named): + if not isinstance(named, NamedArray): + return named - if not is_jax_array_like(x.array): + if not is_jax_array_like(named.array): # this happens when we filter out params for things like lora. # could use eqx.partition to avoid this, but eh - return x + return named - sharding = infer_resource_partitions(x, mapping, mesh=mesh, preserve_existing_shardings=False) + sharding = infer_resource_partitions(named, mapping, mesh=mesh, preserve_existing_shardings=False) assert isinstance(sharding, NamedSharding) if is_in_jit(): - return with_sharding_constraint(x, sharding) - elif sharding.is_fully_addressable: - sharded_array = jax.device_put(x.array, sharding) - return NamedArray(sharded_array, x.axes) + return with_sharding_constraint(named, sharding) + # as a special case, SingleDeviceShardings are routed through jit + elif isinstance(named.array.sharding, SingleDeviceSharding): + # TODO(dlwh): this should be unnecessary in JAX soon. Check after 2024-08-01 + sharded_array = jax.jit(lambda x: x, out_shardings=sharding)(named) + return sharded_array else: - # sharded_array = jax.device_put(x.array, sharding) - ret = eqx.filter_jit(lambda x: with_sharding_constraint(x, sharding))(x) + ret = jax.device_put(named, sharding) return ret return htu.tree_map(_do_device_put, x) commit 77cb2a95c9da637071c2dca2b3f7a9d3195e15d2 Date: 2024-07-16T19:14:27-05:00 narrow range where we use jit for sharding (#98) * narrow range where we use jit for sharding * sigh diff --git a/src/haliax/partitioning.py b/src/haliax/partitioning.py index 48e8b49..58a634c 100644 --- a/src/haliax/partitioning.py +++ b/src/haliax/partitioning.py @@ -139,10 +139,11 @@ def shard(x: T, mapping: Optional[ResourceMapping] = None, mesh: Optional[Mesh] sharding = infer_resource_partitions(named, mapping, mesh=mesh, preserve_existing_shardings=False) assert isinstance(sharding, NamedSharding) + in_sharding = getattr(named.array, "sharding", None) if is_in_jit(): return with_sharding_constraint(named, sharding) # as a special case, SingleDeviceShardings are routed through jit - elif isinstance(named.array.sharding, SingleDeviceSharding): + elif isinstance(in_sharding, SingleDeviceSharding) and in_sharding._device in sharding.device_set: # TODO(dlwh): this should be unnecessary in JAX soon. Check after 2024-08-01 sharded_array = jax.jit(lambda x: x, out_shardings=sharding)(named) return sharded_array commit fe4c3a1b6922fbc67a21ad735f59f475459f1c0b Date: 2024-07-25T13:22:05-07:00 add reduce_loss (#101) diff --git a/src/haliax/nn/__init__.py b/src/haliax/nn/__init__.py index 3617e2b..c343449 100644 --- a/src/haliax/nn/__init__.py +++ b/src/haliax/nn/__init__.py @@ -34,7 +34,7 @@ from .conv import Conv, ConvTranspose from .dropout import Dropout, dropout from .embedding import Embedding from .linear import Linear -from .loss import binary_cross_entropy_loss, cross_entropy_loss, cross_entropy_loss_and_log_normalizers +from .loss import binary_cross_entropy_loss, cross_entropy_loss, cross_entropy_loss_and_log_normalizers, reduce_loss from .mlp import MLP from .normalization import LayerNorm, log_softmax, logsumexp, softmax, standardize from .pool import max_pool, mean_pool, min_pool @@ -77,6 +77,7 @@ __all__ = [ "attention", "one_hot", "binary_cross_entropy_loss", + "reduce_loss", "cross_entropy_loss", "cross_entropy_loss_and_log_normalizers", "Conv", diff --git a/src/haliax/nn/loss.py b/src/haliax/nn/loss.py index 0db9ced..cd3b740 100644 --- a/src/haliax/nn/loss.py +++ b/src/haliax/nn/loss.py @@ -94,6 +94,21 @@ def binary_cross_entropy_loss( return loss +def reduce_loss( + arr, + reduction: Optional[ReductionFunction] | Unspecified = UNSPECIFIED, + reduction_axis: Optional[AxisSelection] = None, + where: Optional[NamedArray] = None, +): + """ + Reduce a loss array according to the given reduction and reduction axis. + If reduction is None, the loss is not reduced. + If reduction is UNSPECIFIED, the default reduction is used (mean). + If reduction_axis is None (default), the loss is reduced over all axes. + """ + return maybe_reduce_loss(arr, reduction, reduction_axis, where) + + def maybe_reduce_loss( arr, reduction: Optional[ReductionFunction] | Unspecified, commit 52e3379fadee8853ac177c8ea06895d8a24e822d Date: 2024-07-25T13:32:15-07:00 fix import for newest JAX (#102) diff --git a/src/haliax/partitioning.py b/src/haliax/partitioning.py index 58a634c..95c5d86 100644 --- a/src/haliax/partitioning.py +++ b/src/haliax/partitioning.py @@ -603,7 +603,10 @@ def round_axis_for_partitioning(axis: Axis, mapping: Optional[ResourceMapping] = def _get_mesh() -> Mesh: - from jax.experimental.maps import thread_resources + try: + from jax.interpreters.pxla import thread_resources + except ImportError: + from jax.experimental.maps import thread_resources return thread_resources.env.physical_mesh commit 17f978567d9dfa4e0e23d263eb1a48dc715e8f60 Date: 2024-07-25T13:32:43-07:00 add scan_aware_tree_map (#100) diff --git a/src/haliax/tree_util.py b/src/haliax/tree_util.py index 31b1ec0..3c21c72 100644 --- a/src/haliax/tree_util.py +++ b/src/haliax/tree_util.py @@ -1,3 +1,5 @@ +import dataclasses +import functools from typing import Optional import equinox as eqx @@ -5,6 +7,8 @@ import jax import jax.tree_util as jtu from jaxtyping import PRNGKeyArray, PyTree +import haliax.nn + from .axis import AxisSelector from .core import NamedArray from .jax_utils import maybe_rng_split @@ -15,12 +19,45 @@ def tree_map(fn, tree, *rest, is_leaf=None): """ Version of [jax.tree_util.tree_map][] that automatically treats NamedArrays as leaves. """ + old_is_leaf = is_leaf if is_leaf is None: is_leaf = lambda x: isinstance(x, NamedArray) else: - is_leaf = lambda x: is_leaf(x) or is_named_array(x) + is_leaf = lambda x: old_is_leaf(x) or is_named_array(x) + + return jax.tree.map(fn, tree, *rest, is_leaf=is_leaf) + + +def scan_aware_tree_map(fn, tree, *rest, is_leaf=None): + """ + Version of [haliax.tree_util.tree_map][] that is aware of the scan-layer pattern, specifically as implmeneted + in hax.nn.Stacked. This function will (implicitly) apply the transform to each layer in each Stacked module + (using vmap). If there are no Stacked modules in the tree, this function is equivalent to [haliax.tree_util.tree_map][]. + + Args: + fn: + tree: + *rest: + is_leaf: + + Returns: + """ + old_is_leaf = is_leaf + if is_leaf is None: + is_leaf = lambda x: isinstance(x, haliax.nn.Stacked) + else: + is_leaf = lambda x: old_is_leaf(x) or isinstance(x, haliax.nn.Stacked) + + mapped_fn = functools.partial(scan_aware_tree_map, fn, is_leaf=is_leaf) + + def rec_fn(x, *rest): + if isinstance(x, haliax.nn.Stacked): + new_inner = haliax.vmap(mapped_fn, x.Block)(x.stacked, *[r.stacked for r in rest]) + return dataclasses.replace(x, stacked=new_inner) # type: ignore + else: + return fn(x) - return jax.tree_util.tree_map(fn, tree, *rest, is_leaf=is_leaf) + return tree_map(rec_fn, tree, *rest, is_leaf=is_leaf) def tree_flatten(tree, is_leaf=None): diff --git a/tests/test_tree_util.py b/tests/test_tree_util.py index 4c93edd..8fb4c54 100644 --- a/tests/test_tree_util.py +++ b/tests/test_tree_util.py @@ -1,6 +1,9 @@ +import dataclasses + import equinox as eqx import jax import jax.numpy as jnp +from chex import assert_trees_all_close import haliax as hax import haliax.tree_util as htu @@ -34,3 +37,55 @@ def test_resize_axis(): # we don't mess with the mean or std of the original array too much assert jnp.allclose(module2.name1.mean(), module.name1.mean(), rtol=1e-1, atol=1e-2) + + +def test_scan_aware_tree_map(): + Embed = hax.Axis("embed", 10) + Up = hax.Axis("up", 20) + Block = hax.Axis("block", 4) + + class Module(eqx.Module): + up: hax.nn.Linear + down: hax.nn.Linear + + def __call__(self, x, *, key): + return self.down(self.up(x), key=key) + + @staticmethod + def init(layer_idx, *, key): + k1, k2 = jax.random.split(key) + up = hax.nn.Linear.init(Embed, Up, key=k1) + down = hax.nn.Linear.init(Up, Embed, key=k2) + + up = dataclasses.replace(up, weight=up.weight + layer_idx) # type: ignore + down = dataclasses.replace(down, weight=down.weight + layer_idx) # type: ignore + + return Module(up=up, down=down) + + class Model(eqx.Module): + layers: hax.nn.Stacked[eqx.Module] + + def __call__(self, x, *, key): + return self.layers.fold(x, key=jax.random.split(key, self.layers.Block.size)) + + @staticmethod + def init(Layers, *, key): + stack = hax.nn.Stacked.init(Layers, Module)( + layer_idx=hax.arange(Layers), key=jax.random.split(key, Layers.size) + ) + return Model(layers=stack) + + model = Model.init(Block, key=jax.random.PRNGKey(0)) + + def transform_linear(x): + if not isinstance(x, hax.nn.Linear): + return x + + # do something that distinguishes doing weights jointly from independently + new_weight = x.weight - hax.mean(x.weight) + return dataclasses.replace(x, weight=new_weight) # type: ignore + + model2 = htu.scan_aware_tree_map(transform_linear, model, is_leaf=lambda x: isinstance(x, hax.nn.Linear)) + model3 = htu.tree_map(transform_linear, model, is_leaf=lambda x: isinstance(x, hax.nn.Linear)) + + assert hax.all(model2.layers.stacked.up.weight != model3.layers.stacked.up.weight) commit 01835a6d431d2497438e056ea5db254d27552cc8 Date: 2024-08-27T12:47:58-07:00 Merge remote-tracking branch 'origin/main' commit 196467e65601b65c3826bf74daaa578a50517c3e Date: 2024-08-30T22:28:40-07:00 add some more docs for Stacked diff --git a/src/haliax/nn/scan.py b/src/haliax/nn/scan.py index 2baf888..9c68d30 100644 --- a/src/haliax/nn/scan.py +++ b/src/haliax/nn/scan.py @@ -156,6 +156,13 @@ class Stacked(eqx.Module, Generic[M]): Stacked also supports gradient checkpointing, which is useful for very large models that don't fit in memory. + Typically only one of "fold" or "scan" can be used with a given Stacked module, depending on the what the module + returns: if the module returns a single output, use "fold"; if the module returns a sequence of intermediates and + an output to be passed to the next layer, use "scan". More concretely, for a transformer, you would use "scan" if + you wanted to return a kv cache (or the attention matrix) as well as the output of the transformer. If you just + wanted the output of the transformer, you would use "fold". + + Example: ```python >>> import equinox as eqx @@ -206,6 +213,32 @@ class Stacked(eqx.Module, Generic[M]): return fn def scan(self, init, *extra_args, **extra_kwargs): + """ + Scan over the stacked module. This is the same as a for loop that applies each instance of the module in sequence + to the input, passing the output of one instance to the next instance. It returns a stack of intermediates as + well as the final output. + + That is, it behaves similarly to the following Python code: + + ```python + carry = init + intermediates = [] + + for block in self.stacked: + carry, extra = block(carry) + intermediates.append(extra) + + return carry, hax.stack(Block, intermediates) + ``` + + Args: + init: + *extra_args: + **extra_kwargs: + + Returns: + + """ if self.gradient_checkpointing: do_block = filter_checkpoint(self._do_block, prevent_cse=self.prevent_cse) else: @@ -213,6 +246,27 @@ class Stacked(eqx.Module, Generic[M]): return haliax.scan(do_block, self.Block)(init, self.stacked, *extra_args, **extra_kwargs) def fold(self, init, *args, **kwargs): + """ + Fold over the stacked module. This is the same as a for loop that applies each instance of the module in sequence + to the input, passing the output of one instance to the next instance. + That is, it behaves similarly to the following Python code: + + ```python + carry = init + for block in self.stacked: + carry = block(carry) + + return carry + ``` + + Args: + init: + *args: + **kwargs: + + Returns: + + """ if self.gradient_checkpointing: do_block = filter_checkpoint(self._do_block, prevent_cse=self.prevent_cse) else: diff --git a/tests/test_scan.py b/tests/test_scan.py index d01896a..3b438b1 100644 --- a/tests/test_scan.py +++ b/tests/test_scan.py @@ -68,3 +68,30 @@ def test_seq_and_stacked_give_same_results(): y_seq = m_seq.fold(x, key=jax.random.split(jax.random.PRNGKey(2), Block.size)) assert hax.all(hax.isclose(y, y_seq, atol=1e-5)) + + +def test_using_scan(): + class Module(eqx.Module): + named: hax.NamedArray + array: jax.Array + static: int = eqx.static_field() + + def __call__(self, x, *, key): + return x + self.array + self.static + hax.random.normal(key, x.axes), x * 2 + + @staticmethod + def init(named, array, static): + return Module(named=named, array=array, static=static) + + Block = hax.Axis("block", 4) + E = hax.Axis("E", 10) + + initial_named = hax.random.uniform(jax.random.PRNGKey(0), (Block, E)) + + m = Stacked.init(Block, Module)(named=initial_named, array=jax.numpy.ones(Block.size), static=1) + + x = hax.random.uniform(jax.random.PRNGKey(1), (E,)) + y, intermediates = m.scan(x, key=jax.random.split(jax.random.PRNGKey(2), Block.size)) + + assert y.axes == (E,) + assert intermediates.axes == (Block, E) commit eaf6a381364befd11b3302870e273a1e8a782797 Date: 2024-09-03T00:27:20-07:00 fix bug in indexing slices diff --git a/src/haliax/core.py b/src/haliax/core.py index 9545522..7c3a58a 100644 --- a/src/haliax/core.py +++ b/src/haliax/core.py @@ -952,6 +952,7 @@ def _compute_new_axes_and_slices_for_index( # we allow this if it's a 0-d or 1-d array if slice_.ndim == 0: ordered_slices[axis_index] = slice_ + kept_axes[axis_index] = False elif slice_.ndim == 1: # we allow this if it's a 1-d array, in which case we treat it as sugar for NamedArray(slice_, sliced-axis) ordered_slices[axis_index] = haliax.named(slice_, axis_name(axis)) diff --git a/tests/core_test.py b/tests/core_test.py index 4e6dec9..4a52f63 100644 --- a/tests/core_test.py +++ b/tests/core_test.py @@ -543,6 +543,23 @@ def test_index(): assert jnp.all(jnp.equal(named1[{"H": 0, "W": 0, "D": 0}], named1.array[0, 0, 0])) +def test_index_with_tracer(): + H = Axis("H", 20) + W = Axis("W", 30) + D = Axis("D", 40) + named1 = hax.random.uniform(PRNGKey(0), (H, W, D)) + + @jax.jit + def f(idx): + return named1["H", idx] + + idx = jnp.array([1, 2, 3]) + assert jnp.all(jnp.equal(f(idx).array, named1.array[1:4, :, :])) + + idx = jnp.array(0) + assert jnp.all(jnp.equal(f(idx).array, named1.array[0, :, :])) + + def test_index_array_slices(): # fancier tests with array slices with named array args H = Axis("H", 10) commit bf807bb1ee8573bc67e41cdb9c8e41c1b43d3068 Date: 2024-09-03T12:46:00-07:00 add errors when scan contract isn't respected, fix logic bug in array slicing diff --git a/src/haliax/jax_utils.py b/src/haliax/jax_utils.py index c1876ab..a95608b 100644 --- a/src/haliax/jax_utils.py +++ b/src/haliax/jax_utils.py @@ -80,7 +80,7 @@ def filter_checkpoint(fun: Callable, *, prevent_cse: bool = True, policy: Option def is_jax_array_like(x): - return hasattr(x, "shape") and hasattr(x, "dtype") + return hasattr(x, "shape") and hasattr(x, "dtype") # and not isinstance(x, haliax.NamedArray) # adapted from jax but exposed so i can use it diff --git a/src/haliax/nn/scan.py b/src/haliax/nn/scan.py index 9c68d30..6836086 100644 --- a/src/haliax/nn/scan.py +++ b/src/haliax/nn/scan.py @@ -102,7 +102,14 @@ class BlockSeq(eqx.Module, Generic[M]): (block_args, block_kwargs) = haliax.tree_util.tree_map( functools.partial(BlockSeq._slice_out, self.Block, i), (extra_args, extra_kwargs) ) - carry, extra = block(carry, *block_args, **block_kwargs) + block_result = block(carry, *block_args, **block_kwargs) + if not isinstance(block_result, (tuple, list)) or len(block_result) != 2: + raise ValueError( + f"BlockSeq.scan expects the block to return a pair of (carry, extra), got {block_result}" + ) + + carry, extra = block_result + out.append(extra) # TODO: do we want to stack the outputs? @@ -124,8 +131,11 @@ class BlockSeq(eqx.Module, Generic[M]): @staticmethod def _slice_out(Block, i, x): - if haliax.is_named_array(x) and haliax.selects_axis(x.axes, Block): - return x[Block, i] + if haliax.is_named_array(x): + if haliax.selects_axis(x.axes, Block): + return x[Block, i] + else: + return x elif haliax.jax_utils.is_jax_array_like(x): return x[i] else: diff --git a/tests/test_scan.py b/tests/test_scan.py index 3b438b1..273d35f 100644 --- a/tests/test_scan.py +++ b/tests/test_scan.py @@ -1,5 +1,6 @@ import equinox as eqx import jax +import pytest import haliax as hax from haliax.nn.scan import BlockSeq, Stacked @@ -66,9 +67,14 @@ def test_seq_and_stacked_give_same_results(): x = hax.random.uniform(jax.random.PRNGKey(1), (E,)) y = m.fold(x, key=jax.random.split(jax.random.PRNGKey(2), Block.size)) y_seq = m_seq.fold(x, key=jax.random.split(jax.random.PRNGKey(2), Block.size)) - assert hax.all(hax.isclose(y, y_seq, atol=1e-5)) + with pytest.raises(ValueError): + m.scan(x, key=jax.random.split(jax.random.PRNGKey(2), Block.size)) + + with pytest.raises(ValueError): + m_seq.scan(x, key=jax.random.split(jax.random.PRNGKey(2), Block.size)) + def test_using_scan(): class Module(eqx.Module): @@ -95,3 +101,35 @@ def test_using_scan(): assert y.axes == (E,) assert intermediates.axes == (Block, E) + + +def test_scan_with_aux_named_args(): + class Module(eqx.Module): + named: hax.NamedArray + array: jax.Array + static: int = eqx.static_field() + + def __call__(self, x, y, *, key): + return x + self.array + self.static + hax.random.normal(key, x.axes), x * 2 + y + + @staticmethod + def init(named, array, static): + return Module(named=named, array=array, static=static) + + Block = hax.Axis("block", 4) + E = hax.Axis("E", 10) + + initial_named = hax.random.uniform(jax.random.PRNGKey(0), (Block, E)) + initial_y = hax.random.uniform(jax.random.PRNGKey(1), (E,)) + + m = Stacked.init(Block, Module)(named=initial_named, array=jax.numpy.ones(Block.size), static=1) + m_seq = BlockSeq.init(Block, Module)(named=initial_named, array=jax.numpy.ones(Block.size), static=1) + + x = hax.random.uniform(jax.random.PRNGKey(1), (E,)) + z, z_scan = m.scan(x, initial_y, key=jax.random.split(jax.random.PRNGKey(2), Block.size)) + z_seq, z_seq_scan = m_seq.scan(x, initial_y, key=jax.random.split(jax.random.PRNGKey(2), Block.size)) + assert hax.all(hax.isclose(z, z_seq, atol=1e-5)) + + z_seq_scan = hax.stack(Block, z_seq_scan) + + assert hax.all(hax.isclose(z_scan, z_seq_scan, atol=1e-5)) commit 9a5e1081160d2d8a0bae19ca532f4b336260136a Date: 2024-09-04T10:37:11-07:00 make out_first = True the default for mlp (#105) diff --git a/src/haliax/nn/mlp.py b/src/haliax/nn/mlp.py index 587f7b0..640cda3 100644 --- a/src/haliax/nn/mlp.py +++ b/src/haliax/nn/mlp.py @@ -44,6 +44,7 @@ class MLP(eqx.Module): depth: int, activation: Callable = relu, *, + out_first: bool = True, use_bias: bool = True, use_final_bias: bool = True, key: PRNGKeyArray, @@ -57,36 +58,34 @@ class MLP(eqx.Module): layers = [] + kwargs: dict = { + "use_bias": use_bias, + "dot_general": dot_general, + "init_scale": init_scale, + "out_first": out_first, + } + + last_kwargs: dict = { + "use_bias": use_final_bias, + "dot_general": dot_general, + "init_scale": init_scale, + "out_first": out_first, + } + if depth == 0: # special case: no hidden layers - layers.append( - Linear.init( - Input, Output, use_bias=use_final_bias, key=keys[0], dot_general=dot_general, init_scale=init_scale - ) - ) + layers.append(Linear.init(Input, Output, key=keys[0], **last_kwargs)) else: # first hidden layer - layers.append( - Linear.init( - Input, Width, use_bias=use_bias, key=keys[0], dot_general=dot_general, init_scale=init_scale - ) - ) + layers.append(Linear.init(Input, Width, key=keys[0], **kwargs)) # middle hidden layers cur = Width next = Width2 for i in range(1, depth): - layers.append( - Linear.init( - cur, next, use_bias=use_bias, key=keys[i], dot_general=dot_general, init_scale=init_scale - ) - ) + layers.append(Linear.init(cur, next, key=keys[i], **kwargs)) cur, next = next, cur - # final hidden layer - layers.append( - Linear.init( - cur, Output, use_bias=use_final_bias, key=keys[-1], dot_general=dot_general, init_scale=init_scale - ) - ) + # final layer + layers.append(Linear.init(cur, Output, key=keys[-1], **last_kwargs)) return MLP( layers=tuple(layers), commit 754c2bbbb4c24fa4ec1af427107d6c5986dd63eb Date: 2024-09-05T13:14:35-07:00 add make_axes as a nice bit of sugar diff --git a/docs/api.md b/docs/api.md index 1886a8d..743a97a 100644 --- a/docs/api.md +++ b/docs/api.md @@ -27,6 +27,7 @@ Occasionally, an axis size can be inferred in some circumstances but not others. ### Axis Manipulation +::: haliax.make_axes ::: haliax.axis.axis_name ::: haliax.axis.concat_axes ::: haliax.axis.union_axes diff --git a/src/haliax/__init__.py b/src/haliax/__init__.py index 7aea845..6a35ab9 100644 --- a/src/haliax/__init__.py +++ b/src/haliax/__init__.py @@ -32,6 +32,7 @@ from .axis import ( ds, dslice, eliminate_axes, + make_axes, selects_axis, ) from .core import ( @@ -893,6 +894,9 @@ __all__ = [ "AxisSpec", "AxisSelection", "AxisSelector", + "make_axes", + "axis_name", + "axis_size", "NamedArray", "broadcast_to", "broadcast_axis", diff --git a/src/haliax/axis.py b/src/haliax/axis.py index 0c80228..49463c9 100644 --- a/src/haliax/axis.py +++ b/src/haliax/axis.py @@ -28,6 +28,17 @@ class Axis: return f"{self.name}({self.size})" +def make_axes(**kwargs: int) -> Tuple[Axis, ...]: + """ + Convenience function for creating a tuple of Axis objects. + + Example: + ``` + X, Y = axes(X=10, Y=20) + """ + return tuple(Axis(name, size) for name, size in kwargs.items()) + + AxisSelector = Union[Axis, str] """AxisSelector is a type that can be used to select a single axis from an array. str or Axis""" AxisSelection = Union[AxisSelector, Sequence[AxisSelector]] diff --git a/src/haliax/core.py b/src/haliax/core.py index 7c3a58a..264097d 100644 --- a/src/haliax/core.py +++ b/src/haliax/core.py @@ -373,11 +373,10 @@ class NamedArray: Supports indexing like: - >>> X = Axis("x", 10) - >>> Y = Axis("y", 20) + >>> X, Y = haliax.make_axes(X=10, Y=20) >>> arr = haliax.random.randint(jax.random.PRNGKey(0), (X, Y), 0, X.size) # slice with ints or slices - >>> arr[{"x": 1, "y": slice(0,10,new_axis=2)}] + >>> arr[{"x": 1, "y": slice(0,10,2)}] >>> Z = Axis("z", 3) # so-called "advanced indexing" with NamedArrays. >>> index_arr = NamedArray(np.array([1, 2, 3]), Z) diff --git a/src/haliax/nn/scan.py b/src/haliax/nn/scan.py index 6836086..d4b6161 100644 --- a/src/haliax/nn/scan.py +++ b/src/haliax/nn/scan.py @@ -300,7 +300,7 @@ class Stacked(eqx.Module, Generic[M]): """ def unbatch_leaf(x): - if haliax.is_named_array(x): + if isinstance(x, haliax.core.NamedArray): if haliax.selects_axis(x.axes, self.Block): return haliax.unbind(x, self.Block) else: diff --git a/tests/core_test.py b/tests/core_test.py index 4a52f63..58f52ea 100644 --- a/tests/core_test.py +++ b/tests/core_test.py @@ -9,9 +9,7 @@ from haliax import Axis, NamedArray def test_unary_np_functions(): - Height = Axis("Height", 2) - Width = Axis("Width", 3) - Depth = Axis("Depth", 4) + Height, Width, Depth = hax.make_axes(Height=2, Width=3, Depth=4) m1 = NamedArray(jnp.ones((Height.size, Width.size, Depth.size)), (Height, Width, Depth)) @@ -29,9 +27,7 @@ def test_unary_np_functions(): def test_reduction_functions(): - Height = Axis("Height", 2) - Width = Axis("Width", 3) - Depth = Axis("Depth", 4) + Height, Width, Depth = hax.make_axes(Height=2, Width=3, Depth=4) rand_m = jax.random.uniform(PRNGKey(0), (Height.size, Width.size, Depth.size)) @@ -69,9 +65,7 @@ def test_reduction_functions(): def test_reduction_functions_with_where(): - H = Axis("H", 2) - W = Axis("W", 3) - D = Axis("D", 4) + H, W, D = hax.make_axes(H=2, W=3, D=4) rand_m = jax.random.uniform(PRNGKey(0), (H.size, W.size, D.size)) @@ -118,9 +112,7 @@ def test_reduction_functions_with_where(): def test_split(): - Height = Axis("Height", 2) - Width = Axis("Width", 3) - Depth = Axis("Depth", 4) + Height, Width, Depth = hax.make_axes(Height=2, Width=3, Depth=4) D10 = Axis("Depth", Depth.size * 10) @@ -144,9 +136,7 @@ def test_split(): def test_take(): - Height = Axis("Height", 2) - Width = Axis("Width", 3) - Depth = Axis("Depth", 4) + Height, Width, Depth = hax.make_axes(Height=2, Width=3, Depth=4) named1 = hax.random.uniform(PRNGKey(0), (Height, Width, Depth)) assert jnp.all(jnp.equal(hax.take(named1, Height, 0).array, named1.array[0])) @@ -178,9 +168,7 @@ def test_take(): def test_take_overlapping_names(): - Height = Axis("Height", 20) - Width = Axis("Width", 30) - Depth = Axis("Depth", 40) + Height, Width, Depth = hax.make_axes(Height=20, Width=30, Depth=40) named1 = hax.random.uniform(PRNGKey(0), (Height, Width, Depth)) Height2 = Axis("Height", 10) @@ -198,9 +186,7 @@ def test_take_overlapping_2(): def cross_entropy(logits: hax.NamedArray, labels: hax.NamedArray) -> hax.NamedArray: return hax.take(logits, Embed, labels) # extract log probability of the correct token - Embed = Axis("Embed", 10) - Block = Axis("Block", 20) - Batch = Axis("Batch", 30) + Embed, Block, Batch = hax.make_axes(Embed=10, Block=20, Batch=30) logits = hax.random.uniform(PRNGKey(0), (Batch, Block, Embed)) labels = hax.random.randint(PRNGKey(0), (Batch, Block), 0, Embed.size) @@ -223,9 +209,7 @@ def test_take_overlapping_2(): def test_cumsum_etc(): - Height = Axis("Height", 2) - Width = Axis("Width", 3) - Depth = Axis("Depth", 4) + Height, Width, Depth = hax.make_axes(Height=2, Width=3, Depth=4) named1 = hax.random.uniform(PRNGKey(0), (Height, Width, Depth)) @@ -255,10 +239,7 @@ def test_cumsum_etc(): def test_rearrange(): - H = Axis("H", 2) - W = Axis("W", 3) - D = Axis("D", 4) - C = Axis("C", 5) + H, W, D, C = hax.make_axes(H=2, W=3, D=4, C=5) named1 = hax.random.uniform(PRNGKey(0), (H, W, D, C)) @@ -304,9 +285,7 @@ def test_rearrange(): def test_rearrange_unused_ellipsis(): # Make sure we just ignore the ellipsis if all axes are specified in addition - H = Axis("Height", 2) - W = Axis("Width", 3) - D = Axis("Depth", 4) + H, W, D = hax.make_axes(Height=2, Width=3, Depth=4) named1 = hax.random.uniform(PRNGKey(0), (H, W, D)) @@ -321,7 +300,7 @@ def test_rearrange_unused_ellipsis(): def test_arange(): - H = Axis("Height", 10) + (H,) = hax.make_axes(H=10) assert jnp.all(jnp.equal(hax.arange(H).array, jnp.arange(10))) assert hax.arange(H).axes == (H,) @@ -334,8 +313,7 @@ def test_arange(): def test_stack(): - H = Axis("H", 4) - W = Axis("W", 3) + H, W = hax.make_axes(H=4, W=3) named1 = hax.random.uniform(PRNGKey(0), (H, W)) named2 = hax.random.uniform(PRNGKey(1), (H, W)) @@ -350,9 +328,8 @@ def test_stack(): def test_concatenate(): - H1 = Axis("H", 4) - H2 = Axis("H", 3) - W = Axis("W", 3) + H1, W = hax.make_axes(H=4, W=3) + H2 = H1.resize(3) named1 = hax.random.uniform(PRNGKey(0), (H1, W)) named2 = hax.random.uniform(PRNGKey(1), (H2, W)) @@ -392,8 +369,7 @@ def test_repeat(): # [3, 4], # [3, 4]]) - H = Axis("H", 2) - W = Axis("W", 2) + H, W = hax.make_axes(H=2, W=2) named1 = hax.named([[1, 2], [3, 4]], (H, W)) @@ -459,9 +435,7 @@ def test_tile(): def test_unflatten_axis(): - H = Axis("Height", 2) - W = Axis("Width", 3) - D = Axis("Depth", 4) + H, W, D = hax.make_axes(Height=2, Width=3, Depth=4) named1 = hax.random.uniform(PRNGKey(0), (H, W, D)) flattened_HW = named1.flatten_axes((H, W), "Z") @@ -483,9 +457,7 @@ def test_unflatten_axis(): def test_ravel(): - H = Axis("Height", 2) - W = Axis("Width", 3) - D = Axis("Depth", 4) + H, W, D = hax.make_axes(Height=2, Width=3, Depth=4) named1 = hax.random.uniform(PRNGKey(0), (H, W, D)) raveled = named1.ravel("Z") @@ -496,13 +468,8 @@ def test_ravel(): def test_rename(): - H = Axis("H", 2) - W = Axis("W", 3) - D = Axis("D", 4) - - H2 = Axis("H2", 2) - W2 = Axis("W2", 3) - D2 = Axis("D2", 4) + H, W, D = hax.make_axes(H=2, W=3, D=4) + H2, W2, D2 = hax.make_axes(H2=2, W2=3, D2=4) named1 = hax.random.uniform(PRNGKey(0), (H, W, D)) @@ -517,9 +484,7 @@ def test_rename(): def test_index(): - H = Axis("H", 20) - W = Axis("W", 30) - D = Axis("D", 40) + H, W, D = hax.make_axes(H=20, W=30, D=40) named1 = hax.random.uniform(PRNGKey(0), (H, W, D)) @@ -544,9 +509,7 @@ def test_index(): def test_index_with_tracer(): - H = Axis("H", 20) - W = Axis("W", 30) - D = Axis("D", 40) + H, W, D = hax.make_axes(H=20, W=30, D=40) named1 = hax.random.uniform(PRNGKey(0), (H, W, D)) @jax.jit @@ -562,12 +525,7 @@ def test_index_with_tracer(): def test_index_array_slices(): # fancier tests with array slices with named array args - H = Axis("H", 10) - W = Axis("W", 20) - D = Axis("D", 30) - C = Axis("C", 40) - Q = Axis("Q", 50) - I0 = Axis("I0", 10) + H, W, D, C, Q, I0 = hax.make_axes(H=10, W=20, D=30, C=40, Q=50, I0=10) named1 = hax.random.uniform(PRNGKey(0), (H, W, D, C, Q)) index_1 = hax.random.randint(PRNGKey(0), (I0,), 0, H.size) @@ -586,9 +544,7 @@ def test_index_array_slices(): # https://numpy.org/doc/stable/user/basics.indexing.html#combining-advanced-and-basic-indexing # Example # Let x.shape be (10, 20, 30, 40, 50) and suppose ind_1 and ind_2 can be broadcast to the shape (2, 3, 4). - I1 = Axis("I1", 2) - I2 = Axis("I2", 3) - I3 = Axis("I3", 4) + I1, I2, I3 = hax.make_axes(I1=2, I2=3, I3=4) ind_1 = hax.random.randint(PRNGKey(0), (I2, I3), 0, W.size) ind_2 = hax.random.randint(PRNGKey(0), (I1, I3), 0, D.size) @@ -615,9 +571,7 @@ def test_index_array_slices(): def test_slice_nd_shorthand_syntax(): # syntax like arr["X", 0:10, "Y", 0:10] is supported - H = Axis("H", 10) - W = Axis("W", 20) - D = Axis("D", 30) + H, W, D = hax.make_axes(H=10, W=20, D=30) named1 = hax.random.uniform(PRNGKey(0), (H, W, D)) @@ -625,9 +579,7 @@ def test_slice_nd_shorthand_syntax(): def test_slice_nd_dslice(): - H = Axis("H", 10) - W = Axis("W", 20) - D = Axis("D", 30) + H, W, D = hax.make_axes(H=10, W=20, D=30) named1 = hax.random.uniform(PRNGKey(0), (H, W, D)) from haliax import ds @@ -641,9 +593,7 @@ def test_slice_nd_dslice(): def test_slice_nd_array_present_dims(): # tests slicing with arrays that are already present in the named array, which is sometimes ok - H = Axis("H", 10) - W = Axis("W", 20) - D = Axis("D", 30) + H, W, D = hax.make_axes(H=10, W=20, D=30) named1 = hax.random.uniform(PRNGKey(0), (H, W, D)) @@ -653,321 +603,3 @@ def test_slice_nd_array_present_dims(): assert jnp.all(jnp.equal(named1[{"H": index1}].array, named1.array[index1.array, :, :])) # this is not ok, since the H would not be eliminated - with pytest.raises(ValueError): - named1[{W: index1}] - - # this is not ok, but is trickier because the H has a different size - H2 = H.resize(5) - index2 = hax.random.randint(PRNGKey(0), (H2,), 0, H.size) - with pytest.raises(ValueError): - named1[{W: index2}] - - # this is ok, since the H would be eliminated anyway - assert jnp.all(jnp.equal(named1[{"H": index2}].array, named1.array[index2.array, :, :])) - - -def test_slice_nd_array_unnamed_slice(): - # tests slicing with arrays that are already present in the named array, which is sometimes ok - H = Axis("H", 10) - W = Axis("W", 20) - D = Axis("D", 30) - - named1 = hax.random.uniform(PRNGKey(0), (H, W, D)) - - index1 = jax.random.randint(PRNGKey(1), (4,), 0, H.size) - assert jnp.all(jnp.equal(named1[{"H": index1}].array, named1.array[index1, :, :])) - - # hidden behavior: if we also pass in an H index to e.g. D, it is zipped together - index2 = hax.random.randint(PRNGKey(2), Axis("H", 4), 0, D.size) - assert jnp.all(jnp.equal(named1[{"H": index1, "D": index2}].array, named1.array[index1, :, index2.array])) - - # this is different though: - index2r = index2.array - assert jnp.all( - jnp.equal( - named1[{"H": index1, "D": index2r}].array, named1.array[index1.reshape(1, -1), :, index2r.reshape(-1, 1)] - ) - ) - assert named1[{"H": index1, "D": index2r}].shape != named1[{"H": index1, "D": index2}].shape - - index1 = list(index1) - assert jnp.all(jnp.equal(named1[{"H": index1}].array, named1.array[index1, :, :])) - - -def test_full_indexing_returns_named_array(): - H = Axis("H", 10) - W = Axis("W", 20) - D = Axis("D", 30) - - named1 = hax.random.uniform(PRNGKey(0), (H, W, D)) - sliced = named1[{"H": 0, "W": 0, "D": 0}] - - assert isinstance(sliced, NamedArray) - assert sliced.shape == {} - - -def test_indexing_bug_from_docs(): - X = hax.Axis("X", 10) - Y = hax.Axis("Y", 20) - Z = hax.Axis("Z", 30) - - a = hax.random.uniform(jax.random.PRNGKey(0), (X, Y, Z)) - - I1 = hax.Axis("I1", 5) - I2 = hax.Axis("I2", 5) - I3 = hax.Axis("I3", 5) - ind1 = hax.random.randint(jax.random.PRNGKey(0), (I1,), 0, 10) - ind2 = hax.random.randint(jax.random.PRNGKey(0), (I2, I3), 0, 20) - - # assert a[{"X": ind1, "Y": ind2}].axes == (I1, I2, I3, Z) - assert a[{"X": ind1, "Y": ind2, "Z": 3}].axes == (I1, I2, I3) - - -def test_duplicate_axis_names_in_slicing(): - X = hax.Axis("X", 10) - Y = hax.Axis("Y", 20) - Z = hax.Axis("Z", 30) - - X2 = hax.Axis("X", 5) - Y2 = hax.Axis("Y", 5) - - a = hax.random.uniform(jax.random.PRNGKey(0), (X, Y, Z)) - ind1 = hax.random.randint(jax.random.PRNGKey(0), (X2,), 0, 10) - ind2 = hax.random.randint(jax.random.PRNGKey(0), (Y2,), 0, 10) - - a[{"X": ind1, "Y": ind2}] # returns a NamedArray with axes = Axis("X", 5), Axis("Y", 5), Axis("Z", 30) - - with pytest.raises(ValueError): - a[{"Y": ind1}] # error, "X" is not eliminated by the indexing operation - - a[{"X": ind2, "Y": ind1}] # ok, because X and Y are eliminated by the indexing operation - - -def test_slice_old_style(): - H = Axis("H", 10) - W = Axis("W", 20) - D = Axis("D", 30) - - named1 = hax.random.randint(PRNGKey(0), (H, W, D), minval=0, maxval=10) - - assert jnp.all(named1.slice("H", start=4, length=2).array == named1.array[4:6, :, :]) - assert jnp.all(named1.slice("W", start=4, length=2).array == named1.array[:, 4:6, :]) - assert jnp.all(named1.slice("D", start=4, length=2).array == named1.array[:, :, 4:6]) - - H2 = Axis("H2", 5) - W2 = Axis("W2", 10) - D2 = Axis("D2", 15) - - assert jnp.all(named1.slice("H", H2, start=4).array == named1.array[4 : 4 + H2.size, :, :]) - assert jnp.all(named1.slice("W", W2, start=4).array == named1.array[:, 4 : 4 + W2.size, :]) - assert jnp.all(named1.slice("D", D2, start=4).array == named1.array[:, :, 4 : 4 + D2.size]) - - -def test_slice_new_style(): - H = Axis("H", 10) - W = Axis("W", 20) - D = Axis("D", 30) - - named1 = hax.random.randint(PRNGKey(0), (H, W, D), minval=0, maxval=10) - - x1 = named1.slice({"H": 4, "W": 5, "D": 7}, length={"H": 2, "W": 3, "D": 4}) - assert jnp.all(x1.array == named1.array[4:6, 5:8, 7:11]) - - with pytest.raises(TypeError): - named1.slice({"H": 4, "W": 5, "D": 7}, length={"H": 2, "W": 3, "D": 4}, start={"H": 1, "W": 2, "D": 3}) - - with pytest.raises(ValueError): - named1.slice({"H": 4, "W": 5, "D": 7}, length={"H": 2, "W": 3}) - - H2 = Axis("H2", 5) - W2 = Axis("W2", 10) - D2 = Axis("D2", 15) - - x2 = named1.slice({"H": 4, "W": 5, "D": 7}, length={"H": H2, "W": W2, "D": D2}) - assert jnp.all(x2.array == named1.array[4 : 4 + H2.size, 5 : 5 + W2.size, 7 : 7 + D2.size]) - - -def test_updated_slice(): - H = Axis("H", 10) - W = Axis("W", 20) - D = Axis("D", 30) - - H2 = H.resize(5) - W2 = W.resize(10) - D2 = D.resize(15) - - named1 = hax.random.randint(PRNGKey(0), (H, W, D), minval=0, maxval=10) - named2 = hax.random.randint(PRNGKey(0), (H2, W2, D2), minval=10, maxval=30) - - named1_updated = named1.updated_slice({"H": 0, "W": 0, "D": 0}, named2) - - assert named1_updated.axes == named1.axes - assert jnp.all(named1_updated["H", 0 : H2.size, "W", 0 : W2.size, "D", 0 : D2.size].array == named2.array) - - # test broadcasting - for pair in [(H2, D2), (H2, W2), (W2, D2), (D2, H2), (D2, W2), (W2, H2)]: - n3 = hax.random.randint(PRNGKey(0), pair, minval=10, maxval=30) - named1_updated = named1.updated_slice({ax.name: 0 for ax in pair}, n3) - assert named1_updated.axes == named1.axes - assert jnp.all((named1_updated[{ax.name: slice(0, ax.size) for ax in pair}] == n3).array) - # check that the array outside the slice is unchanged - assert jnp.all( - ( - named1_updated[{ax.name: slice(ax.size, None) for ax in pair}] - == named1[{ax.name: slice(ax.size, None) for ax in pair}] - ).array - ) - - -def test_updated_slice_extra_update_axis_errors(): - H = Axis("H", 10) - W = Axis("W", 20) - D = Axis("D", 30) - - named1 = hax.random.randint(PRNGKey(0), (H, W, D), minval=0, maxval=10) - named2 = hax.random.randint(PRNGKey(0), (H, W, D), minval=10, maxval=30) - - with pytest.raises(ValueError): - named1.updated_slice({"H": 0, "W": 0, "D": 0, "extra": 0}, named2) - - with pytest.raises(ValueError): - named3 = hax.random.randint(PRNGKey(0), (H, W), minval=10, maxval=30) - named3.updated_slice({"H": 0, "W": 0}, named2) - - -def test_order_of_transpose_add(): - H = Axis("H", 10) - W = Axis("W", 20) - - named1 = hax.random.randint(PRNGKey(0), (H, W), minval=0, maxval=10) - named2 = hax.random.randint(PRNGKey(0), (W, H), minval=10, maxval=30) - - assert (named1 + named2).axes == (H, W) - assert jnp.all((named1 + named2).array == named1.array + named2.array.T) - - -def test_nice_short_string_in_named_array(): - H = Axis("H", 10) - W = Axis("W", 20) - - named1 = hax.random.randint(PRNGKey(0), (H, W), minval=0, maxval=10) - - assert str(named1).startswith("NamedArray(int32{'H': 10, 'W': 20}") - - -def test_nice_short_string_in_named_array_in_eqx_module(): - H = Axis("H", 10) - W = Axis("W", 20) - - named1 = hax.random.randint(PRNGKey(0), (H, W), minval=0, maxval=10) - - class TestModule(eqx.Module): - named1: NamedArray - - mod = TestModule(named1) - - assert str(mod).startswith("TestModule(named1=Named(int32{'H': 10, 'W': 20}))") - - -def test_named_arrays_work_in_eqxi_while_loop(): - H = Axis("H", 10) - W = Axis("W", 20) - - named1 = hax.random.uniform(PRNGKey(0), (H, W)) - - import equinox.internal as eqxi - - def body_fun(t): - i, named1 = t - return i + 1, named1 + named1 - - def cond_fun(t): - i, named1 = t - return i < 10 - - def loss_fun(named1): - i, named1 = eqxi.while_loop(cond_fun, body_fun, (0, named1), kind="checkpointed", max_steps=10) - return named1.sum().scalar() - - grad_fun = eqx.filter_value_and_grad(loss_fun) - - grad_fun(named1) - - -def test_at_for_in_placeish(): - H = Axis("H", 10) - W = Axis("W", 20) - - named1 = hax.random.uniform(PRNGKey(0), (H, W)) - - named1_at = named1.at[H, 0].set(0) - - assert jnp.all(jnp.equal(named1_at[H, 0].array, 0)) - assert jnp.all(named1_at[H, 1:].array == named1[H, 1:].array) - - # test add, multiply, power, etc. - named1_at = named1.at[H, 0].add(1) - assert jnp.all(named1_at.array == named1.array.at[0].add(1)) - - named1_at = named1.at[H, 0].multiply(2) - assert jnp.all(named1_at.array == named1.array.at[0].multiply(2)) - - named1_at = named1.at[H, 0].power(2) - assert jnp.all(named1_at.array == named1.array.at[0].power(2)) - - named1_at = named1.at[H, 0].divide(2) - assert jnp.all(named1_at.array == named1.array.at[0].divide(2)) - - named1_at = named1.at[H, 0].apply(hax.square) - assert jnp.all(named1_at.array == named1.array.at[0].apply(jnp.square)) - - named1_at = named1.at[H, 0].max(0.5) - assert jnp.all(named1_at.array == named1.array.at[0].max(0.5)) - - named1_at = named1.at[H, 0].min(0.5) - assert jnp.all(named1_at.array == named1.array.at[0].min(0.5)) - - -def test_at_with_fancy_indexing(): - H = Axis("H", 10) - W = Axis("W", 20) - I0 = Axis("I0", 5) - I1 = Axis("I1", 5) - - named1 = hax.random.uniform(PRNGKey(0), (H, W)) - ind1 = hax.random.randint(PRNGKey(0), (I0,), 0, H.size) - ind2 = hax.random.randint(PRNGKey(0), (I1,), 0, W.size) - - named1_at = named1.at[H, ind1].set(0) - assert jnp.all(named1_at.array == named1.array.at[ind1.array].set(0)) - - named1_at = named1.at[H, ind1].add(1, mode="clip") - assert jnp.all(named1_at.array == named1.array.at[ind1.array].add(1, mode="clip")) - - named1_at = named1.at[H, ind1, W, ind2].set(0) - assert jnp.all(named1_at.array == named1.array.at[ind1.array.reshape(-1, 1), ind2.array.reshape(1, -1)].set(0)) - - # dslices - from haliax import ds - - named1_at = named1.at[H, ds(3, 5)].set(0) - assert jnp.all(named1_at.array == named1.array.at[3:8].set(0)) - - named1_at = named1.at[H, ds(3, 5), W, ind2].power(2) - assert jnp.all(named1_at.array == named1.array.at[3:8, ind2.array].power(2)) - - -def test_slice_dslice_and_array(): - H = Axis("H", 10) - W = Axis("W", 20) - I0 = Axis("I0", 5) - - named1 = hax.random.uniform(PRNGKey(0), (H, W)) - ind2 = hax.random.randint(PRNGKey(0), (I0,), 0, W.size) - - from haliax import ds - - named1.array.at[3:8, ind2.array].add(jnp.full((5, 5), 2)) - - named1_at = named1.at[H, ds(3, 5), W, ind2].add(2) - assert jnp.all(named1_at.array == named1.array.at[3:8, ind2.array].add(2)) diff --git a/tests/test_attention.py b/tests/test_attention.py index b1faa47..bdb0c18 100644 --- a/tests/test_attention.py +++ b/tests/test_attention.py @@ -93,8 +93,7 @@ def test_alibi_attention_compared_to_hf(): import torch from transformers.models.bloom.modeling_bloom import build_alibi_tensor - L = hax.Axis("L", 128) - H = hax.Axis("NumHeads", 16) + L, H = hax.make_axes(L=1, H=16) # Returns tensor shaped (batch_size * num_heads, 1, max_seq_len) torch_tensor = ( @@ -107,7 +106,7 @@ def test_alibi_attention_compared_to_hf(): def test_fcm_attention_mask(): - KeyPos = hax.Axis("KeyPos", 20) + KeyPos, QueryPos, Head = hax.make_axes(KeyPos=20, QueryPos=10, Head=8) mask = forgetful_causal_mask(KeyPos, mask_prob=0.6, sample_prob=False, key=PRNGKey(0)) @@ -116,9 +115,6 @@ def test_fcm_attention_mask(): assert mask.astype(float).sum().item() <= KeyPos.size - QueryPos = hax.Axis("QueryPos", 10) - Head = hax.Axis("Head", 8) - query = hax.arange(QueryPos).broadcast_axis(Head) key = hax.arange(KeyPos).broadcast_axis(Head) diff --git a/tests/test_axis.py b/tests/test_axis.py index ae8f689..4d9eb0f 100644 --- a/tests/test_axis.py +++ b/tests/test_axis.py @@ -1,12 +1,10 @@ import pytest -from haliax.axis import Axis, eliminate_axes, rearrange_for_partial_order +from haliax.axis import Axis, eliminate_axes, make_axes, rearrange_for_partial_order def test_eliminate_axes(): - H = Axis("H", 3) - W = Axis("W", 4) - C = Axis("C", 5) + H, W, C = make_axes(H=3, W=4, C=5) assert eliminate_axes((H, W), (H,)) == (W,) assert eliminate_axes((H, W), (W,)) == (H,) diff --git a/tests/test_einsum.py b/tests/test_einsum.py index 992bf6c..ca909bb 100644 --- a/tests/test_einsum.py +++ b/tests/test_einsum.py @@ -273,12 +273,7 @@ def test_einsum_various_errors(): def test_einsum_examples(): - - Batch = hax.Axis("batch", 32) - Embed = hax.Axis("embed", 64) - H = hax.Axis("h", 16) - W = hax.Axis("w", 16) - C = hax.Axis("c", 3) + Batch, Embed, H, W, C = hax.make_axes(batch=32, embed=64, h=16, w=16, c=3) # for jax im = jnp.zeros((32, 16, 16, 3)) diff --git a/tests/test_nn.py b/tests/test_nn.py index 83e91f3..08809b7 100644 --- a/tests/test_nn.py +++ b/tests/test_nn.py @@ -46,8 +46,7 @@ def test_dropout(): def test_one_hot(): - i = Axis("i", 3) - c = Axis("c", 3) + i, c = hax.make_axes(i=3, c=3) actual = hax.nn.one_hot(hax.NamedArray(jnp.array([0, 1, 2]), (i,)), c) expected = jnp.array([[1.0, 0.0, 0.0], [0.0, 1.0, 0.0], [0.0, 0.0, 1.0]]) @@ -61,16 +60,14 @@ def test_one_hot(): def test_one_hot_out_of_bound(): - i = Axis("i", 2) - c = Axis("c", 3) + i, c = hax.make_axes(i=2, c=3) actual = hax.nn.one_hot(hax.NamedArray(jnp.array([-1, 3]), (i,)), c) expected = jnp.array([[0.0, 0.0, 0.0], [0.0, 0.0, 0.0]]) assert jnp.all(jnp.isclose(actual.array, expected)) def test_standardize(): - b = Axis("b", 2) - c = Axis("c", 3) + b, c = hax.make_axes(b=2, c=3) actual = hax.nn.standardize(hax.NamedArray(jnp.array([0, 1, 2]), (c,)), c) expected = jax.nn.standardize(jnp.array([0, 1, 2]), axis=0) @@ -113,11 +110,7 @@ def test_standardize(): @pytest.mark.parametrize("depth", [0, 1, 2, 3, 4, 5]) def test_mlp(depth): key = jrandom.PRNGKey(0) - H = Axis("H", 10) - C = Axis("C", 12) - W = Axis("W", 14) - - E = Axis("E", 16) + H, C, W, E = hax.make_axes(H=10, C=12, W=14, E=16) hax_mlp = hax.nn.MLP.init((H, C, W), E, width=8, depth=depth, key=key) x = hax.random.uniform(key, (H, C, W)) @@ -150,10 +143,7 @@ def test_mlp(depth): def test_linear_has_no_function_leaves_by_default(): - H = Axis("H", 10) - C = Axis("C", 12) - W = Axis("W", 14) - E = Axis("E", 16) + H, C, W, E = hax.make_axes(H=10, C=12, W=14, E=16) hax_linear = hax.nn.Linear.init((H, C, W), E, key=jrandom.PRNGKey(0)) assert all(not isinstance(v, Callable) for v in jax.tree_util.tree_leaves(hax_linear)) # type: ignore diff --git a/tests/test_rearrange.py b/tests/test_rearrange.py index 0e0dbf8..0d84e95 100644 --- a/tests/test_rearrange.py +++ b/tests/test_rearrange.py @@ -7,11 +7,7 @@ from haliax._src.rearrange import einops_rearrange # some axes -W = Axis("W", 4) -H = Axis("H", 6) -C = Axis("C", 3) -D = Axis("D", 2) -B = Axis("B", 5) +H, W, C, D, B = hax.make_axes(H=6, W=4, C=3, D=2, B=5) Q = hax.Axis("Q", B.size * H.size) E = Axis("E", H.size * W.size * D.size) diff --git a/tests/test_specialized_fns.py b/tests/test_specialized_fns.py index dbc1449..3b13bef 100644 --- a/tests/test_specialized_fns.py +++ b/tests/test_specialized_fns.py @@ -1,14 +1,13 @@ import jax import jax.numpy as jnp +import haliax import haliax.specialized_fns as hfns -from haliax import Axis, NamedArray +from haliax import NamedArray def test_top_k(): - H = Axis("H", 5) - W = Axis("W", 6) - D = Axis("D", 7) + H, W, D = haliax.make_axes(H=3, W=4, D=5) rand = jax.random.uniform(jax.random.PRNGKey(0), (H.size, W.size, D.size)) n_rand = NamedArray(rand, (H, W, D)) diff --git a/tests/test_tree_util.py b/tests/test_tree_util.py index 8fb4c54..4ad7f55 100644 --- a/tests/test_tree_util.py +++ b/tests/test_tree_util.py @@ -11,10 +11,7 @@ from haliax import Axis def test_resize_axis(): - - A = hax.Axis("A", 10) - B = hax.Axis("B", 20) - C = hax.Axis("C", 30) + A, B, C = hax.make_axes(A=10, B=20, C=30) class Module(eqx.Module): name1: hax.NamedArray commit 019fa2d9f8522bafb77c6957987973e3d2914282 Date: 2024-09-05T13:58:11-07:00 add an example of make_axes to readme diff --git a/README.md b/README.md index a91db2e..cafa01e 100644 --- a/README.md +++ b/README.md @@ -47,6 +47,9 @@ Head = hax.Axis("head", 8) # number of attention heads Key = hax.Axis("key", 64) # key size Embed = hax.Axis("embed", 512) # embedding size +# alternatively: +#Pos, KPos, Head, Key, Embed = hax.make_axes(pos=1024, key_pos=1024, head=8, key=64, embed=512) + def attention_scores(Key, KPos, query, key, mask): # how similar is each query to each key commit 11689bd55b3cacc7bf61eb9e5cca5d0a0e442453 Date: 2024-09-07T22:47:01-07:00 Rename overlapping_axes -> intersect_axes & make overlapping_axes instead the intersection of names (#110) * Renamed overlapping_axes -> intersect_axes * Added overlapping_axes (like intersect_axes but for names) and a test for it * Added overlapping_axes to api.md and __all__ in axis.py --------- Co-authored-by: David Hall <dlwh@cs.stanford.edu> diff --git a/docs/api.md b/docs/api.md index 743a97a..2f47106 100644 --- a/docs/api.md +++ b/docs/api.md @@ -31,10 +31,11 @@ Occasionally, an axis size can be inferred in some circumstances but not others. ::: haliax.axis.axis_name ::: haliax.axis.concat_axes ::: haliax.axis.union_axes +::: haliax.axis.intersect_axes ::: haliax.axis.eliminate_axes ::: haliax.axis.without_axes -::: haliax.axis.overlapping_axes ::: haliax.axis.selects_axis +::: haliax.axis.overlapping_axes ::: haliax.axis.is_axis_compatible diff --git a/src/haliax/axis.py b/src/haliax/axis.py index 49463c9..1268659 100644 --- a/src/haliax/axis.py +++ b/src/haliax/axis.py @@ -297,21 +297,21 @@ def replace_axis(axis_spec: AxisSelection, old: AxisSelector, new: AxisSelection @overload -def overlapping_axes(ax1: AxisSpec, ax2: AxisSelection) -> Tuple[Axis, ...]: +def intersect_axes(ax1: AxisSpec, ax2: AxisSelection) -> Tuple[Axis, ...]: ... @overload -def overlapping_axes(ax1: AxisSelection, ax2: AxisSpec) -> Tuple[Axis, ...]: +def intersect_axes(ax1: AxisSelection, ax2: AxisSpec) -> Tuple[Axis, ...]: ... @overload -def overlapping_axes(ax1: AxisSelection, ax2: AxisSelection) -> Tuple[AxisSelector, ...]: +def intersect_axes(ax1: AxisSelection, ax2: AxisSelection) -> Tuple[AxisSelector, ...]: ... -def overlapping_axes(ax1: AxisSelection, ax2: AxisSelection) -> Tuple[AxisSelector, ...]: +def intersect_axes(ax1: AxisSelection, ax2: AxisSelection) -> Tuple[AxisSelector, ...]: """Returns a tuple of axes that are present in both ax1 and ax2. The returned order is the same as ax1. """ @@ -339,6 +339,23 @@ def overlapping_axes(ax1: AxisSelection, ax2: AxisSelection) -> Tuple[AxisSelect return tuple(out) +def overlapping_axes(ax1: AxisSelection, ax2: AxisSelection) -> Tuple[str, ...]: + """ + Like intersect_axes, but returns the names instead of the axes themselves. + Unlike intersect_axes, it does not throw an error if the sizes of a common axis are + different. + + The returned order is the same as in ax1. + """ + ax1 = ensure_tuple(ax1) + ax2 = ensure_tuple(ax2) + ax1_names = map(axis_name, ax1) + ax2_names = set(map(axis_name, ax2)) + + out = tuple(name for name in ax1_names if name in ax2_names) + return out + + @overload def axis_name(ax: AxisSelector) -> str: # type: ignore ... @@ -555,6 +572,7 @@ __all__ = [ "dslice", "dblock", "eliminate_axes", + "intersect_axes", "is_axis_compatible", "overlapping_axes", "replace_axis", diff --git a/src/haliax/core.py b/src/haliax/core.py index 264097d..536c8d4 100644 --- a/src/haliax/core.py +++ b/src/haliax/core.py @@ -689,9 +689,9 @@ def take(array: NamedArray, axis: AxisSelector, index: Union[int, NamedArray]) - remaining_axes = eliminate_axes(array.axes, axis) # axis order is generally [array.axes[:axis_index], index.axes, array.axes[axis_index + 1 :]] # except that index.axes may overlap with array.axes - overlapping_axes: AxisSpec = haliax.axis.overlapping_axes(remaining_axes, index.axes) + intersecting_axes: AxisSpec = haliax.axis.intersect_axes(remaining_axes, index.axes) - if overlapping_axes: + if intersecting_axes: # if the eliminated axis is also in the index, we rename it to a dummy axis that we can broadcast over it need_to_use_dummy_axis = index._lookup_indices(axis.name) is not None if need_to_use_dummy_axis: diff --git a/tests/test_axis.py b/tests/test_axis.py index 4d9eb0f..d7a9def 100644 --- a/tests/test_axis.py +++ b/tests/test_axis.py @@ -1,6 +1,6 @@ import pytest -from haliax.axis import Axis, eliminate_axes, make_axes, rearrange_for_partial_order +from haliax.axis import Axis, eliminate_axes, make_axes, overlapping_axes, rearrange_for_partial_order def test_eliminate_axes(): @@ -133,3 +133,17 @@ def test_duplicate_elements_errors(): with pytest.raises(ValueError): rearrange_for_partial_order(partial_order, candidates) + + +def test_overlapping_axes_with_different_sizes(): + A1 = Axis("A", 10) + A2 = Axis("A", 12) + B = Axis("B", 14) + C = Axis("C", 16) + D = Axis("D", 18) + + ax1 = (A1, B, C) + ax2 = (A2, C, D) + + overlapping_names = overlapping_axes(ax1, ax2) # Should not error + assert overlapping_names == ("A", "C") commit 30e3217fce7284c7d3392dcfae8723c6f2d88ef2 Date: 2024-09-14T22:39:14-07:00 allow ellipses in output-only einsum diff --git a/src/haliax/_src/einsum.py b/src/haliax/_src/einsum.py index 6a65f44..326b1d7 100644 --- a/src/haliax/_src/einsum.py +++ b/src/haliax/_src/einsum.py @@ -121,10 +121,13 @@ def _output_only_named_einsum(equation, arrays, rhs, axis_aliases): used_aliases = set() input_axis_names = set(ax.name for ax in _all_input_axes(arrays)) + has_ellipsis = False for capture in rhs.captures: if capture is Ellipsis: - raise_parse_error("Can't use ellipsis on the rhs of an einsum without an lhs", equation, None) + # raise_parse_error("Can't use ellipsis on the rhs of an einsum without an lhs", equation, None) + out_axes.append(Ellipsis) + has_ellipsis = True elif capture.binding is None or len(capture.axes) > 1: raise_parse_error( "Parenthesized axes are not currently supported in the output of an einsum", @@ -150,7 +153,6 @@ def _output_only_named_einsum(equation, arrays, rhs, axis_aliases): ) name = ax_name - used_axes.add(name) if name in out_axes: raise_parse_error( @@ -160,8 +162,18 @@ def _output_only_named_einsum(equation, arrays, rhs, axis_aliases): if name not in input_axis_names: raise_parse_error(f"Axis {name} not found in any of the input arrays", equation, capture.char_range) + used_axes.add(name) out_axes.append(name) + # if there's an ellipsis, put all unused axes in the ellipsis + if has_ellipsis: + all_input_axes = _all_input_axes(arrays) + unmentioned = [ax.name for ax in all_input_axes if ax.name not in used_axes] + ellipsis_index = out_axes.index(Ellipsis) + out_axes = out_axes[:ellipsis_index] + unmentioned + out_axes[ellipsis_index + 1 :] + + used_axes = set(out_axes) + _check_for_unused_aliases(axis_aliases, used_aliases, equation) spec = _make_einsum_spec(arrays, out_axes) diff --git a/tests/test_einsum.py b/tests/test_einsum.py index ca909bb..6790fee 100644 --- a/tests/test_einsum.py +++ b/tests/test_einsum.py @@ -330,6 +330,12 @@ def test_einsum_output_only_mode(): assert jnp.all(jnp.equal(einsum("-> Height Width", m1, m2).array, jnp.einsum("ijk,kji->ij", m1.array, m2.array))) assert jnp.all(jnp.equal(einsum("-> Height", m1).array, jnp.einsum("ijk->i", m1.array))) + assert jnp.all(jnp.equal(einsum("-> ...", m1, m2).array, jnp.einsum("ijk,kji->ijk", m1.array, m2.array))) + assert jnp.all(jnp.equal(einsum("-> ... Width", m1, m2).array, jnp.einsum("ijk,kji->ikj", m1.array, m2.array))) + assert jnp.all( + jnp.equal(einsum("-> Depth ... Width", m1, m2).array, jnp.einsum("ijk,kji->kij", m1.array, m2.array)) + ) + with pytest.raises(ValueError): einsum("-> Q Width", m1) commit 2afcf5e35a09e51c730c86e0d5e7c5a8d25b2190 Date: 2024-09-14T22:59:13-07:00 can use ellipsis diff --git a/tests/test_einsum.py b/tests/test_einsum.py index 6790fee..c059b10 100644 --- a/tests/test_einsum.py +++ b/tests/test_einsum.py @@ -250,9 +250,6 @@ def test_einsum_various_errors(): m1 = hax.ones((Height, Hidth, Depth)) m2 = hax.ones((Depth, Hidth, Height)) - with pytest.raises(ValueError, match="Can't use ellipsis"): - einsum("-> ...", m1, m2) - with pytest.raises(ValueError, match="multiple times"): einsum("-> Height Height", m1, m2) commit b131795ae83f3f28a0234bc3e130d4396423ac7b Date: 2024-11-06T09:37:44-08:00 Move StateDict to Haliax, clean it up a lot. (#90) Closes #35 diff --git a/docs/indexing.md b/docs/indexing.md index d9669da..e4f839d 100644 --- a/docs/indexing.md +++ b/docs/indexing.md @@ -72,7 +72,7 @@ can use [haliax.where][] for most of the same functionality, though. Before we continue, a note on shapes in JAX. Most JAX code will be used inside `jit`, which means that the sizes of all arrays must be determined at compile time (i.e. when JAX interprets your functions abstractly). This is a hard -requirement in XLA. It might worked around one day, but it's the way things are for now. +requirement in XLA. A consequence of this restriction is that certain indexing patterns aren't allowed in `jit`-ed JAX code: @@ -97,10 +97,31 @@ f(jnp.arange(10), 2) ``` This is a not-uncommon pattern in situations where you want to process a large array in chunks. In Haliax, we provide -two solutions: [haliax.slice][] as well as dynamic slices ([haliax.dslice][] a.k.a. [haliax.ds][]). +two solutions: [haliax.slice][] and dynamic slices ([haliax.dslice][] a.k.a. [haliax.ds][]). ## Dynamic Slices +[haliax.slice][] is a convenience function that wraps `jax.lax.dynamic_slice` and allows you to slice an array with a +dynamic start and size. This is useful for situations where you need to slice an array in a way that can't be determined +at compile time. For example, the above example can be written as follows: + +```python +import jax + +import haliax as hax + +N = hax.Axis("N", 10) +q = hax.arange(N) + +@hax.named_jit +def f(x, slice_size: int): + num_blocks = N.size // slice_size + def body(i, m): + return i + hax.mean(hax.slice(x, {"N": i * slice_size}, {"N": slice_size})) + jax.lax.fori_loop(0, num_blocks, body, 0.0) +``` + + In light of the requirement that all array sizes be known at compile time, Haliax provides both a simple [haliax.slice][] function, as well as [haliax.dslice][], which can be used with `[]`. The simple slice function is just a wrapper around [jax.lax.dynamic_slice][]] and not worth discussing here. diff --git a/docs/matmul.md b/docs/matmul.md index 531e326..53391ea 100644 --- a/docs/matmul.md +++ b/docs/matmul.md @@ -62,7 +62,7 @@ y = hax.dot(x, w, c, axis=(), out_axes=(D, ..., H)) # shape is (D, W, C, H), eq [haliax.einsum][] is at its best when you want to express a more complex tensor contraction. It is similar to [numpy.einsum](https://numpy.org/doc/stable/reference/generated/numpy.einsum.html) or [einops.einsum](https://einops.rocks/api/einsum/) in terms of syntax and behavior, -but extended to work with named axes, including added flexibility that named axes provide. +but extended to work with named axes, including the added flexibility that named axes provide. Our "flavor" of `einsum` is most similar to `einops.einsum`'s flavor, in that it supports long names for axes (like `"batch h w, h w channel -> batch channel"`) rather than the compact notation of `numpy.einsum` (like `"bhwc,hwc->bc"`). diff --git a/docs/state-dict.md b/docs/state-dict.md new file mode 100644 index 0000000..7cdc54e --- /dev/null +++ b/docs/state-dict.md @@ -0,0 +1,160 @@ +# Serialization + +Haliax supports serialization of modules (including any [equinox.Module][]) to and from PyTorch-compatible +state dicts using the [safetensors](https://github.com/huggingface/safetensors) library. For details on +how state dicts work in PyTorch, see the [PyTorch documentation](https://pytorch.org/docs/stable/notes/serialization.html#saving-and-loading-torch-nn-modules). + +A state dict is a Python dictionary that maps string keys to tensors. It is used to store the parameters +of a model (though typically not the model's structure or hyperparameters). The keys are typically the names of the +model's parameters, arranged as `.`-separated paths. For example, a model with a `conv1` layer might have a +state dict with keys like `conv1.weight` and `conv1.bias`. Sequences of modules (e.g., for lists of layers) are +serialize with keys like `layer.0.weight`, `layer.1.weight`, etc. + +Haliax uses the [safetensors](https://github.com/huggingface/safetensors) library to serialize state dicts. This +library is a safer, more portable format developed by Hugging Face. Serializing a native PyTorch state dict requires +PyTorch itself, and we want to avoid that dependency. Also, PyTorch uses pickles, which are in general not +safe to deserialize from untrusted sources. + +This does mean that you can't directly load a Haliax state dict into PyTorch, but safetensors is lightweight and +easy to use. Hugging Face natively supports it in their libraries. + +## Saving a State Dict + +To serialize a module to a Pytorch-compatible state dict, use the [haliax.state_dict.to_torch_compatible_state_dict][] +function. This function takes a module and returns a state dict. To save the state dict to a file, use the +[haliax.state_dict.save_state_dict][] function, which writes the state dict to a file in safetensor format. +`to_torch_compatible_state_dict` flattens [haliax.nn.Linear] module input and output axis specs to a format that +is compatible with PyTorch Linear modules (though `out_first=True` is necessary to match PyTorch's Linear module). + +```python +import haliax +import jax.random as jrandom + +# Create a module +Heads = haliax.Axis("Heads", 8) +Dim = haliax.Axis("Dim", 16) +Out = haliax.Axis("Out", 5) +module = haliax.nn.Linear.init(In=(Heads, Dim), Out=Out, key=jrandom.PRNGKey(0)) + +# Serialize the module to a state dict +state_dict = haliax.state_dict.to_torch_compatible_state_dict(module) + +# Save the state dict to a file +haliax.state_dict.save_state_dict(state_dict, 'state_dict.safetensors') +``` + +Note that the state dict is saved in the [safetensors](https://github.com/huggingface/safetensors) format, which +is a safer, more portable format developed by Hugging Face. To load a model from a state dict in PyTorch, you +can use safetensors directly. + +```python +import torch +from safetensors.torch import load_model + +model = torch.nn.Linear(10, 5) + +# Load the state dict from a file +state_dict = load_model(model, 'state_dict.safetensors') +``` + +## Loading a State Dict + +Similarly, you can load a state dict from a file using the [haliax.state_dict.load_state_dict][] function. This +function reads a state dict from a file in safetensors format and returns a dictionary. To load the state dict +into a module, use the [haliax.state_dict.from_torch_compatible_state_dict][] function. + +```python +import haliax as hax +import jax.random as jrandom + +# Create a module +Heads = hax.Axis("Heads", 8) +Dim = hax.Axis("Dim", 16) +Out = hax.Axis("Out", 5) +module = hax.nn.Linear.init(In=(Heads, Dim), Out=Out, key=jrandom.PRNGKey(0)) + +# Load the state dict from a file +state_dict = hax.state_dict.load_state_dict('state_dict.safetensors') + +# this will unflatten the state dict and load it into the module +module = hax.state_dict.from_torch_compatible_state_dict(module, state_dict) +``` + +The `from_torch_compatible_state_dict` function will unflatten the state dict and load it into the module. Note +that the module must have the same structure as the module that was serialized to the state dict. If the module +structure has changed, you may need to manually update the state dict keys to match the new structure. + + +## Customizing Serialization + +### Changing the State Dict Key Names + +If for some reason you want to use different names in the serialized state dict (e.g. because you +chose to use different names from a Hugging Face implementation), you can extend your class from [haliax.state_dict.ModuleWithStateDictSerialization][] +and use `_state_dict_key_map` to rename keys. For instance, the `Gpt2Transformer` class in Levanter has this method: + +```python +from typing import Optional +from haliax.state_dict import ModuleWithStateDictSerialization + +class Gpt2Transformer(ModuleWithStateDictSerialization): + ... + + def _state_dict_key_map(self) -> dict[str, Optional[str]]: + return {"blocks": "h"} +``` + +This says that the field called `blocks` in this class should be (de)serialized as `h`, +because the Hugging Face GPT-2 implementation uses `h`, which is not very clear. +You can also "flatten" the submodules of a field by using `None`. + +### Custom Serialization Logic + +If your modules need fancier special logic, you'll need to extend your class from `ModuleWithStateDictSerialization` and +override the default functions `to_state_dict()` and `from_state_dict()`. It takes in and returns a modified +[haliax.state_dict.StateDict][]. As of June 2024, we almost never this in Levanter. + +For implementation, there are a few helper methods from `haliax.state_dict` that you can use: +- To join specific prefix to the keys of Hugging Face state_dict, you can use the helper function `with_prefix()`. + The prefix comes from the name of attributes defined at the beginning of your model class. + +For example, below is the implementation of `to_state_dict()` in [levanter.models.backpack.BackpackLMHeadModel][]. +In this class, we want to preserve HF compatibility by saving untied output embeddings. (We chose not to implement +non-weight-tied embeddings.) + +```python +from typing import Optional + +from haliax.state_dict import with_prefix, StateDict + + +class BackpackLMHeadModel(ModuleWithStateDictSerialization): + ... + + def to_state_dict(self, prefix: Optional[str] = None) -> StateDict: + state_dict = super().to_state_dict(prefix=prefix) + # In levanter's implementation, we have a shared embedding matrix for both the word + # embeddings and the sense embeddings + state_dict[with_prefix(prefix, "backpack.word_embeddings.weight")] = state_dict[ + with_prefix(prefix, "backpack.gpt2_model.wte.weight") + ] + state_dict[with_prefix(prefix, "backpack.position_embeddings.weight")] = state_dict[ + with_prefix(prefix, "backpack.gpt2_model.wpe.weight") + ] + return state_dict +``` + +Similarly, to load weights from the state dict, you might need to implement `from_state_dict`. This function +takes in a state dict and the module with the updated weights. You can use the `with_prefix()` helper function +to join the prefix to the keys of the state dict. + +```python + def from_state_dict(self, state_dict: StateDict, prefix: Optional[str] = None) -> T: + ... + + +``` + +## API Reference + +::: haliax.state_dict diff --git a/mkdocs.yml b/mkdocs.yml index d90c971..3e194a9 100644 --- a/mkdocs.yml +++ b/mkdocs.yml @@ -88,5 +88,6 @@ nav: - Partitioning: 'partitioning.md' - Higher Order Functions: 'hof.md' - FP8: 'fp8.md' + - Serialization: 'state-dict.md' - API Reference: 'api.md' - FAQ: 'faq.md' diff --git a/pyproject.toml b/pyproject.toml index 4b1d0f7..1d40bf8 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -26,6 +26,7 @@ dependencies = [ "equinox>=0.10.6", "jaxtyping>=0.2.20", "jmp>=0.0.4", + "safetensors>=0.4.3" ] dynamic =[ "version" ] @@ -68,3 +69,4 @@ src_paths = ["src", "tests"] [project.urls] "Homepage" = "https://github.com/stanford-crfm/haliax" "Bug Tracker" = "https://github.com/stanford-crfm/haliax/issues/" +"Documentation" = "https://haliax.readthedocs.io/en/latest/" diff --git a/src/haliax/__init__.py b/src/haliax/__init__.py index 6a35ab9..c39fec6 100644 --- a/src/haliax/__init__.py +++ b/src/haliax/__init__.py @@ -14,6 +14,7 @@ import haliax.debug as debug import haliax.nn as nn import haliax.quantization as quantization import haliax.random as random +import haliax.state_dict as state_dict import haliax.tree_util as tree_util import haliax.util as util @@ -890,6 +891,7 @@ __all__ = [ "random", "tree_util", "nn", + "state_dict", "Axis", "AxisSpec", "AxisSelection", diff --git a/src/haliax/_src/einsum.py b/src/haliax/_src/einsum.py index 326b1d7..674e079 100644 --- a/src/haliax/_src/einsum.py +++ b/src/haliax/_src/einsum.py @@ -9,6 +9,7 @@ import haliax from ..axis import Axis, AxisSelector, axis_name, eliminate_axes, rearrange_for_partial_order, union_axes from ..core import NamedArray from ..jax_utils import _jittable_dg_einsum +from ..quantization import DotGeneralOp from ..types import DTypeLike, PrecisionLike from ..util import ensure_tuple from .parsing import AliasTable, parse_einsum, raise_parse_error @@ -19,8 +20,8 @@ def einsum( *arrays: NamedArray, precision: PrecisionLike = None, preferred_element_type: Optional[DTypeLike] = None, - _dot_general=jax.lax.dot_general, - **axis_aliases, + _dot_general: DotGeneralOp = jax.lax.dot_general, + **axis_aliases: AxisSelector, ) -> NamedArray: """Compute the tensor contraction of the input arrays according to Haliax's named variant of the Einstein summation convention. diff --git a/src/haliax/_src/state_dict.py b/src/haliax/_src/state_dict.py new file mode 100644 index 0000000..06c5444 --- /dev/null +++ b/src/haliax/_src/state_dict.py @@ -0,0 +1,433 @@ +# Module to support torch-style "state dict" serialization via safetensors +import dataclasses +import typing +from typing import Any, Optional, Sequence, TypeVar + +import equinox as eqx +import jax +import jax.numpy as jnp +import numpy as np +from jax import ShapeDtypeStruct +from jax.experimental.multihost_utils import sync_global_devices +from jax.sharding import Mesh, NamedSharding, PartitionSpec +from jax.tree_util import DictKey, FlattenedIndexKey, GetAttrKey, SequenceKey +from jaxtyping import PyTree + +import haliax.partitioning as partitioning +from haliax._src.util import index_where +from haliax.core import NamedArray, named +from haliax.jax_utils import is_jax_array_like + + +try: + import safetensors +except ImportError: + safetensors = None + + +StateDict = dict[str, Any] +Mod = TypeVar("Mod", bound=eqx.Module) +T = TypeVar("T") + + +def from_torch_compatible_state_dict( + t: T, state_dict: StateDict, *, unflatten_linear: bool = True, prefix: Optional[str] = None +) -> T: + """ + Convert a state dict to a tree that is compatible with the structure of `t`. + + This applies [haliax.state_dict.from_state_dict][] followed by [haliax.state_dict.unflatten_linear_layers][]. + """ + if unflatten_linear: + t = _flatten_to_unflatten(t, state_dict, prefix) + else: + t = from_state_dict(t, state_dict, prefix=prefix) + + return t + + +def _flatten_to_unflatten(t, state_dict, prefix): + """ + Flatten the torch compatible state_dict before loading into t, and then recover the unflattened layers. + """ + # typically, `t` is a bunch of ShapeDtypeStructs, which can't be transposed etc. so we instead have to zeros() + # into real arrays (that aren't actually real b/c this is inside a jit) + def _dt_struct_to_array(struct): + if not isinstance(struct, ShapeDtypeStruct): + return struct + return jnp.zeros(struct.shape, struct.dtype) + + t = jax.tree.map(_dt_struct_to_array, t) + flat_t = flatten_linear_layers(t) + flat_t = from_state_dict(flat_t, state_dict, prefix=prefix) + t = unflatten_linear_layers(t, flat_t) + return t + + +@typing.overload +def with_prefix(prefix: str | None, leaf: str) -> str: + ... + + +@typing.overload +def with_prefix(prefix: str, leaf: None) -> str: + ... + + +@typing.overload +def with_prefix(prefix: Optional[str], leaf: Optional[str]) -> Optional[str]: + ... + + +def with_prefix(prefix: Optional[str], leaf: Optional[str]) -> Optional[str]: + """Joins two optional path strings in a way compatible with pytorch state dict serialization""" + if prefix is None: + return leaf + elif leaf is None: + return prefix + else: + return f"{prefix}.{leaf}" + + +class ModuleWithStateDictSerialization(eqx.Module): + """An eqx.Module that can be serialized to a torch-style state dict.""" + + def to_state_dict(self, prefix: Optional[str] = None) -> StateDict: + return default_eqx_module_to_state_dict(self, prefix) + + def from_state_dict(self: Mod, state_dict: StateDict, prefix: Optional[str] = None) -> Mod: + return default_eqx_module_from_state_dict(self, state_dict, prefix) + + def _state_dict_key_map(self) -> dict[str, Optional[str]]: + """Returns a dict mapping eqx.Module keys to torch keys that need to be renamed for serialization""" + return {} + + +def from_state_dict(tree: T, state_dict: StateDict, prefix: Optional[str] = None) -> T: + """ + Given a (template) tree and a state dict, return a new tree with the same structure as the input tree, but with + the values from the state dict. + + Args: + tree: The template tree + state_dict: The state dict + prefix: The prefix to use when looking up keys in the state dict + + Returns: + A new tree with the same structure as the input tree, but with the values from the state dict. + + """ + # TODO: assert compatibility of old and new values (type, shape, etc.) + if isinstance(tree, eqx.Module): + if hasattr(tree, "from_state_dict"): + return tree.from_state_dict(state_dict, prefix) + else: + return default_eqx_module_from_state_dict(tree, state_dict, prefix) + elif isinstance(tree, list): + return [from_state_dict(item, state_dict, with_prefix(prefix, str(i))) for i, item in enumerate(tree)] # type: ignore + elif isinstance(tree, dict): + return {k: from_state_dict(v, state_dict, prefix=with_prefix(prefix, k)) for k, v in tree.items()} # type: ignore + elif isinstance(tree, NamedArray): + if prefix is None: + raise ValueError("Cannot extract a leaf value from a torch dict without a prefix") + + array = state_dict[prefix] + + if isinstance(array, np.ndarray): + mesh = partitioning._get_mesh() + # TODO: modernize this + if mesh.devices.size > 1: # this happens with the default mesh + pspec = partitioning.pspec_for_axis(tree.axes) + sharding = jax.sharding.NamedSharding(mesh, pspec) + array = jax.make_array_from_callback(tree.array.shape, sharding, lambda indices: array[indices]) + else: + array = jnp.array(array) + array = named(array, tree.axes) + else: + array = named(array, tree.axes) + array = partitioning.auto_sharded(array) + + return array + elif is_jax_array_like(tree): + if prefix is None: + raise ValueError("Cannot extract a leaf value from a state dict without a prefix") + # TODO: add "strict" flag so we can return None in cases where it's just missing + return jnp.array(state_dict[prefix]) + else: + if prefix is None: + return tree + return state_dict.get(prefix, tree) + + +def to_state_dict(tree: PyTree, prefix: Optional[str] = None) -> StateDict: + """ + Convert a PyTree to a state dict. + + Returns: + The state dict representation of the input tree. + """ + if isinstance(tree, eqx.Module): + if hasattr(tree, "to_state_dict"): + state_dict = tree.to_state_dict(prefix) + else: + state_dict = default_eqx_module_to_state_dict(tree, prefix) + elif isinstance(tree, list): + state_dict = {} + for i, item in enumerate(tree): + child = to_state_dict(item, prefix=with_prefix(prefix, str(i))) + # TODO: check for conflicts? + state_dict.update(child) + elif isinstance(tree, dict): + state_dict = {} + for k, v in tree.items(): + child = to_state_dict(v, prefix=with_prefix(prefix, k)) + # TODO: check for conflicts? + state_dict.update(child) + elif isinstance(tree, NamedArray): + if prefix is None: + raise ValueError("Cannot convert a leaf value to a state dict without a prefix") + if tree.array is not None: + state_dict = {prefix: tree.array} + else: + state_dict = {} + elif is_jax_array_like(tree): + if prefix is not None: + if tree is not None: + state_dict = {prefix: tree} + else: + state_dict = {} + else: + raise ValueError("Cannot convert a leaf value to a state dict without a prefix") + else: + raise ValueError(f"Unsupported type {type(tree)}") + + return state_dict + + +def default_eqx_module_from_state_dict(mod: Mod, state_dict: StateDict, prefix: Optional[str] = None) -> Mod: + key_map: Dict[str, Optional[str]] = getattr(mod, "_state_dict_key_map", lambda: {})() # type: ignore + names = [] + values = [] + for field in dataclasses.fields(mod): + # only encode dynamic fields (i.e. fields that don't have the static flag) + if field.metadata.get("static", False): + continue + key = key_map.get(field.name, field.name) + value = getattr(mod, field.name) + # TODO: might want to add a flag that allows missing keys? + new = from_state_dict(value, state_dict, with_prefix(prefix, key)) + # Do not try to update parameters that are never defined + if value is None and new is None: + continue + names.append(field.name) + values.append(new) + return eqx.tree_at(lambda m: [getattr(m, name) for name in names], mod, values) + + +def default_eqx_module_to_state_dict(mod: eqx.Module, prefix: Optional[str] = None) -> StateDict: + """ + Convert an eqx.Module to a state dict. This is the default implementation of the to_state_dict method for + eqx.Modules. It works by iterating over the fields of the module and calling to_state_dict on each field. + Args: + mod: + prefix: + + Returns: + + """ + state_dict: StateDict = {} + key_map: Dict[str, Optional[str]] = getattr(mod, "_state_dict_key_map", lambda: {})() # type: ignore + for field in dataclasses.fields(mod): + if field.metadata.get("static", False): + continue + key = key_map.get(field.name, field.name) + value = getattr(mod, field.name) + child = to_state_dict(value, with_prefix(prefix, key)) + # TODO: should we check for conflicts? + state_dict.update(child) + return state_dict + + +def format_path_for_state_dict(prefix: Optional[str], path: Sequence) -> str: + res = "".join(_format_key_path_element(path_elem) for path_elem in path) + # res will have a . + if prefix is not None: + res = f"{prefix}{res}" + elif res.startswith("."): + res = res[1:] + + return res + + +# Torch compatible KeyPath formatting. Torch just always uses . +def _format_key_path_element(path_elem) -> str: + match path_elem: + case SequenceKey(idx): # type: ignore + return f".{idx}" + case DictKey(key): # type: ignore + return f".{key}" + case GetAttrKey(): # type: ignore + return str(path_elem) + case FlattenedIndexKey(idx): # type: ignore + return f".{idx}" + case _: + # The convention in JAX is to append the separator in the element itself + # so we expect it to have + path_elem = str(path_elem) + if path_elem.startswith("."): + return path_elem + else: + return f".{path_elem}" + + +def to_numpy_state_dict(model, prefix: Optional[str] = None) -> StateDict: + """ + Convert a model to a state dict by first creating desharded copies of all parameters that reside in CPU + memory. + + This method is especially useful for saving models distributed across multiple hosts. + """ + + with jax.default_device(jax.local_devices(backend="cpu")[0]): + + def get_to_cpu(arr): + if not is_jax_array_like(arr): + return arr + elif isinstance(arr, np.ndarray): + return arr + elif arr.is_fully_addressable: + r = np.array(arr) + return r + else: + # unfortunately, jax's allgather seems to replicate to every device rather than every host + # which doesn't work for ~7B parameter models on TPU (assuming we also have optimizer state) + # this approach limits us to <64B parameters, but that's good enough for now + # we're going to do something a bit fancy, where we shard the model into a (process, device) mesh, + # then look for some axis along which we can shard the array, and then we'll do an allgather + # via pjit. If we can't find one, we'll just fully replicate since it probably isn't that big. + # TODO: ensure that this mesh arranges devices correctly + # (jax seems to do this internally itself, so we should be fine?) + process_mesh = Mesh(np.array(jax.devices()).reshape((jax.process_count(), -1)), ("process", "device")) + # now we need to find an axis along which we can shard the array. + # for this, we need to find an axis s.t. size(axis) % local_devices == 0 + + try: + axis_to_shard = index_where( + lambda axis_size: axis_size % process_mesh.devices.size == 0, arr.shape + ) + except ValueError: + return np.array(arr) + + shardings = [None if i != axis_to_shard else "device" for i in range(len(arr.shape))] + sharding = NamedSharding(process_mesh, PartitionSpec(*shardings)) + out = jax.jit(lambda x: x, out_shardings=sharding)(arr) + return np.array(out) + + # need to make sure the model is on *this machine* and *this machine's CPU* before saving + model = jax.tree.map(lambda arr: get_to_cpu(arr), model) + # TODO: it would be nice if safetensors supported an iterator or something so we could do the allgather one at a time + state_dict = to_state_dict(model, prefix=prefix) + return state_dict + + +_GLOBAL_SAVE_COUNT = 0 + + +def save_state_dict(state_dict: StateDict, path): + """ + Save a model's state dict to a file, bringing all tensors to the CPU first and then converting to numpy. + This will save using safetensors format + """ + state_dict = {k: v for k, v in state_dict.items() if v is not None} + if jax.process_index() == 0: + # the "pt" is a lie but it doesn't seem to actually matter and HF demands it + safetensors.numpy.save_file(state_dict, path, metadata={"format": "pt"}) + global _GLOBAL_SAVE_COUNT + sync_global_devices(f"save_state_dict {_GLOBAL_SAVE_COUNT}") + _GLOBAL_SAVE_COUNT += 1 + + +def load_state_dict(path): + """ + Load a model's state dict from a file, bringing all tensors to the CPU first and then converting to numpy. + This will load using safetensors format + """ + state_dict = safetensors.numpy.load_file(path) + return state_dict + + +def flatten_linear_layers(tree: T) -> T: + """ + In PyTorch, linear layers are stored as a 2d weight matrix and a 1d bias vector. In Haliax, + linear layers can have arbitrary dimensions, grouped into input and output axes. This function + flattens the linear layers in a tree to be compatible with PyTorch-style state dicts. + + :param tree: + """ + from haliax.nn import Linear + + def _flatten_linear(layer): + if not isinstance(layer, Linear): + return layer + + weight = layer.weight + bias = layer.bias + + if weight.array is not None: + out_first = layer.out_first + weight = weight.flatten_axes(layer.Out, "__OUT__").flatten_axes(layer.In, "__IN__") + + if out_first: + weight = weight.rearrange((..., "__OUT__", "__IN__")) + else: + weight = weight.rearrange((..., "__IN__", "__OUT__")) + + if bias is not None: + bias = bias.flatten_axes(layer.Out, "__OUT__") + + In = weight.resolve_axis("__IN__") + Out = weight.resolve_axis("__OUT__") + + return dataclasses.replace(layer, weight=weight, bias=bias, In=In, Out=Out) # type: ignore + else: + return layer + + return jax.tree.map(_flatten_linear, tree, is_leaf=lambda x: isinstance(x, Linear)) + + +def unflatten_linear_layers(template: T, tree_with_flattened_linears: T) -> T: + """ + Unflattens linear layers in a tree that was flattened with [haliax.state_dict.flatten_linear_layers][]. + Template has the same structure as the tree that was flattened, but with the original (unflattened) + linear layers. + + Returns: + The same tree as `tree_with_flattened_linears`, but with the linear layers unflattened to match + the structure of `template`. + """ + + from haliax.nn import Linear + + def _unflatten_linear(template, flattened): + assert isinstance(template, Linear) == isinstance(flattened, Linear) + + if not isinstance(template, Linear): + return flattened + + weight = flattened.weight + bias = flattened.bias + + if weight.array is not None: + weight = weight.unflatten_axis("__OUT__", template.Out).unflatten_axis("__IN__", template.In) + weight = weight.rearrange(template.weight.axes) + + if bias is not None: + bias = bias.unflatten_axis("__OUT__", template.Out) + assert template.bias is not None, "Flattened bias but template has no bias" + bias = bias.rearrange(template.bias.axes) + + return dataclasses.replace(template, weight=weight, bias=bias) # type: ignore + + return jax.tree.map( + _unflatten_linear, template, tree_with_flattened_linears, is_leaf=lambda x: isinstance(x, Linear) + ) diff --git a/src/haliax/core.py b/src/haliax/core.py index 536c8d4..89ac2b6 100644 --- a/src/haliax/core.py +++ b/src/haliax/core.py @@ -1207,7 +1207,9 @@ def unflatten_axis(array: NamedArray, axis: AxisSelector, new_axes: AxisSpec) -> raise ValueError("Must specify at least one axis to split") if axis_size != prod(ax.size for ax in new_axes): - raise ValueError(f"Cannot split {axis} into {new_axes}: size mismatch") + raise ValueError( + f"Cannot split {axis} into {new_axes}: size mismatch ({axis_size} != {prod(ax.size for ax in new_axes)})" + ) resolved_new_axes = array.axes[:old_index] + tuple(new_axes) + array.axes[old_index + 1 :] new_array = jnp.reshape(array.array, [ax.size for ax in resolved_new_axes]) diff --git a/src/haliax/nn/linear.py b/src/haliax/nn/linear.py index ffba87c..cbf697e 100644 --- a/src/haliax/nn/linear.py +++ b/src/haliax/nn/linear.py @@ -1,9 +1,8 @@ import math -from typing import Callable, Optional +from typing import Optional import equinox as eqx -import jax.lax -from jaxtyping import PRNGKeyArray +from jax.random import PRNGKey import haliax as hax @@ -29,14 +28,13 @@ class Linear(eqx.Module): In: AxisSpec, Out: AxisSpec, *, - key, - use_bias=True, - out_first: bool = False, - dot_general=None, + key: PRNGKey, + use_bias: bool = True, + out_first: bool = True, + dot_general: Optional[DotGeneralOp] = None, init_scale: float = 1.0, ) -> "Linear": """ - Args: In: AxisSpec: The input axis spec Out: AxisSpec: The output axis spec @@ -57,7 +55,7 @@ class Linear(eqx.Module): return Linear(weight, bias, In, Out, dot_general=dot_general) @named_call - def __call__(self, inputs, *, key: Optional[PRNGKeyArray] = None): + def __call__(self, inputs, *, key: Optional[PRNGKey] = None): """ Args: inputs (NamedArray): Input array diff --git a/src/haliax/nn/pool.py b/src/haliax/nn/pool.py index 9aa5597..8c3c048 100644 --- a/src/haliax/nn/pool.py +++ b/src/haliax/nn/pool.py @@ -48,6 +48,7 @@ def pool( of `n` `(low, high)` integer pairs that give the padding to apply before and after each spatial dimension, or an integer to pad all dimensions. use_ceil: if True, will use ceil instead of floor to compute the output shape + Returns: The output of the reduction for each window slice. """ @@ -154,12 +155,12 @@ def max_pool( Window: the size of the window to pool over inputs: input data with dimensions (batch, window dims..., features). stride: a sequence of `n` integers, representing the inter-window - stride (default: `(1, ..., 1)`). + stride (default: `(1, ..., 1)`). padding: either the string `'SAME'`, the string `'VALID'`, or a sequence - of `n` `(low, high)` integer pairs that give the padding to apply before - and after each spatial dimension. + of `n` `(low, high)` integer pairs that give the padding to apply before + and after each spatial dimension. Returns: - The maximum value in each window slice. + The maximum value in each window slice. """ return pool(Window, inputs, -float("inf"), jax.lax.max, stride, padding, use_ceil=use_ceil) @@ -184,7 +185,7 @@ def min_pool( and after each spatial dimension. use_ceil: if True, will use ceil instead of floor to compute the output shape Returns: - The minimum value in each window slice. + The minimum value in each window slice. """ return pool(Window, inputs, float("inf"), jax.lax.min, stride, padding, use_ceil=use_ceil) @@ -204,11 +205,10 @@ def mean_pool( Args: Window: the size of the window to pool over inputs: input data with dimensions (batch, window dims..., features). - stride: a sequence of `n` integers, representing the inter-window - stride (default: `(1, ..., 1)`). + stride: a sequence of `n` integers, representing the inter-window stride (default: `(1, ..., 1)`). padding: either the string `'SAME'`, the string `'VALID'`, or a sequence - of `n` `(low, high)` integer pairs that give the padding to apply before - and after each spatial dimension. + of `n` `(low, high)` integer pairs that give the padding to apply before + and after each spatial dimension. Returns: The mean value in each window slice. """ diff --git a/src/haliax/nn/scan.py b/src/haliax/nn/scan.py index d4b6161..41df272 100644 --- a/src/haliax/nn/scan.py +++ b/src/haliax/nn/scan.py @@ -1,13 +1,16 @@ import functools -from typing import Dict, Generic, Optional, Protocol, Sequence, Type, TypeVar +import re +from typing import Any, Dict, Generic, Optional, Protocol, Sequence, Type, TypeVar, cast import equinox as eqx import jax +from jax import numpy as jnp import haliax import haliax.util from haliax.jax_utils import filter_checkpoint +from .._src.state_dict import ModuleWithStateDictSerialization, StateDict, with_prefix from ..axis import Axis @@ -46,10 +49,14 @@ class BlockFoldable(Protocol[M]): ... def unstacked(self) -> Sequence[M]: + """ + Returns the unstacked version of this module. This is useful for logging or saving checkpoints. + + """ ... -class BlockSeq(eqx.Module, Generic[M]): +class BlockSeq(ModuleWithStateDictSerialization, Generic[M]): """ A "BlockSeq" wraps another module and produces a "sequential" version of it, where an input is applied to each instance of the sequential module in sequence. This is useful for e.g. transformers @@ -144,8 +151,28 @@ class BlockSeq(eqx.Module, Generic[M]): def _state_dict_key_map(self) -> Dict[str, Optional[str]]: return {"blocks": None} + def from_state_dict(self: M, state_dict: StateDict, prefix: Optional[str] = None) -> M: + out_blocks = [] + for i, block in enumerate(self.blocks): + my_prefix = with_prefix(prefix, str(i)) + block = block.from_state_dict(state_dict, my_prefix) + out_blocks.append(block) + + return eqx.tree_at(lambda m: m.blocks, self, out_blocks) + + def to_state_dict(self, prefix: Optional[str] = None) -> StateDict: + """ + Returns the unstacked format of the module, which is compatible with torch.nn.Sequential, with keys of the form (...). The stacked/vectorized format is required for haliax.nn.Stacked and vectorizes all such tensors into a single shared key.". + """ + state_dict: StateDict = {} + for i, block in enumerate(self.blocks): + my_prefix = with_prefix(prefix, str(i)) + state_dict.update(block.to_state_dict(my_prefix)) + + return state_dict + -class Stacked(eqx.Module, Generic[M]): +class Stacked(ModuleWithStateDictSerialization, Generic[M]): """ A "Stacked" wraps another module and produces a "stacked" version of it, where an input is applied to each instance of the stacked module in sequence. This is useful for e.g. transformers @@ -318,3 +345,78 @@ class Stacked(eqx.Module, Generic[M]): # now we need to transpose the leaves unstacked_leaves = tuple(zip(*unstacked_leaves)) return tuple(map(lambda x: jax.tree_util.tree_unflatten(structure, x), unstacked_leaves)) + + def to_state_dict(self, prefix: Optional[str] = None) -> StateDict: + # this method needs to "devectorize" the blocks, so that we have a list of blocks h.0.FOO, h.1.FOO, etc. + # first just do the normal thing with our own dict, which we'll post-process + state_dict: StateDict = super().to_state_dict(prefix) + + return _unstack_state_dict(state_dict, prefix) + + def from_state_dict(self: M, state_dict: StateDict, prefix: Optional[str] = None) -> M: + # this method needs to "vectorize" the blocks, so that we have a single block h.FOO + # first just do the normal thing with our own dict, which we'll post-process + stacked = _stack_state_dict(state_dict, prefix=prefix) + out = super().from_state_dict(stacked, prefix=prefix) # type: ignore + return out + + +def _stack_state_dict(state_dict: StateDict, prefix: Optional[str] = None) -> StateDict: + """ + Stack all keys matching prefix in a new state dict, returning a state dict that has all keys matching + prefix stacked, but otherwise the same. + + Stacked in this case means roughly "compatible with a torch.nn.Sequential", which means that the + keys are of the form "<prefix>.0.<key>", "<prefix>.1.<key>", etc. + + Mostly for use with [haliax.nn.Stacked][]. + """ + vectorized_dict: StateDict = {} + + tensors_to_vectorize: dict[str, list[Optional[Any]]] = {} + if prefix is not None: + prefix_for_pat = re.escape(prefix + ".") + else: + prefix_for_pat = "" + pattern = re.compile(rf"{prefix_for_pat}(\d+)\.(.*)") + + for k, v in state_dict.items(): + match = pattern.match(k) + if match: + block_idx = int(match.group(1)) + block_key = match.group(2) + tensors = tensors_to_vectorize.setdefault(block_key, []) + if len(tensors) <= block_idx: + tensors.extend([None] * (block_idx - len(tensors) + 1)) + assert tensors[block_idx] is None, f"Duplicate key {k}" + tensors[block_idx] = v + else: + vectorized_dict[k] = v + + # now we have to vectorize the tensors + for k, tensors in tensors_to_vectorize.items(): + vectorized_dict[cast(str, with_prefix(prefix, k))] = jnp.stack(tensors, axis=0) + + return vectorized_dict + + +def _unstack_state_dict(state_dict: StateDict, prefix: Optional[str] = None) -> StateDict: + """ + Unstack all keys matching prefix in a new state dict, returning a state dict that has all keys matching + prefix unstacked, but otherwise the same. Mostly for use with [haliax.nn.Stacked][]. + + Unstacked in this case means roughly "compatible with a torch.nn.Sequential", which means that the + keys are of the form "<prefix>.0.<key>", "<prefix>.1.<key>", etc. + """ + new_dict: StateDict = {} + prefix = with_prefix(prefix, "") + assert prefix is not None + + for k, v in state_dict.items(): + if k.startswith(prefix) and v is not None: + for i, v_i in enumerate(v): + new_dict[f"{prefix}{i}.{k[len(prefix):]}"] = v_i + else: + new_dict[k] = v + + return new_dict diff --git a/src/haliax/partitioning.py b/src/haliax/partitioning.py index 95c5d86..17908c1 100644 --- a/src/haliax/partitioning.py +++ b/src/haliax/partitioning.py @@ -382,7 +382,7 @@ def named_jit( donate_args: Optional[PyTree] = None, donate_kwargs: Optional[PyTree] = None, **pjit_args, -): +) -> typing.Union[WrappedCallable[Args, R], typing.Callable[[Callable[Args, R]], WrappedCallable[Args, R]]]: """ A version of pjit that uses NamedArrays and the provided resource mapping to infer resource partitions for sharded computation for. @@ -395,6 +395,8 @@ def named_jit( Functionally this is very similar to something like: + This function can be used as a decorator or as a function. + ```python def wrapped_fn(arg): result = fn(arg) @@ -425,7 +427,7 @@ def named_jit( if fn is None: return functools.partial( # type: ignore - named_jit, + named_jit, # type: ignore axis_resources=axis_resources, in_axis_resources=in_axis_resources, out_axis_resources=out_axis_resources, diff --git a/src/haliax/state_dict.py b/src/haliax/state_dict.py new file mode 100644 index 0000000..67d7542 --- /dev/null +++ b/src/haliax/state_dict.py @@ -0,0 +1,45 @@ +from typing import Optional, TypeVar + +from ._src.state_dict import ( + ModuleWithStateDictSerialization, + StateDict, + flatten_linear_layers, + from_state_dict, + from_torch_compatible_state_dict, + load_state_dict, + save_state_dict, + to_numpy_state_dict, + to_state_dict, + unflatten_linear_layers, + with_prefix, +) + + +T = TypeVar("T") + + +def to_torch_compatible_state_dict(t: T, *, flatten_linear: bool = True, prefix: Optional[str] = None) -> StateDict: + """ + Convert a tree to a state dict that is compatible with torch-style state dicts. + + This applies [haliax.state_dict.flatten_linear_layers][] followed by [haliax.state_dict.to_state_dict][] + """ + if flatten_linear: + t = flatten_linear_layers(t) + return to_numpy_state_dict(t, prefix=prefix) + + +__all__ = [ + "ModuleWithStateDictSerialization", + "from_torch_compatible_state_dict", + "load_state_dict", + "save_state_dict", + "from_state_dict", + "flatten_linear_layers", + "unflatten_linear_layers", + "with_prefix", + "to_state_dict", + "to_numpy_state_dict", + "StateDict", + "to_torch_compatible_state_dict", +] diff --git a/tests/test_scan.py b/tests/test_scan.py index 273d35f..a7b6cf6 100644 --- a/tests/test_scan.py +++ b/tests/test_scan.py @@ -133,3 +133,34 @@ def test_scan_with_aux_named_args(): z_seq_scan = hax.stack(Block, z_seq_scan) assert hax.all(hax.isclose(z_scan, z_seq_scan, atol=1e-5)) + + +def test_stacked_to_state_dict(): + class Module(eqx.Module): + named: hax.NamedArray + array: jax.Array + static: int = eqx.static_field() + + def __call__(self, x, *, key): + return x + self.array + self.static + hax.random.normal(key, x.axes) + + @staticmethod + def init(named, array, static): + return Module(named=named, array=array, static=static) + + Block = hax.Axis("block", 4) + E = hax.Axis("E", 10) + + initial_named = hax.random.uniform(jax.random.PRNGKey(0), (Block, E)) + + m = Stacked.init(Block, Module)(named=initial_named, array=jax.numpy.ones(Block.size), static=1) + + state_dict = m.to_state_dict() + m2 = m.from_state_dict(state_dict) + input = hax.random.uniform(jax.random.PRNGKey(1), (E,)) + key = jax.random.split(jax.random.PRNGKey(2), Block.size) + + y = m.fold(input, key=key) + y2 = m2.fold(input, key=key) + + assert hax.all(hax.equal(y, y2)) diff --git a/tests/test_state_dict.py b/tests/test_state_dict.py new file mode 100644 index 0000000..fe08962 --- /dev/null +++ b/tests/test_state_dict.py @@ -0,0 +1,129 @@ +from typing import Any + +import equinox as eqx +import jax +import jax.numpy as jnp +import pytest + +import haliax as hax +from haliax.nn import Linear +from haliax.nn.scan import _stack_state_dict, _unstack_state_dict +from haliax.state_dict import flatten_linear_layers, from_state_dict, to_state_dict, unflatten_linear_layers + + +@pytest.mark.parametrize("out_dims_first", [True, False]) +def test_flatten_linear_layers(out_dims_first: bool): + H = hax.Axis("H", 10) + W = hax.Axis("W", 20) + D = hax.Axis("D", 30) + B = hax.Axis("B", 40) + linear = hax.nn.Linear.init((H, W), (D, B), key=jax.random.PRNGKey(0), use_bias=True, out_first=out_dims_first) + + if out_dims_first: + assert linear.weight.axes == (D, B, H, W) + else: + assert linear.weight.axes == (H, W, D, B) + + flat_linear = flatten_linear_layers(linear) + + flat_state_dict = to_state_dict(flat_linear) + if out_dims_first: + assert flat_state_dict["weight"].shape == (D.size * B.size, H.size * W.size) + else: + assert flat_state_dict["weight"].shape == (H.size * W.size, D.size * B.size) + assert flat_state_dict["bias"].shape == (D.size * B.size,) + assert flat_state_dict["weight"].dtype == flat_state_dict["bias"].dtype == linear.weight.dtype + + # now unflatten it + linear2 = Linear.init((H, W), (D, B), key=jax.random.PRNGKey(1), use_bias=True, out_first=out_dims_first) + new_linear = unflatten_linear_layers(linear2, flat_linear) + + if out_dims_first: + assert new_linear.weight.axes == (D, B, H, W) + else: + assert new_linear.weight.axes == (H, W, D, B) + assert new_linear.bias.axes == (D, B) # type: ignore + + assert linear == new_linear + + +# Test cases for stack_state_dict +@pytest.mark.parametrize( + "input_dict, prefix, expected_output", + [ + # Single block stacking + ( + { + "block.0.weight": jnp.array([1, 2]), + "block.0.bias": jnp.array([3]), + "block.1.weight": jnp.array([4, 5]), + "block.1.bias": jnp.array([6]), + }, + "block", + { + "block.weight": jnp.array([[1, 2], [4, 5]]), + "block.bias": jnp.array([[3], [6]]), + }, + ), + # Mixed data types and unmatched items remain unchanged + ( + { + "block.0.weight": jnp.array([1, 2]), + "block.0.bias": jnp.array([3]), + "block.1.weight": jnp.array([4, 5]), + "block.1.bias": jnp.array([6.0]), + "unrelated.item": jnp.array([7]), + }, + "block", + { + "block.weight": jnp.array([[1, 2], [4, 5]]), + "block.bias": jnp.array([[3.0], [6.0]]), + "unrelated.item": jnp.array([7]), + }, + ), + # No items match prefix, all items should remain unchanged + ( + { + "module.0.param": jnp.array([1]), + "module.1.param": jnp.array([2]), + }, + "block", + { + "module.0.param": jnp.array([1]), + "module.1.param": jnp.array([2]), + }, + ), + ], +) +def test_stack_state_dict(input_dict, prefix, expected_output): + result = _stack_state_dict(input_dict, prefix) + for key in expected_output: + assert jnp.all(jnp.array_equal(result[key], expected_output[key])), f"Failed on key: {key}" + + # now unstack it + unstacked = _unstack_state_dict(result, prefix) + for key in input_dict: + assert jnp.all(jnp.array_equal(unstacked[key], input_dict[key])), f"Failed on key: {key}" + + +class M(eqx.Module): + a: Any + b: Any + + def __init__(self, a, b): + self.a = a + self.b = b + + +def test_to_from_state_dict(): + a = jnp.array([1, 2]) + b = jnp.array([3, 4]) + m = M(a, b) + + state_dict = to_state_dict(m) + assert state_dict == {"a": a, "b": b} + + m2 = M(jnp.array([0, 0]), jnp.array([0, 0])) + m2 = from_state_dict(m2, state_dict) + assert jnp.all(m2.a == a) + assert jnp.all(m2.b == b) commit 00b41aa65b840298150bf3dd32df1d77d25e83d3 Date: 2024-11-07T14:26:38-08:00 this should be an error diff --git a/src/haliax/core.py b/src/haliax/core.py index 89ac2b6..8013cfc 100644 --- a/src/haliax/core.py +++ b/src/haliax/core.py @@ -246,7 +246,9 @@ class NamedArray: try: axis_index = index_where(lambda a: a.name == ax_name, self.axes) if axis_index >= 0: - warnings.warn("Found axis with same name but different size.", UserWarning) + raise RuntimeError( + f"Found axis with same name but different size: {axis} vs {self.axes[axis_index]}" + ) return axis_index except ValueError: return None commit ceb90ce1770c32b45e1614da29ef14f8d11bbc4a Date: 2024-11-15T21:22:13-08:00 changes needs to make Levanter work w/ new torch serialization diff --git a/src/haliax/_src/state_dict.py b/src/haliax/_src/state_dict.py index 06c5444..10304eb 100644 --- a/src/haliax/_src/state_dict.py +++ b/src/haliax/_src/state_dict.py @@ -16,7 +16,7 @@ from jaxtyping import PyTree import haliax.partitioning as partitioning from haliax._src.util import index_where from haliax.core import NamedArray, named -from haliax.jax_utils import is_jax_array_like +from haliax.jax_utils import is_jax_array_like, is_scalarish try: @@ -166,7 +166,9 @@ def to_state_dict(tree: PyTree, prefix: Optional[str] = None) -> StateDict: Returns: The state dict representation of the input tree. """ - if isinstance(tree, eqx.Module): + if tree is None: + return {} + elif isinstance(tree, eqx.Module): if hasattr(tree, "to_state_dict"): state_dict = tree.to_state_dict(prefix) else: @@ -198,6 +200,11 @@ def to_state_dict(tree: PyTree, prefix: Optional[str] = None) -> StateDict: state_dict = {} else: raise ValueError("Cannot convert a leaf value to a state dict without a prefix") + elif is_scalarish(tree): + if prefix is not None: + state_dict = {prefix: tree} + else: + raise ValueError("Cannot convert a leaf value to a state dict without a prefix") else: raise ValueError(f"Unsupported type {type(tree)}") @@ -291,37 +298,46 @@ def to_numpy_state_dict(model, prefix: Optional[str] = None) -> StateDict: with jax.default_device(jax.local_devices(backend="cpu")[0]): def get_to_cpu(arr): - if not is_jax_array_like(arr): + if is_scalarish(arr): + return arr + elif not is_jax_array_like(arr): return arr elif isinstance(arr, np.ndarray): return arr - elif arr.is_fully_addressable: - r = np.array(arr) - return r - else: - # unfortunately, jax's allgather seems to replicate to every device rather than every host - # which doesn't work for ~7B parameter models on TPU (assuming we also have optimizer state) - # this approach limits us to <64B parameters, but that's good enough for now - # we're going to do something a bit fancy, where we shard the model into a (process, device) mesh, - # then look for some axis along which we can shard the array, and then we'll do an allgather - # via pjit. If we can't find one, we'll just fully replicate since it probably isn't that big. - # TODO: ensure that this mesh arranges devices correctly - # (jax seems to do this internally itself, so we should be fine?) - process_mesh = Mesh(np.array(jax.devices()).reshape((jax.process_count(), -1)), ("process", "device")) - # now we need to find an axis along which we can shard the array. - # for this, we need to find an axis s.t. size(axis) % local_devices == 0 - - try: - axis_to_shard = index_where( - lambda axis_size: axis_size % process_mesh.devices.size == 0, arr.shape + elif is_jax_array_like(arr): + if arr.is_fully_addressable: + r = np.array(arr) + return r + else: + # unfortunately, jax's allgather seems to replicate to every device rather than every host + # which doesn't work for ~7B parameter models on TPU (assuming we also have optimizer state) + # this approach limits us to <64B parameters, but that's good enough for now + # we're going to do something a bit fancy, where we shard the model into a (process, device) mesh, + # then look for some axis along which we can shard the array, and then we'll do an allgather + # via pjit. If we can't find one, we'll just fully replicate since it probably isn't that big. + # TODO: ensure that this mesh arranges devices correctly + # (jax seems to do this internally itself, so we should be fine?) + process_mesh = Mesh( + np.array(jax.devices()).reshape((jax.process_count(), -1)), ("process", "device") ) - except ValueError: - return np.array(arr) - - shardings = [None if i != axis_to_shard else "device" for i in range(len(arr.shape))] - sharding = NamedSharding(process_mesh, PartitionSpec(*shardings)) - out = jax.jit(lambda x: x, out_shardings=sharding)(arr) - return np.array(out) + # now we need to find an axis along which we can shard the array. + # for this, we need to find an axis s.t. size(axis) % local_devices == 0 + + try: + axis_to_shard = index_where( + lambda axis_size: axis_size % process_mesh.devices.size == 0, arr.shape + ) + except ValueError: + return np.array(arr) + + shardings = [None if i != axis_to_shard else "device" for i in range(len(arr.shape))] + sharding = NamedSharding(process_mesh, PartitionSpec(*shardings)) + out = jax.jit(lambda x: x, out_shardings=sharding)(arr) + return np.array(out) + elif is_scalarish(arr): + return np.asarray(arr) + else: + raise ValueError(f"Unsupported type {type(arr)}") # need to make sure the model is on *this machine* and *this machine's CPU* before saving model = jax.tree.map(lambda arr: get_to_cpu(arr), model) diff --git a/src/haliax/jax_utils.py b/src/haliax/jax_utils.py index a95608b..663ad7c 100644 --- a/src/haliax/jax_utils.py +++ b/src/haliax/jax_utils.py @@ -152,7 +152,7 @@ def is_scalarish(x): if isinstance(x, haliax.NamedArray): return x.ndim == 0 else: - return jnp.isscalar(x) or x.shape == () + return jnp.isscalar(x) or (getattr(x, "shape", None) == ()) def is_on_mac_metal(): diff --git a/src/haliax/nn/scan.py b/src/haliax/nn/scan.py index 41df272..6dc04db 100644 --- a/src/haliax/nn/scan.py +++ b/src/haliax/nn/scan.py @@ -8,7 +8,8 @@ from jax import numpy as jnp import haliax import haliax.util -from haliax.jax_utils import filter_checkpoint +from haliax.jax_utils import filter_checkpoint, is_jax_array_like +from haliax.util import is_jax_or_hax_array_like from .._src.state_dict import ModuleWithStateDictSerialization, StateDict, with_prefix from ..axis import Axis @@ -167,7 +168,9 @@ class BlockSeq(ModuleWithStateDictSerialization, Generic[M]): state_dict: StateDict = {} for i, block in enumerate(self.blocks): my_prefix = with_prefix(prefix, str(i)) - state_dict.update(block.to_state_dict(my_prefix)) + # we can't assume to_state_dict is implemented, so we have to do it manually + block_dict = haliax.state_dict.to_state_dict(block, my_prefix) + state_dict.update(block_dict) return state_dict @@ -413,7 +416,7 @@ def _unstack_state_dict(state_dict: StateDict, prefix: Optional[str] = None) -> assert prefix is not None for k, v in state_dict.items(): - if k.startswith(prefix) and v is not None: + if k.startswith(prefix) and is_jax_or_hax_array_like(v): for i, v_i in enumerate(v): new_dict[f"{prefix}{i}.{k[len(prefix):]}"] = v_i else: diff --git a/src/haliax/state_dict.py b/src/haliax/state_dict.py index 67d7542..fdf7a70 100644 --- a/src/haliax/state_dict.py +++ b/src/haliax/state_dict.py @@ -1,5 +1,10 @@ from typing import Optional, TypeVar +import equinox + +from haliax.jax_utils import is_jax_array_like +from haliax.types import FilterSpec + from ._src.state_dict import ( ModuleWithStateDictSerialization, StateDict, @@ -18,12 +23,22 @@ from ._src.state_dict import ( T = TypeVar("T") -def to_torch_compatible_state_dict(t: T, *, flatten_linear: bool = True, prefix: Optional[str] = None) -> StateDict: +def to_torch_compatible_state_dict( + t: T, *, flatten_linear: bool = True, prefix: Optional[str] = None, filter: FilterSpec = is_jax_array_like +) -> StateDict: """ Convert a tree to a state dict that is compatible with torch-style state dicts. This applies [haliax.state_dict.flatten_linear_layers][] followed by [haliax.state_dict.to_state_dict][] + + Args: + t: The tree to convert + flatten_linear: Whether to flatten linear layers + prefix: The prefix to use for the state dict keys + filter: The filter to use for selecting which nodes to include in the state dict. By default, this includes only + array-like objects (e.g. JAX and NumPy arrays). """ + t = equinox.filter(t, filter) if flatten_linear: t = flatten_linear_layers(t) return to_numpy_state_dict(t, prefix=prefix) diff --git a/src/haliax/types.py b/src/haliax/types.py index 2d326ae..3606bc0 100644 --- a/src/haliax/types.py +++ b/src/haliax/types.py @@ -1,8 +1,9 @@ -from typing import Any, Literal, Protocol, Tuple, TypeAlias, Union +from typing import Any, Callable, Literal, Protocol, Tuple, TypeAlias, Union import jax.numpy as jnp import numpy as np from jax.lax import Precision +from jaxtyping import PyTree DType: TypeAlias = np.dtype @@ -30,3 +31,13 @@ IntScalar = Union[int, jnp.ndarray] PrecisionLike = Union[None, str, Precision, Tuple[str, str], Tuple[Precision, Precision]] GatherScatterModeStr = Literal["promise_in_bounds", "clip", "drop", "fill"] + + +FilterSpec = Union[bool, Callable[[Any], bool]] +""" +A filter specification. Typically used on a pytree to filter out certain subtrees. Boolean values are +treated as-is, while callables are called on each element of the pytree. If the callable returns True, the element +is kept, otherwise it is filtered out. +""" + +FilterTree = FilterSpec | PyTree[FilterSpec] commit 539ecf439823586588bca098c3291d2f67ecd15c Date: 2024-11-18T14:02:50-08:00 re-fix the sharded to cpu (backport from levanter) (#111) diff --git a/src/haliax/_src/state_dict.py b/src/haliax/_src/state_dict.py index 10304eb..581b982 100644 --- a/src/haliax/_src/state_dict.py +++ b/src/haliax/_src/state_dict.py @@ -320,6 +320,7 @@ def to_numpy_state_dict(model, prefix: Optional[str] = None) -> StateDict: process_mesh = Mesh( np.array(jax.devices()).reshape((jax.process_count(), -1)), ("process", "device") ) + # now we need to find an axis along which we can shard the array. # for this, we need to find an axis s.t. size(axis) % local_devices == 0 @@ -332,7 +333,7 @@ def to_numpy_state_dict(model, prefix: Optional[str] = None) -> StateDict: shardings = [None if i != axis_to_shard else "device" for i in range(len(arr.shape))] sharding = NamedSharding(process_mesh, PartitionSpec(*shardings)) - out = jax.jit(lambda x: x, out_shardings=sharding)(arr) + out = jax.device_put(arr, sharding) return np.array(out) elif is_scalarish(arr): return np.asarray(arr) commit 76b8f25af5bfff34fe58dbc67604d78577b91c17 Date: 2024-12-03T17:38:46-08:00 TWeaks to flattening of linear layers to better work with optimizers (#112) * better flatten * manage MaskedNodes diff --git a/src/haliax/__init__.py b/src/haliax/__init__.py index c39fec6..c6f4fe6 100644 --- a/src/haliax/__init__.py +++ b/src/haliax/__init__.py @@ -34,6 +34,8 @@ from .axis import ( dslice, eliminate_axes, make_axes, + replace_axis, + resolve_axis, selects_axis, ) from .core import ( @@ -1060,6 +1062,8 @@ __all__ = [ "stack", "concatenate", "eliminate_axes", + "resolve_axis", + "replace_axis", "selects_axis", "concat_axes", "concat_axis_specs", diff --git a/src/haliax/_src/state_dict.py b/src/haliax/_src/state_dict.py index 581b982..e8b7a7d 100644 --- a/src/haliax/_src/state_dict.py +++ b/src/haliax/_src/state_dict.py @@ -15,7 +15,8 @@ from jaxtyping import PyTree import haliax.partitioning as partitioning from haliax._src.util import index_where -from haliax.core import NamedArray, named +from haliax.axis import Axis +from haliax.core import NamedArray, flatten_axes, named from haliax.jax_utils import is_jax_array_like, is_scalarish @@ -390,24 +391,22 @@ def flatten_linear_layers(tree: T) -> T: weight = layer.weight bias = layer.bias + new_Out: Axis = flatten_axes(layer.Out, "__OUT__") + new_In: Axis = flatten_axes(layer.In, "__IN__") + if weight.array is not None: out_first = layer.out_first - weight = weight.flatten_axes(layer.Out, "__OUT__").flatten_axes(layer.In, "__IN__") + weight = weight.flatten_axes(layer.Out, new_Out).flatten_axes(layer.In, new_In) if out_first: weight = weight.rearrange((..., "__OUT__", "__IN__")) else: weight = weight.rearrange((..., "__IN__", "__OUT__")) - if bias is not None: - bias = bias.flatten_axes(layer.Out, "__OUT__") - - In = weight.resolve_axis("__IN__") - Out = weight.resolve_axis("__OUT__") + if isinstance(bias, NamedArray): + bias = bias.flatten_axes(layer.Out, new_Out) - return dataclasses.replace(layer, weight=weight, bias=bias, In=In, Out=Out) # type: ignore - else: - return layer + return dataclasses.replace(layer, weight=weight, bias=bias, In=new_In, Out=new_Out) # type: ignore return jax.tree.map(_flatten_linear, tree, is_leaf=lambda x: isinstance(x, Linear)) @@ -438,7 +437,7 @@ def unflatten_linear_layers(template: T, tree_with_flattened_linears: T) -> T: weight = weight.unflatten_axis("__OUT__", template.Out).unflatten_axis("__IN__", template.In) weight = weight.rearrange(template.weight.axes) - if bias is not None: + if isinstance(bias, NamedArray): bias = bias.unflatten_axis("__OUT__", template.Out) assert template.bias is not None, "Flattened bias but template has no bias" bias = bias.rearrange(template.bias.axes) diff --git a/src/haliax/axis.py b/src/haliax/axis.py index 1268659..7f0b367 100644 --- a/src/haliax/axis.py +++ b/src/haliax/axis.py @@ -394,6 +394,52 @@ def axis_size(ax: AxisSpec) -> int: return prod(axis.size for axis in ensure_tuple(ax)) # type: ignore +@typing.overload +def resolve_axis(axis_spec: AxisSpec, axis_selection: AxisSelector) -> Axis: + ... + + +@typing.overload +def resolve_axis(axis_spec: AxisSpec, axis_selection: AxisSelection) -> AxisSpec: + ... + + +def resolve_axis(axis_spec: AxisSpec, axis_selection: AxisSelection) -> AxisSpec: + """ + Returns the axis or axes in axis_spec that match the name of axis_selection. + + If axis_selection is a str or axis, returns a single Axis. If it is a sequence, returns a sequence of Axes. + + If an axis is present with a different size, raises ValueError. + """ + ax: Axis + if isinstance(axis_selection, str | Axis): + name = axis_name(axis_selection) + for ax in ensure_tuple(axis_spec): + if axis_name(ax) == name: + if isinstance(axis_selection, Axis) and axis_size(ax) != axis_size(axis_selection): + raise ValueError(f"Axis {name} has different sizes in {axis_spec} and {axis_selection}") + return ax + raise ValueError(f"Axis {name} not found in {axis_spec}") + else: + as_map = axis_spec_to_shape_dict(axis_spec) + out: list[Axis] = [] + + for ax in ensure_tuple(axis_selection): # type: ignore + name = axis_name(ax) + if name not in as_map: + raise ValueError(f"Axis {name} not found in {axis_spec}") + if isinstance(ax, Axis): + if as_map[name] != ax.size: # type: ignore + raise ValueError(f"Axis {name} has different sizes in {axis_spec} and {axis_selection}") + else: + out.append(ax) + else: + out.append(Axis(name, as_map[name])) + + return tuple(out) + + class dslice(eqx.Module): """ Dynamic slice, comprising a (start, length) pair. Also aliased as ds. @@ -576,6 +622,7 @@ __all__ = [ "is_axis_compatible", "overlapping_axes", "replace_axis", + "resolve_axis", "selects_axis", "union_axes", "without_axes", diff --git a/src/haliax/core.py b/src/haliax/core.py index 8013cfc..e8acf19 100644 --- a/src/haliax/core.py +++ b/src/haliax/core.py @@ -1143,12 +1143,65 @@ def rename(array: NamedArray, renames: Mapping[AxisSelector, AxisSelector]) -> N return NamedArray(array.array, new_axes) +@typing.overload +def flatten_axes(axis: Axis, old_axes: Axis, new_axis: AxisSelector) -> Axis: + pass + + +@typing.overload +def flatten_axes(axis: AxisSpec, new_axis: AxisSelector) -> Axis: + pass + + +@typing.overload +def flatten_axes(axis: AxisSpec, old_axes: AxisSelection, new_axis: AxisSelector) -> AxisSpec: + pass + + +@typing.overload def flatten_axes(array: NamedArray, old_axes: AxisSelection, new_axis: AxisSelector) -> NamedArray: + pass + + +def flatten_axes( # type: ignore + # array: NamedArray | AxisSpec, old_axes: AxisSelection, new_axis: AxisSelector + *args, + **kwargs, +) -> NamedArray | AxisSpec: """ Merge a sequence of axes into a single axis. The new axis must have the same size as the product of the old axes. - The new axis is always inserted starting at the index of the first old axis in theunderlying array. + The new axis is always inserted starting at the index of the first old axis in the underlying array. + + This function can be used in two ways: + + * `flatten_axes(array, old_axes, new_axis)`: merge the old axes of the array into a new axis + * `flatten_axes(axes, old_axes, new_axis)`: merge the old axes into a new axis """ + + if len(args) + len(kwargs) == 2: + return _simple_flatten(*args, **kwargs) + else: + return _full_flatten(*args, **kwargs) + + +def _simple_flatten(axis: AxisSpec, new_axis: AxisSelector) -> Axis: + size = haliax.axis_size(axis) + if isinstance(new_axis, Axis): + if new_axis.size != size: + raise ValueError(f"Cannot merge {axis} into {new_axis}: size mismatch") + return new_axis + + assert isinstance(new_axis, str) + return Axis(new_axis, size) + + +def _full_flatten( + array: NamedArray | AxisSpec, old_axes: AxisSelection, new_axis: AxisSelector +) -> NamedArray | AxisSpec: + if isinstance(array, str | Axis | Sequence): + return _flatten_axis_spec(array, old_axes, new_axis) + old_axes = ensure_tuple(old_axes) old_axes = array.resolve_axis(old_axes) total_axis_size = haliax.axis_size(old_axes) @@ -1187,6 +1240,42 @@ def flatten_axes(array: NamedArray, old_axes: AxisSelection, new_axis: AxisSelec return NamedArray(raw_array, tuple(new_axes)) +def _flatten_axis_spec(axes: AxisSpec, old_axes: AxisSelection, new_axis: AxisSelector) -> AxisSpec: + axes = ensure_tuple(axes) + old_axes = ensure_tuple(old_axes) + old_axes = haliax.axis.resolve_axis(axes, old_axes) + total_axis_size = haliax.axis_size(old_axes) + + if isinstance(new_axis, Axis): + if new_axis.size != total_axis_size: + raise ValueError(f"Cannot merge {old_axes} into {new_axis}: size mismatch") + else: + assert isinstance(new_axis, str) + new_axis = Axis(new_axis, total_axis_size) + + if len(old_axes) == 0: # type: ignore + return (new_axis,) + axes + + # ensure that the old_axes are contiguous + # we basically ensure that the old_axes occur after the index of the first old_axis + intermediate_axes: List[Axis] = [] + new_axes: List[Axis] = [] + index_of_first_old_axis = None + for i, ax in enumerate(axes): + if ax in old_axes: # type: ignore + if index_of_first_old_axis is None: + index_of_first_old_axis = i + intermediate_axes.extend(old_axes) # type: ignore + new_axes.append(new_axis) + else: + continue + else: + intermediate_axes.append(ax) + new_axes.append(ax) + + return tuple(new_axes) + + def unflatten_axis(array: NamedArray, axis: AxisSelector, new_axes: AxisSpec) -> NamedArray: """ Split an axis into a sequence of axes. The old axis must have the same size as the product of the new axes. commit 81bbb7887704eeb0e016a47508ea8963f38686be Date: 2024-12-16T13:24:40-08:00 fix partitioning of ShapeDtypeStruct (#114) * fix partitioning of ShapeDtypeStruct * blech diff --git a/src/haliax/partitioning.py b/src/haliax/partitioning.py index 17908c1..0d2aa8a 100644 --- a/src/haliax/partitioning.py +++ b/src/haliax/partitioning.py @@ -8,7 +8,7 @@ from typing import Callable, ContextManager, Mapping, Optional, ParamSpec, Seque import equinox as eqx import jax -from equinox import module_update_wrapper +from equinox import is_array, module_update_wrapper from jax.lax import with_sharding_constraint from jax.sharding import Mesh, NamedSharding, PartitionSpec, SingleDeviceSharding from jaxtyping import PyTree @@ -20,7 +20,7 @@ from .axis import Axis, AxisSelection, AxisSelector from .core import NamedArray from .jax_utils import Static, is_in_jit, is_jax_array_like, is_on_mac_metal from .tree_util import hashable_combine, hashable_partition -from .util import StringHolderEnum, ensure_tuple, is_named_array +from .util import StringHolderEnum, ensure_tuple PhysicalAxisSpec = Union[(str), Sequence[str]] @@ -274,7 +274,7 @@ class _NamedJitWrapper(eqx.Module): if out_axis_resources is None: out_axis_resources = axis_resources - dynamic_argspec, static_argspec = hashable_partition((args, kwargs), is_jax_array_like) + dynamic_argspec, static_argspec = hashable_partition((args, kwargs), is_array) dynamic = (self._dynamic_fun, dynamic_argspec) donate_args = self._donate_args @@ -436,7 +436,7 @@ def named_jit( **pjit_args, ) - dynamic_fun, static_fun = hashable_partition(fn, is_jax_array_like) + dynamic_fun, static_fun = hashable_partition(fn, is_array) wrapper = _NamedJitWrapper( fn, @@ -514,7 +514,7 @@ def _named_pjit_cache(fun_names, **jitkwargs) -> WrappedCallable: fun = hashable_combine(dynamic_fun, static_fun) args, kwargs = hashable_combine(dynamic_spec, static_spec) out = fun(*args, **kwargs) - out_dynamic, out_static = hashable_partition(out, is_jax_array_like) + out_dynamic, out_static = hashable_partition(out, is_array) return out_dynamic, Static(out_static) fun_name, fun_qualname = fun_names @@ -543,7 +543,7 @@ def _cached_filter_eval_shape(fun, *args, **kwargs): eval_shape is surprisingly expensive, so we cache it. We use this for named_pjit for evaluating resource partitions of the output. """ - dynamic, static = hashable_partition((fun, args, kwargs), is_jax_array_like) + dynamic, static = hashable_partition((fun, args, kwargs), is_array) if static not in _eval_shape_cache: _eval_shape_cache[static] = eqx.filter_eval_shape(fun, *args, **kwargs) diff --git a/src/haliax/quantization.py b/src/haliax/quantization.py index 9a3edcc..e684f3a 100644 --- a/src/haliax/quantization.py +++ b/src/haliax/quantization.py @@ -10,7 +10,6 @@ from typing import Optional, Protocol, TypeVar import equinox as eqx import jax from jax import numpy as jnp -from jax._src.tree_util import BuiltInKeyEntry from jax.tree_util import DictKey, FlattenedIndexKey, GetAttrKey, SequenceKey from jax.typing import DTypeLike @@ -253,7 +252,7 @@ def _matches_target_fp8(key_path, config: Fp8Config) -> bool: return re.match(config.targets, key_path_str) is not None -def _key_path_to_str(key_path: tuple[BuiltInKeyEntry, ...]) -> str: +def _key_path_to_str(key_path: tuple) -> str: out = "" for k in key_path: match k: commit 993c6a744d2ad087871064ebcfec3cf48b674541 Date: 2025-01-22T00:29:40-08:00 add unique diff --git a/src/haliax/__init__.py b/src/haliax/__init__.py index c6f4fe6..aa8e4d8 100644 --- a/src/haliax/__init__.py +++ b/src/haliax/__init__.py @@ -62,7 +62,7 @@ from .core import ( ) from .hof import fold, map, scan, vmap from .jax_utils import filter_checkpoint -from .ops import clip, isclose, pad_left, trace, tril, triu, where +from .ops import clip, isclose, pad_left, trace, tril, triu, unique, where from .partitioning import auto_sharded, axis_mapping, fsdp, named_jit, shard, shard_with_axis_mapping from .specialized_fns import top_k from .types import Scalar @@ -1011,6 +1011,7 @@ __all__ = [ "vmap", "trace", "where", + "unique", "clip", "tril", "triu", diff --git a/src/haliax/ops.py b/src/haliax/ops.py index fb23f8d..53c5069 100644 --- a/src/haliax/ops.py +++ b/src/haliax/ops.py @@ -3,6 +3,9 @@ from typing import Optional, Union import jax import jax.numpy as jnp +from jaxtyping import ArrayLike + +import haliax from .axis import Axis, AxisSelector from .core import NamedArray, NamedOrNumeric, broadcast_arrays, broadcast_arrays_and_return_axes, named @@ -156,4 +159,147 @@ def raw_array_or_scalar(x: NamedOrNumeric): return x -__all__ = ["trace", "where", "tril", "triu", "isclose", "pad_left", "clip"] +@typing.overload +def unique( + array: NamedArray, Unique: Axis, *, axis: AxisSelector | None = None, fill_value: ArrayLike | None = None +) -> NamedArray: + ... + + +@typing.overload +def unique( + array: NamedArray, + Unique: Axis, + *, + return_index: typing.Literal[True], + axis: AxisSelector | None = None, + fill_value: ArrayLike | None = None, +) -> tuple[NamedArray, NamedArray]: + ... + + +@typing.overload +def unique( + array: NamedArray, + Unique: Axis, + *, + return_inverse: typing.Literal[True], + axis: AxisSelector | None = None, + fill_value: ArrayLike | None = None, +) -> tuple[NamedArray, NamedArray]: + ... + + +@typing.overload +def unique( + array: NamedArray, + Unique: Axis, + *, + return_counts: typing.Literal[True], + axis: AxisSelector | None = None, + fill_value: ArrayLike | None = None, +) -> tuple[NamedArray, NamedArray]: + ... + + +@typing.overload +def unique( + array: NamedArray, + Unique: Axis, + *, + return_index: bool = False, + return_inverse: bool = False, + return_counts: bool = False, + axis: AxisSelector | None = None, + fill_value: ArrayLike | None = None, +) -> NamedArray | tuple[NamedArray, ...]: + ... + + +def unique( + array: NamedArray, + Unique: Axis, + *, + return_index: bool = False, + return_inverse: bool = False, + return_counts: bool = False, + axis: AxisSelector | None = None, + fill_value: ArrayLike | None = None, +) -> NamedArray | tuple[NamedArray, ...]: + """ + Like jnp.unique, but with named axes. + + Args: + array: The input array. + Unique: The name of the axis that will be created to hold the unique values. + fill_value: The value to use for the fill_value argument of jnp.unique + axis: The axis along which to find unique values. + return_index: If True, return the indices of the unique values. + return_inverse: If True, return the indices of the input array that would reconstruct the unique values. + """ + size = Unique.size + + is_multireturn = return_index or return_inverse or return_counts + + kwargs = dict( + size=size, + fill_value=fill_value, + return_index=return_index, + return_inverse=return_inverse, + return_counts=return_counts, + ) + + if axis is not None: + axis_index = array._lookup_indices(axis) + if axis_index is None: + raise ValueError(f"Axis {axis} not found in array. Available axes: {array.axes}") + out = jnp.unique(array.array, axis=axis_index, **kwargs) + else: + out = jnp.unique(array.array, **kwargs) + + if is_multireturn: + unique = out[0] + next_index = 1 + if return_index: + index = out[next_index] + next_index += 1 + if return_inverse: + inverse = out[next_index] + next_index += 1 + if return_counts: + counts = out[next_index] + next_index += 1 + else: + unique = out + + ret = [] + + if axis is not None: + out_axes = haliax.axis.replace_axis(array.axes, axis, Unique) + else: + out_axes = (Unique,) + + unique_values = haliax.named(unique, out_axes) + if not is_multireturn: + return unique_values + + ret.append(unique_values) + + if return_index: + ret.append(haliax.named(index, Unique)) + + if return_inverse: + if axis is not None: + assert axis_index is not None + inverse = haliax.named(inverse, array.axes[axis_index]) + else: + inverse = haliax.named(inverse, array.axes) + ret.append(inverse) + + if return_counts: + ret.append(haliax.named(counts, Unique)) + + return tuple(ret) + + +__all__ = ["trace", "where", "tril", "triu", "isclose", "pad_left", "clip", "unique"] diff --git a/tests/test_ops.py b/tests/test_ops.py index 0a1e28d..a96f891 100644 --- a/tests/test_ops.py +++ b/tests/test_ops.py @@ -235,3 +235,112 @@ def test_reductions_produce_scalar_named_arrays_when_None_axis(): # But if we specify axes, we always get a NamedArray, even if it's a scalar assert isinstance(hax.mean(named1, axis=("Height", "Width")), NamedArray) assert hax.mean(named1, axis=("Height", "Width")).axes == () + + +def test_unique(): + # named version of this test: + # >>> M = jnp.array([[1, 2], + # ... [2, 3], + # ... [1, 2]]) + # >>> jnp.unique(M) + # Array([1, 2, 3], dtype=int32) + + Height = Axis("Height", 3) + Width = Axis("Width", 2) + + named1 = hax.named([[1, 2], [2, 3], [1, 2]], (Height, Width)) + + U = Axis("U", 3) + + named2 = hax.unique(named1, U) + + assert jnp.all(jnp.equal(named2.array, jnp.array([1, 2, 3]))) + + # If you pass an ``axis`` keyword, you can find unique *slices* of the array along + # that axis: + # + # >>> jnp.unique(M, axis=0) + # Array([[1, 2], + # [2, 3]], dtype=int32) + + U2 = Axis("U2", 2) + named3 = hax.unique(named1, U2, axis=Height) + assert jnp.all(jnp.equal(named3.array, jnp.array([[1, 2], [2, 3]]))) + + # >>> x = jnp.array([3, 4, 1, 3, 1]) + # >>> values, indices = jnp.unique(x, return_index=True) + # >>> print(values) + # [1 3 4] + # >>> print(indices) + # [2 0 1] + # >>> jnp.all(values == x[indices]) + # Array(True, dtype=bool) + + x = hax.named([3, 4, 1, 3, 1], ("Height",)) + U3 = Axis("U3", 3) + values, indices = hax.unique(x, U3, return_index=True) + + assert jnp.all(jnp.equal(values.array, jnp.array([1, 3, 4]))) + assert jnp.all(jnp.equal(indices.array, jnp.array([2, 0, 1]))) + + assert jnp.all(jnp.equal(values.array, x[{"Height": indices}].array)) + + # If you set ``return_inverse=True``, then ``unique`` returns the indices within the + # unique values for every entry in the input array: + # + # >>> x = jnp.array([3, 4, 1, 3, 1]) + # >>> values, inverse = jnp.unique(x, return_inverse=True) + # >>> print(values) + # [1 3 4] + # >>> print(inverse) + # [1 2 0 1 0] + # >>> jnp.all(values[inverse] == x) + # Array(True, dtype=bool) + + values, inverse = hax.unique(x, U3, return_inverse=True) + + assert jnp.all(jnp.equal(values.array, jnp.array([1, 3, 4]))) + assert jnp.all(jnp.equal(inverse.array, jnp.array([1, 2, 0, 1, 0]))) + + # In multiple dimensions, the input can be reconstructed using + # :func:`jax.numpy.take`: + # + # >>> values, inverse = jnp.unique(M, axis=0, return_inverse=True) + # >>> jnp.all(jnp.take(values, inverse, axis=0) == M) + # Array(True, dtype=bool) + # + + values, inverse = hax.unique(named1, U3, axis=Height, return_inverse=True) + + assert jnp.all((values[{"U3": inverse}] == named1).array) + + # **Returning counts** + # If you set ``return_counts=True``, then ``unique`` returns the number of occurrences + # within the input for every unique value: + # + # >>> x = jnp.array([3, 4, 1, 3, 1]) + # >>> values, counts = jnp.unique(x, return_counts=True) + # >>> print(values) + # [1 3 4] + # >>> print(counts) + # [2 2 1] + # + # For multi-dimensional arrays, this also returns a 1D array of counts + # indicating number of occurrences along the specified axis: + # + # >>> values, counts = jnp.unique(M, axis=0, return_counts=True) + # >>> print(values) + # [[1 2] + # [2 3]] + # >>> print(counts) + # [2 1] + + values, counts = hax.unique(x, U3, return_counts=True) + + assert jnp.all(jnp.equal(values.array, jnp.array([1, 3, 4]))) + assert jnp.all(jnp.equal(counts.array, jnp.array([2, 2, 1]))) + + values, counts = hax.unique(named1, U2, axis=Height, return_counts=True) + + assert jnp.all(jnp.equal(values.array, jnp.array([[1, 2], [2, 3]]))) + assert jnp.all(jnp.equal(counts.array, jnp.array([2, 1]))) commit 99e78f496f25eb840ccbdfe39f08a546c4591901 Date: 2025-01-23T23:49:05-08:00 this? diff --git a/tests/test_fp8.py b/tests/test_fp8.py index 3c47f60..454c11d 100644 --- a/tests/test_fp8.py +++ b/tests/test_fp8.py @@ -27,14 +27,17 @@ def test_fp8_is_reasonable(): In, Out, key=jrandom.PRNGKey(0), dot_general=hax.quantization.Fp8DotGeneralOp.init(), init_scale=0.1 ) - input = hax.random.normal(jrandom.PRNGKey(3), In) + input = hax.random.normal(jrandom.PRNGKey(3), In) * 0.1 + input2 = hax.random.normal(jrandom.PRNGKey(2), In) * 0.1 output = linear(input) fp8_output = fp8_linear(input) + fp8_output2 = fp8_linear(input2) assert output.shape == fp8_output.shape assert output.dtype == fp8_output.dtype - assert_trees_all_close(output.array, fp8_output.array, atol=1e-2, rtol=5e-2) + assert_trees_all_close(output.array, fp8_output.array, atol=2e-2, rtol=1e-2) + assert not jnp.allclose(fp8_output2.array, fp8_output.array, atol=2e-2, rtol=1e-2) # https://github.com/google/flax/blob/6f2b08e024c2fd2f8cec42a6c82408cb35412319/tests/linen/linen_test.py#L1222 commit df27a8d1cd8f4e6f8a988c1ce3e9ae1d8ee122cc Date: 2025-02-14T16:49:29-08:00 add mup configuration (#116) * add mup configuration * refactor attn scaling factor * add doc * tiny fix diff --git a/src/haliax/nn/attention.py b/src/haliax/nn/attention.py index 6e2f5f4..c105b7c 100644 --- a/src/haliax/nn/attention.py +++ b/src/haliax/nn/attention.py @@ -33,6 +33,7 @@ def dot_product_attention_weights( bias: Optional[NamedArray] = None, attention_dtype: Optional[jnp.dtype] = None, precision: PrecisionLike = None, + scaling_factor: Optional[float] = None, ) -> NamedArray: """ NamedArray version of dot product attention. Computes the logits for the attention weights. Note that the @@ -46,12 +47,16 @@ def dot_product_attention_weights( :param bias: Optional[NamedArray] broadcast compatible with (KeySize, QPos, KPos). Should be float :param attention_dtype: Optional dtype to use for attention :param precision: PrecisionLike for dot product. See precision argument to jax.lax.dot_general + :param scaling_factor: Optional float as scaling factor for attention score. Default to 1/sqrt(D) :return: NamedArray of shape (QPos, KPos) """ # cf https://github.com/google/flax/blob/509bf97ea272e130d932920f45307ac98947d994/flax/linen/attention.py#L40 orig_dtype = query.dtype - query = query / jnp.sqrt(query.axis_size(Key)) + if scaling_factor is None: + scaling_factor = 1.0 / jnp.sqrt(query.axis_size(Key)) + + query = query * scaling_factor if attention_dtype is not None: query = query.astype(attention_dtype) commit 2b7a8b02c73e5a90f6b9729477d8e37e52643c3a Date: 2025-02-26T17:15:35-08:00 handle jax 0.5.1 einsum changes (#119) * handle jax 0.5.1 einsum changes * such noise * why is this different in CI? * this? diff --git a/src/haliax/jax_utils.py b/src/haliax/jax_utils.py index 663ad7c..cf1c12c 100644 --- a/src/haliax/jax_utils.py +++ b/src/haliax/jax_utils.py @@ -16,6 +16,16 @@ import haliax from haliax.types import PrecisionLike +try: + # jax v0.5.1 or newer + from jax._src.numpy import ( + einsum as jax_einsum, # pylint: disable=g-import-not-at-top # pytype: disable=import-error + ) +except ImportError: + # jax v0.5.0 or older + from jax._src.numpy import lax_numpy as jax_einsum # pylint: disable=g-import-not-at-top + + F = typing.TypeVar("F", bound=Callable[..., Any]) @@ -169,6 +179,13 @@ def _jittable_dg_einsum( preferred_element_type: DTypeLike | None = None, _dot_general: Callable[..., Array] = jax.lax.dot_general, ) -> Array: + """ + So we want to pass around a jittable dot_general module, but JAX's builtin version doesn't support this. + So we copy over the implementation of jax.numpy.einsum and modify thing so that it is jittable (via + eqx.filter_jit) + + More or less copied from AQT + """ operands = (subscripts, *operands) if out is not None: raise NotImplementedError("The 'out' argument to jnp.einsum is not supported.") @@ -191,7 +208,7 @@ def _jittable_dg_einsum( contractions = tuple((a, frozenset(b), c) for a, b, c, *_ in contractions) - einsum = eqx.filter_jit(lax_numpy._einsum, inline=True) + einsum = eqx.filter_jit(jax_einsum._einsum, inline=True) if spec is not None: einsum = jax.named_call(einsum, name=spec) return einsum(operands, contractions, precision, preferred_element_type, _dot_general) # type: ignore[operator] diff --git a/src/haliax/random.py b/src/haliax/random.py index 9d2c4ea..68f276f 100644 --- a/src/haliax/random.py +++ b/src/haliax/random.py @@ -24,6 +24,7 @@ def uniform( minval = broadcast_to(minval, shape).array maxval = broadcast_to(maxval, shape).array jax_shape = _to_jax_shape(shape) + print(jax_shape, minval, maxval) jax_array = jrandom.uniform(key=key, shape=jax_shape, dtype=dtype, minval=minval, maxval=maxval) return haliax.auto_sharded(NamedArray(jax_array, shape)) diff --git a/tests/test_fp8.py b/tests/test_fp8.py index 3c47f60..efffaa0 100644 --- a/tests/test_fp8.py +++ b/tests/test_fp8.py @@ -34,7 +34,7 @@ def test_fp8_is_reasonable(): assert output.shape == fp8_output.shape assert output.dtype == fp8_output.dtype - assert_trees_all_close(output.array, fp8_output.array, atol=1e-2, rtol=5e-2) + assert_trees_all_close(output.array, fp8_output.array, atol=2e-2, rtol=5e-2) # https://github.com/google/flax/blob/6f2b08e024c2fd2f8cec42a6c82408cb35412319/tests/linen/linen_test.py#L1222 diff --git a/tests/test_ops.py b/tests/test_ops.py index 0a1e28d..c81a549 100644 --- a/tests/test_ops.py +++ b/tests/test_ops.py @@ -150,7 +150,9 @@ def test_where(use_jit): Volume = hax.Axis("Volume", Height.size * Width.size * Depth.size) named7 = hax.random.uniform(PRNGKey(0), (Height, Width, Depth)) named8, named9, named10 = hax_where(named7 > 0.5, fill_value=-1, new_axis=Volume) - assert jnp.all((named7[{"Height": named8, "Width": named9, "Depth": named10}] > 0.5).array) + unnamed_7 = named7.array + unnamed_8, unnamed_9, unnamed_10 = jnp.where(unnamed_7 > 0.5, size=Volume.size, fill_value=-1) + assert jnp.all(unnamed_8 == named8.array) def test_clip(): diff --git a/tests/test_random.py b/tests/test_random.py index effc0fd..7e3f681 100644 --- a/tests/test_random.py +++ b/tests/test_random.py @@ -41,8 +41,15 @@ def test_uniform_with_bounds_broadcast(): assert hax.all(u >= lb) assert hax.all(u <= 0.5) + # for lb and ub, broadcast the raw arrays for jax + lb_raw = lb.array.reshape(-1, 1) + ub_raw = ub.array.reshape(1, -1) + + lb_raw = jnp.broadcast_to(lb_raw, (Height.size, Width.size)) + ub_raw = jnp.broadcast_to(ub_raw, (Height.size, Width.size)) + check_gen_is_equal( - lambda k, s: jax.random.uniform(k, shape=s, minval=lb.array.reshape(-1, 1), maxval=ub.array.reshape(1, -1)), + lambda k, s: jax.random.uniform(k, shape=s, minval=lb_raw, maxval=ub_raw), lambda k, s: hax.random.uniform(k, s, minval=lb, maxval=ub), ) commit f8a5ade62c0177911683937f7d57e8e876518515 Date: 2025-02-26T17:16:34-08:00 int8 quantization from aqt (#118) * add int8 quantizations * add dependency * formatting * add test * formatting * refactor quantization configs and docs * formatting * bump jax version in CI * drop the cpu flag * ci version * ci version * ci version diff --git a/.github/workflows/run_quick_levanter_tests.yaml b/.github/workflows/run_quick_levanter_tests.yaml index 82f748f..333cbbf 100644 --- a/.github/workflows/run_quick_levanter_tests.yaml +++ b/.github/workflows/run_quick_levanter_tests.yaml @@ -17,7 +17,7 @@ jobs: run: | python -m pip install --upgrade pip pip install flake8 pytest - pip install --upgrade "jax[cpu]==0.4.26" "jaxlib[cpu]==0.4.26" + pip install --upgrade "jax[cpu]==0.4.35" "jaxlib[cpu]==0.4.35" - name: Install Levanter from source run: | @@ -29,7 +29,7 @@ jobs: run: | # install second since levanter will install a built version of haliax cd ../haliax - pip install .[dev] + pip install "jax[cpu]==0.4.35" "jaxlib[cpu]==0.4.35" .[dev] - name: Test levanter with pytest run: | cd ../levanter diff --git a/.github/workflows/run_tests.yaml b/.github/workflows/run_tests.yaml index 90e979c..8a03bea 100644 --- a/.github/workflows/run_tests.yaml +++ b/.github/workflows/run_tests.yaml @@ -17,8 +17,7 @@ jobs: run: | python -m pip install --upgrade pip pip install flake8 pytest - pip install --upgrade "jax[cpu]==0.4.30" "jaxlib[cpu]==0.4.30" - pip install .[dev] + pip install jax==0.4.35 jaxlib==0.4.35 .[dev] - name: Test with pytest run: | XLA_FLAGS=--xla_force_host_platform_device_count=8 PYTHONPATH=tests:src:. pytest tests diff --git a/docs/fp8.md b/docs/fp8.md index 99fc762..7b9c218 100644 --- a/docs/fp8.md +++ b/docs/fp8.md @@ -23,7 +23,7 @@ Using FP8 with Haliax is actually pretty straightforward. To enable FP8, do this ```python import haliax.quantization as haxq # setup -module = haxq.fp8_linear_layers(module) +module = haxq.quantize_linear_layers(module, haxq.QuantizationConfig(fp8=True)) # if using optax. This saves a tiny amount of memory so you can skip it if you want _, trainable_module = haxq.partition_for_grad_overwrite(module) @@ -81,13 +81,13 @@ class MyModule(eqx.Module): module = MyModule.init(key=jax.random.PRNGKey(0)) # Enable FP8 -module = hax.quantization.fp8_linear_layers(module) +module = hax.quantization.quantize_linear_layers(module, QuantizationConfig(fp8=True)) # Enable FP8 for a specific layer -from haliax.quantization import Fp8Config +from haliax.quantization import QuantizationConfig -config = Fp8Config(targets=["up_proj"]) -module = hax.quantization.fp8_linear_layers(module, config) +config = QuantizationConfig(targets=["up_proj"], fp8=True) +module = hax.quantization.quantize_linear_layers(module, config) # Train step grads = eqx.filter_grad(loss_fn)(module, data) @@ -96,7 +96,7 @@ updates, opt_state = opt.update(grads, opt_state, params=module) # or however y module = hax.quantization.apply_updates(module, updates, grads) ``` -That's it! Just a few lines of code to enabl e FP8. The `fp8_linear_layers` function will transform your module to use FP8 +That's it! Just a few lines of code to enable FP8. The `quantize_linear_layers` function will transform your module to use FP8 for linear layers (or a subset if you want), and the combo of `partition_for_grad_overwrite` and `apply_updates` function will apply the updates to the module in a way that is compatible with FP8. @@ -138,7 +138,7 @@ gradient and stores it in the gradient. ## Functions -::: haliax.quantization.fp8_linear_layers +::: haliax.quantization.quantize_linear_layers ::: haliax.quantization.partition_for_grad_overwrite ::: haliax.quantization.apply_updates diff --git a/pyproject.toml b/pyproject.toml index 1d40bf8..9e893be 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -26,7 +26,8 @@ dependencies = [ "equinox>=0.10.6", "jaxtyping>=0.2.20", "jmp>=0.0.4", - "safetensors>=0.4.3" + "safetensors>=0.4.3", + "aqtp>=0.8.2", ] dynamic =[ "version" ] diff --git a/src/haliax/quantization.py b/src/haliax/quantization.py index e684f3a..e23ef10 100644 --- a/src/haliax/quantization.py +++ b/src/haliax/quantization.py @@ -7,8 +7,11 @@ import warnings from dataclasses import dataclass from typing import Optional, Protocol, TypeVar +import aqt.jax.v2.config as aqt_config import equinox as eqx import jax +import jax.random as jrandom +from aqt.jax.v2.aqt_dot_general import DotGeneral from jax import numpy as jnp from jax.tree_util import DictKey, FlattenedIndexKey, GetAttrKey, SequenceKey from jax.typing import DTypeLike @@ -183,23 +186,63 @@ class Fp8DotGeneralOp(OverwriteWithGradient): return y +class Int8DotGeneralOp(OverwriteWithGradient): + + cfg: DotGeneral + + @classmethod + def init(cls): + cfg = aqt_config.config_v3() + return cls(cfg) + + def __call__( + self, + lhs, + rhs, + dimension_numbers, + precision, + preferred_element_type=None, + ): + cfg = aqt_config.set_context(self.cfg, jrandom.PRNGKey(42), train_step=None) + return cfg(lhs, rhs, dimension_numbers, precision, preferred_element_type) + + @dataclass(frozen=True) -class Fp8Config: - amax_history_length: int = 1024 - compute_dtype: DTypeLike = None +class QuantizationConfig: targets: Optional[list[str] | str] = dataclasses.field(default=None) """ If provided, only modules with names in this list will be quantized. If a single string, will be treated as a regex """ + amax_history_length: int = 1024 + compute_dtype: DTypeLike = None + + fp8: bool = False + int8: bool = False + + def __post_init__(self): + assert not (self.fp8 and self.int8), "Cannot use FP8 and INT8 quantization at the same time." + + +def quantize_linear_layers(tree: T, config: QuantizationConfig) -> T: + """ + Converts a module tree to use FP8/INT8 quantization. + """ + if config.fp8: + return _quantize_linear_layers(tree, config, Fp8DotGeneralOp, config.amax_history_length, config.compute_dtype) + elif config.int8: + return _quantize_linear_layers(tree, config, Int8DotGeneralOp) + else: + warnings.warn("Both fp8 and int8 are set to False. `quantize_linear_layers()` is no-op.") + return tree + -def fp8_linear_layers(tree: T, config: Fp8Config = Fp8Config()) -> T: +def _quantize_linear_layers(tree: T, config: QuantizationConfig, dot_general_cls, *args, **kwargs) -> T: """ - Converts a module tree to use FP8 quantization. - Linear modules that have a name that matches the targets (if provided) will be converted to use FP8. + Linear modules that have a name that matches the targets (if provided) will be converted to quantized version. (If targets is None, all linear modules will be converted.) - This essentially goes through and adds FP8DotGeneralOp to the Linear modules. + This essentially goes through and adds corresponding DotGeneralOp to the Linear modules. """ def _is_special_module(module): @@ -211,31 +254,29 @@ def fp8_linear_layers(tree: T, config: Fp8Config = Fp8Config()) -> T: return functools.reduce(lambda ctor, batch_axis: vmap(ctor, batch_axis), reversed(batch_dims), ctor) # TODO: test scanlayers for dg - def fp8_quantize_module(path_prefix, batch_dims: tuple[Axis, ...], path, module: T) -> T: + def quantize_module(path_prefix, batch_dims: tuple[Axis, ...], path, module: T) -> T: path = path_prefix + path if isinstance(module, hnn.Stacked): new_inner = jax.tree_util.tree_map_with_path( - functools.partial(fp8_quantize_module, path_prefix + (GetAttrKey("stacked"),), batch_dims + (module.Block,)), # type: ignore + functools.partial(quantize_module, path_prefix + (GetAttrKey("stacked"),), batch_dims + (module.Block,)), # type: ignore module.stacked, is_leaf=_is_special_module, ) return dataclasses.replace(module, stacked=new_inner) # type: ignore elif isinstance(module, hnn.Linear): - if _matches_target_fp8(path, config): - vmapped_dg = _batchify_ctor(Fp8DotGeneralOp.init, batch_dims)( - config.amax_history_length, config.compute_dtype - ) + if _matches_target(path, config): + vmapped_dg = _batchify_ctor(dot_general_cls.init, batch_dims)(*args, **kwargs) module = dataclasses.replace(module, dot_general=vmapped_dg) # type: ignore return module else: return module return jax.tree_util.tree_map_with_path( - lambda p, m: fp8_quantize_module((), (), p, m), tree, is_leaf=_is_special_module + lambda p, m: quantize_module((), (), p, m), tree, is_leaf=_is_special_module ) -def _matches_target_fp8(key_path, config: Fp8Config) -> bool: +def _matches_target(key_path, config: QuantizationConfig) -> bool: if not key_path: key = "" else: diff --git a/tests/test_fp8.py b/tests/test_fp8.py index efffaa0..fec3059 100644 --- a/tests/test_fp8.py +++ b/tests/test_fp8.py @@ -10,11 +10,11 @@ import haliax as hax from haliax._src.fp8 import compute_scale from haliax.nn import Linear from haliax.quantization import ( - Fp8Config, Fp8DotGeneralOp, + QuantizationConfig, apply_updates, - fp8_linear_layers, partition_for_grad_overwrite, + quantize_linear_layers, ) @@ -138,7 +138,7 @@ def test_layer_splicing(): Output = hax.Axis("Output", 32) mlp = hax.nn.MLP.init(Input, Output, Hidden, 3, key=init_key, init_scale=0.1) - mlp_q = fp8_linear_layers(mlp, Fp8Config()) + mlp_q = quantize_linear_layers(mlp, QuantizationConfig(fp8=True)) for layer in mlp_q.layers: assert isinstance(layer.dot_general, Fp8DotGeneralOp) @@ -148,14 +148,14 @@ def test_layer_splicing(): chex.assert_trees_all_close(output.array, output_q.array, atol=1e-3, rtol=1e-3) assert not jnp.allclose(output_q.array, 0) # don't want them to all underflow - mlp_q = fp8_linear_layers(mlp, Fp8Config(targets="layers.0")) + mlp_q = quantize_linear_layers(mlp, QuantizationConfig(targets="layers.0", fp8=True)) for i, layer in enumerate(mlp_q.layers): if i == 0: assert isinstance(layer.dot_general, Fp8DotGeneralOp) else: assert not isinstance(layer.dot_general, Fp8DotGeneralOp) - mlp_q = fp8_linear_layers(mlp, Fp8Config(targets=["0", "1"])) + mlp_q = quantize_linear_layers(mlp, QuantizationConfig(targets=["0", "1"], fp8=True)) for i, layer in enumerate(mlp_q.layers): if i < 2: assert isinstance(layer.dot_general, Fp8DotGeneralOp) @@ -193,7 +193,7 @@ def test_fp8ize_stacking(): In = hax.Axis("In", 16) Out = hax.Axis("Out", 32) tformer = Tformer.init(In, Out, key=jrandom.PRNGKey(0)) - tformer_q = fp8_linear_layers(tformer, Fp8Config()) + tformer_q = quantize_linear_layers(tformer, QuantizationConfig(fp8=True)) # want to be sure this vmaps the dot_general to the right places dg = tformer_q.blocks.stacked.up_proj.dot_general @@ -204,7 +204,7 @@ def test_fp8ize_stacking(): assert isinstance(dg, Fp8DotGeneralOp) # just stack the up_proj - tformer_q = fp8_linear_layers(tformer, Fp8Config(targets=["up_proj"])) + tformer_q = quantize_linear_layers(tformer, QuantizationConfig(targets=["up_proj"], fp8=True)) dg = tformer_q.blocks.stacked.up_proj.dot_general assert isinstance(dg, Fp8DotGeneralOp) dg = tformer_q.blocks.stacked.down_proj.dot_general diff --git a/tests/test_int8.py b/tests/test_int8.py new file mode 100644 index 0000000..01ff5c1 --- /dev/null +++ b/tests/test_int8.py @@ -0,0 +1,23 @@ +import jax.random as jrandom +from chex import assert_trees_all_close + +import haliax as hax +from haliax.nn import Linear +from haliax.quantization import Int8DotGeneralOp + + +def test_int8_is_reasonable(): + In = hax.Axis("In", 8) + Out = hax.Axis("Out", 8) + linear = Linear.init(In, Out, key=jrandom.PRNGKey(0), init_scale=0.1) + + int8_linear = Linear.init(In, Out, key=jrandom.PRNGKey(0), dot_general=Int8DotGeneralOp.init(), init_scale=0.1) + + input = hax.random.normal(jrandom.PRNGKey(3), In) + output = linear(input) + int8_output = int8_linear(input) + + assert output.shape == int8_output.shape + assert output.dtype == int8_output.dtype + + assert_trees_all_close(output.array, int8_output.array, atol=1e-2, rtol=5e-2) commit a1505c76310a92e24641b0f09f161bfd96f9b809 Date: 2025-03-07T11:44:41-08:00 We scale better than that. (#120) diff --git a/README.md b/README.md index cafa01e..7f7a34c 100644 --- a/README.md +++ b/README.md @@ -25,8 +25,8 @@ Despite the focus on legibility, Haliax is also **fast**, typically about as fast as "pure" JAX code. Haliax is also built to be **scalable**: it can support [Fully-Sharded Data Parallelism (FSDP)](https://engineering.fb.com/2021/07/15/open-source/fsdp/) and Tensor Parallelism with [just a few lines of code](https://colab.research.google.com/drive/1QX4yH3zRFF3Xiibf1aahETcSQ5nbcUMz). Haliax powers [Levanter](https://github.com/stanford-crfm/levanter), -our companion library for training large language models and other foundation models, with scale proven up to 20B parameters -and up to a TPU v3-256 pod slice. +our companion library for training large language models and other foundation models, with scale proven up to 70B parameters +and up to TPU v4-2048. ## Example: Attention commit 69f297fbaaf69d0a51f73b175a240baa6512c3c2 Date: 2025-03-09T23:06:30-07:00 Support much deeper configuration for checkpointing in Stacked (#121) * wip * add support for checkpoint policies to scan diff --git a/mkdocs.yml b/mkdocs.yml index 3e194a9..8de9b46 100644 --- a/mkdocs.yml +++ b/mkdocs.yml @@ -85,6 +85,7 @@ nav: - Rearrange: 'rearrange.md' - Matrix Multiplication: 'matmul.md' - Neural Networks: 'nn.md' + - Module Stacks: 'stacked.md' - Partitioning: 'partitioning.md' - Higher Order Functions: 'hof.md' - FP8: 'fp8.md' diff --git a/src/haliax/__init__.py b/src/haliax/__init__.py index c6f4fe6..433003b 100644 --- a/src/haliax/__init__.py +++ b/src/haliax/__init__.py @@ -61,7 +61,7 @@ from .core import ( updated_slice, ) from .hof import fold, map, scan, vmap -from .jax_utils import filter_checkpoint +from .jax_utils import tree_checkpoint_name from .ops import clip, isclose, pad_left, trace, tril, triu, where from .partitioning import auto_sharded, axis_mapping, fsdp, named_jit, shard, shard_with_axis_mapping from .specialized_fns import top_k @@ -887,7 +887,6 @@ def true_divide(x1: NamedOrNumeric, x2: NamedOrNumeric, /) -> NamedOrNumeric: # deprecated name concat_axis_specs = concat_axes - __all__ = [ "debug", "random", @@ -1071,4 +1070,5 @@ __all__ = [ "ravel", "flatten", "is_named_array", + "tree_checkpoint_name", ] diff --git a/src/haliax/jax_utils.py b/src/haliax/jax_utils.py index cf1c12c..6f0552b 100644 --- a/src/haliax/jax_utils.py +++ b/src/haliax/jax_utils.py @@ -1,5 +1,6 @@ import functools as ft import typing +import warnings from typing import Any, Callable, Optional, Sequence, Union import equinox as eqx @@ -8,8 +9,8 @@ import numpy as np from jax import Array from jax import numpy as jnp from jax import random as jrandom -from jax._src.numpy import lax_numpy -from jax._src.typing import DTypeLike +from jax.ad_checkpoint import checkpoint_name +from jax.typing import DTypeLike from jaxtyping import PRNGKeyArray import haliax @@ -27,6 +28,7 @@ except ImportError: F = typing.TypeVar("F", bound=Callable[..., Any]) +T = typing.TypeVar("T") class Static(eqx.Module): @@ -70,23 +72,9 @@ def filter_eval_shape(*args, **kwargs): def filter_checkpoint(fun: Callable, *, prevent_cse: bool = True, policy: Optional[Callable[..., bool]] = None): """As `jax.checkpoint`, but allows any Python object as inputs and outputs""" - @ft.wraps(fun) - def _fn(_static, _dynamic): - _args, _kwargs = eqx.combine(_static, _dynamic) - _out = fun(*_args, **_kwargs) - _dynamic_out, _static_out = eqx.partition(_out, is_jax_array_like) - return _dynamic_out, Static(_static_out) + warnings.warn("filter_checkpoint is deprecated, use eqx.filter_checkpoint instead", DeprecationWarning) - checkpointed_fun = jax.checkpoint(_fn, prevent_cse=prevent_cse, policy=policy, static_argnums=(0,)) - - @ft.wraps(fun) - def wrapper(*args, **kwargs): - dynamic, static = eqx.partition((args, kwargs), is_jax_array_like) - dynamic_out, static_out = checkpointed_fun(static, dynamic) - - return eqx.combine(dynamic_out, static_out.value) - - return wrapper + return eqx.filter_checkpoint(fun, prevent_cse=prevent_cse, policy=policy) def is_jax_array_like(x): @@ -202,7 +190,7 @@ def _jittable_dg_einsum( contract_path = opt_einsum.contract_path else: ty = next(iter(non_constant_dim_types)) - contract_path = lax_numpy._poly_einsum_handlers.get(ty, lax_numpy._default_poly_einsum_handler) + contract_path = jax_einsum._poly_einsum_handlers.get(ty, jax_einsum._default_poly_einsum_handler) # using einsum_call=True here is an internal api for opt_einsum... sorry operands, contractions = contract_path(*operands, einsum_call=True, use_blas=True, optimize=optimize) @@ -212,3 +200,23 @@ def _jittable_dg_einsum( if spec is not None: einsum = jax.named_call(einsum, name=spec) return einsum(operands, contractions, precision, preferred_element_type, _dot_general) # type: ignore[operator] + + +def tree_checkpoint_name(x: T, name: str) -> T: + """ + Checkpoint a tree of arrays with a given name. This is useful for gradient checkpointing. + This is equivalent to calling [jax.ad_checkpoint.checkpoint_name][] + except that it works for any PyTree, not just arrays. + + See Also: + * [jax.ad_checkpoint.checkpoint_name][] + * [haliax.nn.StackedCheckpointPolicy][] + """ + + def _checkpoint_leaf(x): + if is_jax_array_like(x): + return checkpoint_name(x, name) + else: + return x + + return jax.tree.map(_checkpoint_leaf, x) diff --git a/src/haliax/nn/__init__.py b/src/haliax/nn/__init__.py index c343449..8d0f892 100644 --- a/src/haliax/nn/__init__.py +++ b/src/haliax/nn/__init__.py @@ -38,10 +38,7 @@ from .loss import binary_cross_entropy_loss, cross_entropy_loss, cross_entropy_l from .mlp import MLP from .normalization import LayerNorm, log_softmax, logsumexp, softmax, standardize from .pool import max_pool, mean_pool, min_pool -from .scan import BlockSeq, Stacked - - -# TODO: support where in softmax, etc +from .scan import BlockSeq, Stacked, StackedCheckpointPolicy def one_hot(x: NamedArray | int, class_axis: Axis, *, dtype=None) -> NamedArray: diff --git a/src/haliax/nn/scan.py b/src/haliax/nn/scan.py index 6dc04db..c012ce5 100644 --- a/src/haliax/nn/scan.py +++ b/src/haliax/nn/scan.py @@ -1,6 +1,8 @@ +import dataclasses import functools import re -from typing import Any, Dict, Generic, Optional, Protocol, Sequence, Type, TypeVar, cast +import warnings +from typing import Any, Dict, Generic, Literal, Optional, Protocol, Sequence, Type, TypeVar, Union, cast import equinox as eqx import jax @@ -8,7 +10,7 @@ from jax import numpy as jnp import haliax import haliax.util -from haliax.jax_utils import filter_checkpoint, is_jax_array_like +from haliax.jax_utils import tree_checkpoint_name from haliax.util import is_jax_or_hax_array_like from .._src.state_dict import ModuleWithStateDictSerialization, StateDict, with_prefix @@ -26,6 +28,179 @@ class ModuleInit(Protocol[M_co]): ... +@dataclasses.dataclass +class StackedCheckpointPolicy: + """ + A class that represents a gradient checkpoint policy for blocks in a Stacked module. This is used to control + gradient checkpointing in [haliax.nn.Stacked][] and [haliax.nn.BlockSeq][]. + + Gradient checkpointing is a technique for reducing memory usage in training large models. It works by saving only a + subset of the forward pass and recomputing the rest in the backward pass. (By doing parts of the forward pass again) + JAX suggests that this usually isn't necessary when not using scan-over-layers (i.e. Stacked), so this is mostly + useful for Stacked modules. + + A scan block takes a "carry" and some extra arguments, and returns a "carry" and an "output". The "carry" is passed + to the next block, and the "output" is concatenated into a final result (sort of like an RNN). + + Schematically it might look like this: + + ``` + I I I I + | | | | + C -> B -C-> B -C-> B -C-> B --> C + | | | | + O O O O + ``` + + where "C" is the carry and "O" is the output. A block will typically do some computation (e.g. a Transformer block) + as well, which might require saving or recomputing in the backward pass. + + Imagine we save just the carries, then during the backward pass, we can recompute the outputs using the carries + and the inputs (and the blocks), and then compute the gradient as usual. This requires O(N) memory and O(N) time, + where N is the number of blocks. This is the default behavior in Haliax and works well for most models. + + Alternatively, we could only save the initial and final carry. (This corresponds to + `StackedCheckpointPolicy(save_carries=False, save_outputs=False)` or `"recompute"`) + Then, during the backward pass, for each block we + can compute all blocks up to that point (to get its input carry) and then compute the block itself. + This requires O(1) memory and O(N^2) time. + + Intermediate approaches exist (including O(sqrt(N)) memory and O(N) time), but we don't support them yet. + + Another choice is to "offload" carries and outputs to the host, which can reduce memory usage on the device. + We support offloading carries and outputs to the host, but not internals. + + See Also: + * [JAX docs on gradient checkpointing](https://docs.jax.dev/en/latest/gradient-checkpointing.html) + """ + + save_carries: bool | Literal["offload"] = True + """ + Whether to save all carries in the forward pass. If True, carries are saved in the forward pass and used in the + backward pass. If "offload", carries are saved in the forward pass and offloaded to the host + """ + save_outputs: bool | Literal["offload"] = True + """ + Whether to save scan outputs in the forward pass. If True, outputs are saved in the forward pass and + used in the backward pass. If "offload", outputs are saved in the forward pass and offloaded to the host + """ + save_block_internals: bool | list[str] = True + """ + Whether to save internal state of blocks. If a list, only the listed names are saved, as + with [jax.checkpoint_policies.save_only_these_names][]. + + See Also: https://docs.jax.dev/en/latest/gradient-checkpointing.html#custom-policies-for-offload + """ + prevent_cse: bool = False + """ + Whether to prevent common subexpression elimination in the checkpointed function. + """ + + disable: bool = False + """ + Whether to disable gradient checkpointing entirely. This is useful for debugging. + """ + + @staticmethod + def from_bool_or_str(remat_policy: bool | str): + """ + Convert a boolean or string into a BlockCheckpointPolicy. This is useful for converting user input + into a BlockCheckpointPolicy. + + Choices: + * True: save outputs, don't save block internals. This is the classic Haliax behavior. + * False: save everything. + * "offload": offload outputs to the host, don't save block internals. + * "recompute" or "full": don't save outputs or block internals. + * "save_all": save outputs and block internals. Equivalent to False + """ + if remat_policy == "offload": + return StackedCheckpointPolicy(save_carries="offload", save_outputs="offload", save_block_internals=False) + elif remat_policy == "recompute" or remat_policy == "full": + return StackedCheckpointPolicy(save_carries=False, save_outputs=False, save_block_internals=False) + elif remat_policy == "save_all": + return StackedCheckpointPolicy(save_carries=True, save_outputs=True, save_block_internals=True) + elif remat_policy is True: + return StackedCheckpointPolicy(save_carries=True, save_outputs=True, save_block_internals=False) + elif remat_policy is False: + return StackedCheckpointPolicy(save_carries=True, save_outputs=True, save_block_internals=True) + else: + raise ValueError(f"Invalid checkpoint policy {remat_policy}") + + @staticmethod + def _mk(remat_policy: Union[bool, str, "StackedCheckpointPolicy"]) -> "StackedCheckpointPolicy": + if isinstance(remat_policy, StackedCheckpointPolicy): + return remat_policy + else: + return StackedCheckpointPolicy.from_bool_or_str(remat_policy) + + def checkpoint(self, carry_name: str, output_name: str, callable): + if self.disable: + return callable + policy = self._to_jax_policy(carry_name, output_name) + if policy is None: + return callable + else: + return eqx.filter_checkpoint(callable, policy=policy, prevent_cse=self.prevent_cse) + + def _to_jax_policy(self, carry_name: str, output_name: str): + our_names_to_save = [] + our_names_to_offload = [] + our_names_to_remat = [] + + if self.save_outputs is True: + our_names_to_save.append(output_name) + elif self.save_outputs == "offload": + our_names_to_offload.append(output_name) + else: + assert self.save_outputs is False, f"Invalid save_outputs {self.save_outputs}" + our_names_to_remat.append(output_name) + + if self.save_carries is True: + our_names_to_save.append(carry_name) + elif self.save_carries == "offload": + our_names_to_offload.append(carry_name) + else: + assert self.save_carries is False, f"Invalid save_carries {self.save_carries}" + our_names_to_remat.append(carry_name) + + if isinstance(self.save_block_internals, Sequence): + our_names_to_save.extend(self.save_block_internals) + + if len(our_names_to_offload) > 0: + if self.save_block_internals is True: + raise ValueError("Can't save all block internals and offload outputs. Use a list of names instead.") + + return jax.checkpoint_policies.save_and_offload_only_these_names( + names_which_can_be_saved=our_names_to_save, + names_which_can_be_offloaded=our_names_to_offload, + offload_src="device", + offload_dst="pinned_host", + ) + else: + if len(our_names_to_remat) > 0: + if self.save_block_internals is True: + p1 = jax.checkpoint_policies.save_anything_except_these_names(*our_names_to_remat) + if len(our_names_to_save) > 0: + p2 = jax.checkpoint_policies.save_only_these_names(*our_names_to_save) + return jax.checkpoint_policies.save_from_both_policies(p1, p2) + else: + return p1 + else: + return jax.checkpoint_policies.save_only_these_names(*our_names_to_save) + elif len(our_names_to_save) > 0: + p1 = jax.checkpoint_policies.save_only_these_names(*our_names_to_save) + if self.save_block_internals is True: + p2 = jax.checkpoint_policies.save_anything_except_these_names(*our_names_to_remat) + return jax.checkpoint_policies.save_from_both_policies(p1, p2) + else: + return p1 + elif self.save_block_internals is True: + return jax.checkpoint_policies.save_anything_except_these_names(*our_names_to_remat) + else: + return None + + class BlockFoldable(Protocol[M]): """ A superclass for [haliax.nn.Stacked][] and [haliax.nn.BlockSeq][] that exposes the fold and scan methods, as @@ -39,7 +214,12 @@ class BlockFoldable(Protocol[M]): @classmethod def init( - cls: Type[S], Block: Axis, module: Type[M], *, gradient_checkpointing: bool = False, prevent_cse: bool = False + cls: Type[S], + Block: Axis, + module: Type[M], + *, + gradient_checkpointing: bool | StackedCheckpointPolicy = False, + prevent_cse: bool = False, ) -> ModuleInit[S]: ... @@ -70,23 +250,37 @@ class BlockSeq(ModuleWithStateDictSerialization, Generic[M]): blocks: Sequence[M] Block: Axis = eqx.static_field() - gradient_checkpointing: bool = eqx.static_field() + gradient_checkpointing: StackedCheckpointPolicy = eqx.static_field() @classmethod def init( - cls: Type[S], Block: Axis, module: Type[M], *, gradient_checkpointing: bool = False, prevent_cse: bool = False + cls: Type[S], + Block: Axis, + module: Type[M], + *, + gradient_checkpointing: bool | StackedCheckpointPolicy = False, + prevent_cse: bool | None = None, ) -> ModuleInit[S]: """ This is a curried init method that takes the Block and module and returns a function that takes the arguments to the module's init method. Any NamedArrays in the arguments will be sliced along the Block axis (if it exists). JAX arrays will be sliced along the first axis. """ - del prevent_cse # not needed, but kept for compat with Stacked + + gradient_checkpointing = StackedCheckpointPolicy._mk(gradient_checkpointing) + + if prevent_cse is not None: + warnings.warn( + "The prevent_cse argument is deprecated and will be removed in a future version of Haliax. Use the" + " StackedCheckpointPolicy instead.", + DeprecationWarning, + ) + gradient_checkpointing = dataclasses.replace(gradient_checkpointing, prevent_cse=prevent_cse) @functools.wraps(module) def fn(*args, **kwargs): # The only complexity here is that the args and kwargs might have a Block axis in them, - # in which case we need to loop over them them to slice them out. + # in which case we need to loop over them to slice them out. def init_block(i): (block_args, block_kwargs) = haliax.tree_util.tree_map( @@ -101,38 +295,50 @@ class BlockSeq(ModuleWithStateDictSerialization, Generic[M]): return fn def scan(self, init: T, *extra_args, **extra_kwargs): - out = [] - carry = init + def do_scan(init, *extra_args, **extra_kwargs): + out = [] + carry = init - for i, block in enumerate(self.blocks): - if self.gradient_checkpointing: - block = filter_checkpoint(block) - (block_args, block_kwargs) = haliax.tree_util.tree_map( - functools.partial(BlockSeq._slice_out, self.Block, i), (extra_args, extra_kwargs) - ) - block_result = block(carry, *block_args, **block_kwargs) - if not isinstance(block_result, (tuple, list)) or len(block_result) != 2: - raise ValueError( - f"BlockSeq.scan expects the block to return a pair of (carry, extra), got {block_result}" + for i, block in enumerate(self.blocks): + + (block_args, block_kwargs) = haliax.tree_util.tree_map( + functools.partial(BlockSeq._slice_out, self.Block, i), (extra_args, extra_kwargs) ) - carry, extra = block_result + block_result = block(carry, *block_args, **block_kwargs) - out.append(extra) + if not isinstance(block_result, (tuple, list)) or len(block_result) != 2: + raise ValueError( + f"BlockSeq.scan expects the block to return a pair of (carry, extra), got {block_result}" + ) - # TODO: do we want to stack the outputs? - return carry, out + carry, extra = block_result + + carry = tree_checkpoint_name(carry, self._carry_ckpt_name) + extra = tree_checkpoint_name(extra, self._output_ckpt_name) + + out.append(extra) + + return carry, haliax.tree_util.tree_map(lambda *x: haliax.stack(self.Block, x), *out) + + do_scan = self.gradient_checkpointing.checkpoint(self._carry_ckpt_name, self._output_ckpt_name, do_scan) + + return do_scan(init, *extra_args, **extra_kwargs) def fold(self, init: T, *args, **kwargs) -> T: - carry = init - for i, block in enumerate(self.blocks): - if self.gradient_checkpointing: - block = filter_checkpoint(block) - (block_args, block_kwargs) = haliax.tree_util.tree_map( - functools.partial(BlockSeq._slice_out, self.Block, i), (args, kwargs) - ) - carry = block(carry, *block_args, **block_kwargs) - return carry + def do_fold(init, *args, **kwargs): + carry = init + for i, block in enumerate(self.blocks): + (block_args, block_kwargs) = haliax.tree_util.tree_map( + functools.partial(BlockSeq._slice_out, self.Block, i), (args, kwargs) + ) + carry = block(carry, *block_args, **block_kwargs) + carry = tree_checkpoint_name(carry, self._carry_ckpt_name) + return carry + + do_fold = self.gradient_checkpointing.checkpoint(self._carry_ckpt_name, self._output_ckpt_name, do_fold) + + return do_fold(init, *args, **kwargs) def unstacked(self) -> Sequence[M]: return self.blocks @@ -174,6 +380,14 @@ class BlockSeq(ModuleWithStateDictSerialization, Generic[M]): return state_dict + @property + def _output_ckpt_name(self): + return f"BlockSeq[{self.Block}, {self.blocks[0].__class__.__name__}].outputs" + + @property + def _carry_ckpt_name(self): + return f"BlockSeq[{self.Block}, {self.blocks[0].__class__.__name__}].carry" + class Stacked(ModuleWithStateDictSerialization, Generic[M]): """ @@ -192,12 +406,12 @@ class Stacked(ModuleWithStateDictSerialization, Generic[M]): that the function has the same control flow for every element of the stack. Stacked supports both "fold" and "scan" semantics. "fold" is the same as a for loop that accumulates a single - output, while "scan" is the same as a for loop that accumulates a list of intermediates as well as the final output. + output, while "scan" is the same as a for loop that accumulates a list of outputs as well as the final output. Stacked also supports gradient checkpointing, which is useful for very large models that don't fit in memory. Typically only one of "fold" or "scan" can be used with a given Stacked module, depending on the what the module - returns: if the module returns a single output, use "fold"; if the module returns a sequence of intermediates and + returns: if the module returns a single output, use "fold"; if the module returns a sequence of outputs and an output to be passed to the next layer, use "scan". More concretely, for a transformer, you would use "scan" if you wanted to return a kv cache (or the attention matrix) as well as the output of the transformer. If you just wanted the output of the transformer, you would use "fold". @@ -227,48 +441,65 @@ class Stacked(ModuleWithStateDictSerialization, Generic[M]): stacked: M Block: Axis = eqx.static_field() - # TODO: support fancier gradient checkpointing - gradient_checkpointing: bool = eqx.static_field() - prevent_cse: bool = eqx.static_field() + gradient_checkpointing: StackedCheckpointPolicy = eqx.static_field() @classmethod def init( - cls, Block: Axis, module: Type[M], *, gradient_checkpointing: bool = False, prevent_cse: bool = False + cls, + Block: Axis, + module: Type[M], + *, + gradient_checkpointing: bool | StackedCheckpointPolicy | str = False, + prevent_cse: bool | None = None, ) -> ModuleInit["Stacked[M]"]: """ Initialize a Stacked module. This method is curried: you can pass in the Block and module, and it will return a function that takes (batched) arguments to the vmapped module's init method. - :param Block: - :param module: - :param gradient_checkpointing: - :param prevent_cse: - :return: + + Args: + Block: The axis that will be stacked over. This is typically a "layer" axis, but could be any axis. + module: The module that will be stacked. This module must take a batched input and return a batched output. + gradient_checkpointing: Whether to use gradient checkpointing. If True, uses the default policy. If a string, + uses the policy specified by the string. If a StackedCheckpointPolicy, uses that policy. + prevent_cse: Whether to prevent common subexpression elimination in the checkpointed function. This is useful + for debugging, but may slow down the function. """ + gradient_checkpointing = StackedCheckpointPolicy._mk(gradient_checkpointing) + + if prevent_cse is not None: + warnings.warn( + "The prevent_cse argument is deprecated and will be removed in a future version of Haliax. Use the" + " StackedCheckpointPolicy instead.", + DeprecationWarning, + ) + + gradient_checkpointing = dataclasses.replace(gradient_checkpointing, prevent_cse=prevent_cse) + @functools.wraps(module) def fn(*args, **kwargs): stacked = haliax.vmap(module.init, Block)(*args, **kwargs) - return Stacked(stacked, Block, gradient_checkpointing, prevent_cse) + return Stacked(stacked, Block, gradient_checkpointing) return fn def scan(self, init, *extra_args, **extra_kwargs): """ Scan over the stacked module. This is the same as a for loop that applies each instance of the module in sequence - to the input, passing the output of one instance to the next instance. It returns a stack of intermediates as + to the input, passing the output of one instance to the next instance. It returns a stack of outputs as well as the final output. That is, it behaves similarly to the following Python code: ```python carry = init - intermediates = [] + outputs = [] for block in self.stacked: carry, extra = block(carry) - intermediates.append(extra) + outputs.append(extra) - return carry, hax.stack(Block, intermediates) + return carry, hax.stack(Block, outputs) ``` Args: @@ -279,11 +510,24 @@ class Stacked(ModuleWithStateDictSerialization, Generic[M]): Returns: """ - if self.gradient_checkpointing: - do_block = filter_checkpoint(self._do_block, prevent_cse=self.prevent_cse) - else: - do_block = self._do_block - return haliax.scan(do_block, self.Block)(init, self.stacked, *extra_args, **extra_kwargs) + carry_name = self._carry_ckpt_name + output_name = self._output_ckpt_name + + def do_block(carry, block, *args, **kwargs): + carry, out = block(carry, *args, **kwargs) + carry = tree_checkpoint_name(carry, carry_name) + out = tree_checkpoint_name(out, output_name) + return carry, out + + def do_scan(init, *extra_args, **extra_kwargs): + carry, out = haliax.scan(do_block, self.Block)(init, self.stacked, *extra_args, **extra_kwargs) + # carry = _tree_checkpoint_name(carry, carry_name) + # out = _tree_checkpoint_name(out, output_name) + return carry, out + + do_scan = self.gradient_checkpointing.checkpoint(carry_name, output_name, do_scan) + + return do_scan(init, *extra_args, **extra_kwargs) def fold(self, init, *args, **kwargs): """ @@ -300,19 +544,26 @@ class Stacked(ModuleWithStateDictSerialization, Generic[M]): ``` Args: - init: - *args: - **kwargs: + init: The initial value of carry to pass to the first block + *args: Extra arguments to pass to the blocks. These are passed directly to the blocks + **kwargs: Extra keyword arguments to pass to the blocks. These are passed directly to the blocks Returns: """ - if self.gradient_checkpointing: - do_block = filter_checkpoint(self._do_block, prevent_cse=self.prevent_cse) - else: - do_block = self._do_block + carry_name = self._carry_ckpt_name - return haliax.fold(do_block, self.Block)(init, self.stacked, *args, **kwargs) + def do_block(carry, block, *args, **kwargs): + carry = block(carry, *args, **kwargs) + carry = tree_checkpoint_name(carry, carry_name) + return carry + + def do_fold(init, *extra_args, **extra_kwargs): + return haliax.fold(do_block, self.Block)(init, self.stacked, *extra_args, **extra_kwargs) + + do_scan = self.gradient_checkpointing.checkpoint(carry_name, self._output_ckpt_name, do_fold) + + return do_scan(init, *args, **kwargs) @staticmethod def _do_block(carry, block, *extra_args, **extra_kwargs): @@ -363,6 +614,14 @@ class Stacked(ModuleWithStateDictSerialization, Generic[M]): out = super().from_state_dict(stacked, prefix=prefix) # type: ignore return out + @property + def _carry_ckpt_name(self): + return f"Stacked[{self.Block}, {self.stacked.__class__.__name__}].carry" + + @property + def _output_ckpt_name(self): + return f"Stacked[{self.Block}, {self.stacked.__class__.__name__}].outputs" + def _stack_state_dict(state_dict: StateDict, prefix: Optional[str] = None) -> StateDict: """ diff --git a/src/haliax/random.py b/src/haliax/random.py index 68f276f..9d2c4ea 100644 --- a/src/haliax/random.py +++ b/src/haliax/random.py @@ -24,7 +24,6 @@ def uniform( minval = broadcast_to(minval, shape).array maxval = broadcast_to(maxval, shape).array jax_shape = _to_jax_shape(shape) - print(jax_shape, minval, maxval) jax_array = jrandom.uniform(key=key, shape=jax_shape, dtype=dtype, minval=minval, maxval=maxval) return haliax.auto_sharded(NamedArray(jax_array, shape)) diff --git a/tests/test_scan.py b/tests/test_scan.py index a7b6cf6..e1d4377 100644 --- a/tests/test_scan.py +++ b/tests/test_scan.py @@ -1,9 +1,11 @@ import equinox as eqx import jax import pytest +from equinox import filter_value_and_grad import haliax as hax -from haliax.nn.scan import BlockSeq, Stacked +from haliax.jax_utils import tree_checkpoint_name +from haliax.nn.scan import BlockSeq, Stacked, StackedCheckpointPolicy def test_unstacked(): @@ -130,8 +132,6 @@ def test_scan_with_aux_named_args(): z_seq, z_seq_scan = m_seq.scan(x, initial_y, key=jax.random.split(jax.random.PRNGKey(2), Block.size)) assert hax.all(hax.isclose(z, z_seq, atol=1e-5)) - z_seq_scan = hax.stack(Block, z_seq_scan) - assert hax.all(hax.isclose(z_scan, z_seq_scan, atol=1e-5)) @@ -164,3 +164,56 @@ def test_stacked_to_state_dict(): y2 = m2.fold(input, key=key) assert hax.all(hax.equal(y, y2)) + + +def test_checkpoint_carries(): + class Module(eqx.Module): + named: hax.NamedArray + + def __call__(self, x): + y = tree_checkpoint_name(hax.sin(x + self.named), "sin") + y = tree_checkpoint_name(hax.cos(y + x), "cos") + return y + x + + @staticmethod + def init(named): + return Module(named=named) + + Block = hax.Axis("block", 4) + E = hax.Axis("E", 10) + + initial_named = hax.random.uniform(jax.random.PRNGKey(0), (Block, E)) + + carry_policy = StackedCheckpointPolicy(save_carries=True, save_outputs=False, save_block_internals=False) + save_nothing = StackedCheckpointPolicy(save_carries=False, save_outputs=False, save_block_internals=False) + save_everything = StackedCheckpointPolicy(save_carries=True, save_outputs=True, save_block_internals=True) + save_internals = StackedCheckpointPolicy(save_carries=False, save_outputs=False, save_block_internals=True) + save_cos = StackedCheckpointPolicy(save_carries=False, save_outputs=False, save_block_internals=["cos"]) + save_sin_carry = StackedCheckpointPolicy(save_carries=True, save_outputs=False, save_block_internals=["sin"]) + + for name, (policy, expected_scan_shapes) in { + "carry": (carry_policy, [(E.size,), (Block.size, E.size)]), + "nothing": (save_nothing, [(E.size,)]), + "everything": (save_everything, [(E.size,), (Block.size, E.size), (Block.size, E.size)]), + "internals": (save_internals, [(E.size,), (Block.size, E.size), (Block.size, E.size)]), + "cos": (save_cos, [(E.size,), (Block.size, E.size)]), + "sin": (save_sin_carry, [(E.size,), (Block.size, E.size), (Block.size, E.size)]), + }.items(): + m = Stacked.init( + Block, + Module, + gradient_checkpointing=policy, + )(named=initial_named) + + def loss_fn(m, x): + y = m.fold(x) + return hax.sum(y).scalar() + + grad_fn = filter_value_and_grad(loss_fn) + + jaxpr = jax.make_jaxpr(grad_fn)(m, hax.random.uniform(jax.random.PRNGKey(1), (E,))) + closed_call = next(eqn for eqn in jaxpr.jaxpr.eqns if eqn.primitive == jax.core.closed_call_p) + out_shapes = [out.aval.shape for out in closed_call.outvars] + + # saved_residuals doesn't give me sensible results, so I'm doing this by hand + assert out_shapes == expected_scan_shapes, f"{name}: Expected {expected_scan_shapes}, got {out_shapes}" commit e54bcdd41337b1702fd15ae4452f43cd029fd4ef Date: 2025-03-09T23:10:08-07:00 Improve documentation and doc site (#122) * wip * add support for checkpoint policies to scan * make the docs nicer * trying to make docs nicer diff --git a/docs/api.md b/docs/api.md index 2f47106..be4bcfd 100644 --- a/docs/api.md +++ b/docs/api.md @@ -55,11 +55,11 @@ Occasionally, an axis size can be inferred in some circumstances but not others. ### Combining Arrays -We don't include `hstack` or `vstack` because we prefer semantic axes. ::: haliax.concatenate ::: haliax.stack +(We don't include `hstack` or `vstack` because they are subsumed by `stack`.) ## Array Manipulation @@ -289,6 +289,16 @@ See also the section on [Partitioning](partitioning.md). ::: haliax.partitioning.physical_axis_size ::: haliax.partitioning.sharding_for_axis + +## Gradient Checkpointing + +Haliax mainly just defers to JAX and [equinox.filter_checkpoint][] for gradient checkpointing. However, +we provide a few utilities to make it easier to use. + +See also [haliax.nn.StackedCheckpointPolicy][]. + +::: haliax.tree_checkpoint_name + ### Old API These functions are being deprecated and will be removed in a future release. diff --git a/docs/broadcasting.md b/docs/broadcasting.md index 472ce48..be9aef3 100644 --- a/docs/broadcasting.md +++ b/docs/broadcasting.md @@ -62,8 +62,8 @@ This method takes one or more axes and adds them to the array. ## Explicit Broadcasting Functions -::: haliax.broadcast_axis -::: haliax.broadcast_to +* [haliax.broadcast_axis][] +* [haliax.broadcast_to][] <!-- diff --git a/docs/css/mkdocstrings.css b/docs/css/mkdocstrings.css index 3c0b11e..ed5cc94 100644 --- a/docs/css/mkdocstrings.css +++ b/docs/css/mkdocstrings.css @@ -1,9 +1,19 @@ /* Indentation. */ -div.doc-contents:not(.first) { +div.doc-contents { padding-left: 25px; border-left: .05rem solid var(--md-typeset-table-color); } + +div.doc-class:not(.doc-contents .doc-contents)::after { + content: ""; + display: block; + width: 100%; + height: 1px; /* Adjust thickness */ + background-color: black; /* Adjust color */ + margin: 10px 0; /* Adjust spacing */ +} + /* Mark external links as such. */ a.external::after, a.autorefs-external::after { diff --git a/docs/fp8.md b/docs/fp8.md index 7b9c218..6d49527 100644 --- a/docs/fp8.md +++ b/docs/fp8.md @@ -1,20 +1,11 @@ -# FP8 Training +# Quantized Training !!! warning - FP8 training in Haliax is currently experimental and may change in the future. + FP8 and Int8 training in Haliax is currently experimental and may change in the future. -FP8 refers to 8-bit floating point numbers. FP8 is a massively reduced precision compared to the 32-bit floating point numbers -or 16-bit floating point numbers that are typically used in deep learning: there are only 256 possible values in FP8, compared to -the (almost) 2^32 in 32-bit and 2^16 in 16-bit. However, FP8 is still useful for training deep learning models, especially on -hardware that is optimized for FP8. In particular, it can massively accelerate training on hardware that is optimized for FP8: -H100 has 2x FP8 FLOPS compared to FP16 FLOPS and almost 60x(!) compared to F32 FLOPS. - -The FP8 in Haliax is currently designed to optimize throughput on FP8-enabled devices (currently H100) rather -than to save memory. In particular, Haliax's FP8 support is not designed to quantize a model to FP8 for deployment, -though this shouldn't be that hard to add for models that were trained using this functionality. -We would be happy to accept contributions to add this functionality, -and are happy to work with you to do so. In particular, adding this for models trained using Haliax's FP8 should be easy. +Haliax supports training with FP8 and int8. This is useful for training on hardware that is optimized for FP8 or Int8, +such as the H100 (fp8) or A100s (int8) and TPU v5 and newer (int8). ## TL;DR @@ -38,15 +29,42 @@ module = haxq.apply_updates(module, updates, overwrite) And train your model like normal. -## How to use FP8 +Similarly, you can use `Int8` by setting `Int8=True` in the `QuantizationConfig` object. -To use FP8, you need to do two things: -* Enable FP8 for the layers you want to use FP8 -* Modify your training step to be compatible with FP8 -Each of these is just a couple of lines of code. +## What is FP8? + +FP8 refers to 8-bit floating point numbers. FP8 is a massively reduced precision compared to the 32-bit floating point numbers +or 16-bit floating point numbers that are typically used in deep learning: there are only 256 possible values in FP8, compared to +the (almost) 2^32 in 32-bit and 2^16 in 16-bit. However, FP8 is still useful for training deep learning models, especially on +hardware that is optimized for FP8. In particular, it can massively accelerate training on hardware that is optimized for FP8: +H100 has 2x FP8 FLOPS compared to FP16 FLOPS and almost 60x(!) compared to F32 FLOPS. + +The FP8 in Haliax is currently designed to optimize throughput on FP8-enabled devices (currently H100) rather +than to save memory. In particular, Haliax's FP8 support is not designed to quantize a model to FP8 for deployment, +though this shouldn't be that hard to add for models that were trained using this functionality. +We would be happy to accept contributions to add this functionality, +and are happy to work with you to do so. In particular, adding this for models trained using Haliax's FP8 should be easy. + +See this [FP8 Primer](https://docs.nvidia.com/deeplearning/transformer-engine/user-guide/examples/fp8_primer.html) for more information on FP8. + +## What is Int8? +Int8 refers to 8-bit integers. Int8 has the same number of bits as FP8, but the interpretation is different: instead of +exponentially spaced numbers, Int8 has linearly spaced numbers. + +In Haliax, we support Int8 training through Google's [AQT](https://github.com/google/aqt) library. AQT (for +"Accurate Quantization Training") is a library that allows you to train models with quantization-aware training (QAT). + +## How to use FP8 or Int8 in Haliax + +To use quantized training in Haliax, you need to do three things: + +* Enable FP8 (or int8) for the layers you want +* Modify your training step to be compatible + +Each of these is just a couple of lines of code. ```python import haliax as hax @@ -96,8 +114,8 @@ updates, opt_state = opt.update(grads, opt_state, params=module) # or however y module = hax.quantization.apply_updates(module, updates, grads) ``` -That's it! Just a few lines of code to enable FP8. The `quantize_linear_layers` function will transform your module to use FP8 -for linear layers (or a subset if you want), and the combo of `partition_for_grad_overwrite` and `apply_updates` function will apply the updates to the module +That's it! Just a few lines of code to enable FP8. The `quantize_linear_layers` function will transform your module to use +quantization-aware training for linear layers (or a subset if you want), and the combo of `partition_for_grad_overwrite` and `apply_updates` function will apply the updates to the module in a way that is compatible with FP8. ## How FP8 works @@ -134,6 +152,13 @@ original precision. It remembers the maximum absolute value for each of the inp and scales the gradients back to the original precision. It remembers the maximum absolute value for the incoming gradient and stores it in the gradient. +## How Int8 works + +Int8 is in principle the same, though the details differ. AQT is a much more flexible library than the FP8 implementation, +because it can be a bit more finicky. We use AQT directly, and we recommend you look at the +[AQT documentation](https://github.com/google/aqt?tab=readme-ov-file#how-aqt-works-internally) for more +information on how it works. + # API Reference ## Functions @@ -152,7 +177,8 @@ gradient and stores it in the gradient. ::: haliax.quantization.DefaultDotGeneralOp ::: haliax.quantization.Fp8DotGeneralOp +::: haliax.quantization.Int8DotGeneralOp ## Configuration -::: haliax.quantization.Fp8Config +::: haliax.quantization.QuantizationConfig diff --git a/docs/nn.md b/docs/nn.md index 4203c5b..78ddb4c 100644 --- a/docs/nn.md +++ b/docs/nn.md @@ -5,6 +5,7 @@ Haliax provides a small number of neural network modules that are compatible with Equinox, though they naturally all use [haliax.NamedArray][]. (We welcome PRs for more modules! Nothing too exotic though.) + The most interesting of these modules is [haliax.nn.Stacked][], which allows you to create homogenous "stacks" of the same module (e.g. transformer blocks), which is a common pattern in deep learning. @@ -21,11 +22,12 @@ of the same module (e.g. transformer blocks), which is a common pattern in deep ### Meta -::: haliax.nn.scan.BlockFoldable -::: haliax.nn.BlockSeq -::: haliax.nn.Stacked ::: haliax.nn.MLP +### Stacked + +See the full documentation of [Stacked](stacked.md). + ### Convolution Unlike other frameworks, Haliax doesn't distinguish between 1D, 2D, and 3D, and general convolutions. Instead, we have diff --git a/docs/stacked.md b/docs/stacked.md new file mode 100644 index 0000000..389aeb0 --- /dev/null +++ b/docs/stacked.md @@ -0,0 +1,203 @@ +# Module Stacks + +A core pattern for larger models in JAX is the "scan-over-layers" pattern, where you have a sequence of layers +that get stacked together, and you use [jax.lax.scan][] or [haliax.fold][] or [haliax.scan][] to apply them to a +sequence of inputs. In Haliax, layers are represented as [equinox.nn.Module][]s, and the [haliax.nn.Stacked][] module +provides a way to create a sequence of layers that can be applied to a sequence of inputs that implements the +scan-over-layers pattern. + +## Stacked + +[haliax.nn.Stacked][] lets you apply a layer sequentially to an input, scanning over a "Layers" axis. For instance, +a Transformer might use a Stacked for its Transformer blocks: + + +```python +class TransformerBlock(eqx.Module): + + def __init__(self, config: TransformerConfig, layer_index, *, key): + attn_key, mlp_key = jax.random.split(key) + self.attention = Attention.init(config, key=attn_key) + self.mlp = MLP.init(config, key=mlp_key) + self.ln1 = LayerNorm.init(config.Hidden) + self.ln2 = LayerNorm.init(config.Hidden) + self.layer_index = layer_index + + def __call__(self, x): + y = self.attention(self.ln1(x)) + x = x + y + y = self.mlp(self.ln2(x)) + return x + y + +class Transformer(eqx.Module): + def __init__(self, config: TransformerConfig): + self.blocks = Stacked.init(Layers, TransformerBlock)( + config, # static configuration + scale=hax.arange(Layers), # dynamic configuration. Each layer gets a scalar scale value [0, 1, 2, ...] + key=jax.random.split(key, Layers), # dynamic configuration. Each layer gets a different key + ) + + def __call__(self, x: NamedArray) -> NamedArray: + # morally the equivalent of: + # for block in self.blocks: + # x = block(x) + # Except that it works better with JAX compile times. + + return self.blocks.fold(x) +``` + +You can think of [haliax.nn.Stacked][] as an analog to PyTorch's +[torch.nn.Sequential](https://pytorch.org/docs/stable/generated/torch.nn.Sequential.html), except that +every layer in the sequence must have exactly the same shape and configuration. + +Internally, a Stacked is a single copy of the module, except that every NamedArray inside that module +has a Block axis prepended (as though they were stacked with [haliax.stack][]). Similarly, every JAX array +inside the module has its first axis prepended with an axis of the same size as the Block axis, as though +they were stacked with [jax.numpy.stack][]. + +When you call the Stacked, it scans over the Block axis, applying the module to each element of the Block. + +### Creating a Stacked + +To create a Stacked, we provide `Stacked.init`, which takes a "Layers" [haliax.Axis][] and another Module as +well as args and kwargs for that module. The Layer is the axis that the Stacked will scan over, and the `args` +and `kwargs` are implicitly vmapped over the Layers. + +For instance, to create a stack of GPT2 blocks, you might do: + +```python +import jax.random + +blocks = Stacked.init(Layers, Gpt2Block)( + config, # static configuration + scale=hax.arange(Layers), # dynamic configuration. Each layer gets a scalar scale value [0, 1, 2, ...] + key=jax.random.split(key, Layers.size), # dynamic configuration. Each layer gets a different key +) +``` + +Any NamedArray passed to the Stacked init will have its Layers axis (if present) vmapped over. Any +JAX array will have its first axis vmapped over. + + +### Fold Blocks vs Scan Blocks + +The Stacked module provides two ways to apply the layers: `fold` and `scan`. A fold is the moral equivalent of this for loop: + +```python +for block in self.blocks: + x = block(x) +``` + +while a scan is the moral equivalent of this for loop: + +```python +out = [] +for block in self.blocks: + x, y = block(x) + out.append(y) + +return x, stack(out) +``` + +Blocks can be coded to either support fold or scan, but not both. +A "fold Block" should have the signature `def __call__(self, x: Carry) -> Carry`, +while a "scan Block" should have the signature `def __call__(self, x: Carry) -> Tuple[Carry, Output]`. + +(See also [jax.lax.scan][], [haliax.fold][], and [haliax.scan][].) + +### Requirements for Stacked Blocks + +As we said above, the Stacked module requires that all the layers have the same shape and configuration. + +A further constraint is that the elements of the stack must have the same Python control flow. This is the usual +constraint imposed on jit-compiled functions in JAX. All control flow must use `jax.lax` primitives like +[jax.lax.cond][], [jax.lax.while_loop][], and [jax.lax.scan][]. You can't use Python control flow like `if` or `for` +except for static control flow that is the same for all elements of the stack. + +## BlockSeq and BlockFoldable + +We also provide a way to create a sequence of layers that can be applied to a sequence of inputs that implements the +same interface as [haliax.nn.Stacked][], but with a different implementation. This is the [haliax.nn.BlockSeq][] module. +BlockSeq implements those for loops directly, rather than using [haliax.fold][] or [haliax.scan][]. + +[haliax.nn.scan.BlockFoldable][] is an interface that both [haliax.nn.Stacked][] and [haliax.nn.BlockSeq][] implement. + +## Gradient Checkpointing + +The [haliax.nn.Stacked][] module also provides a way to do gradient checkpointing, which can be useful for deep models. + +Gradient checkpointing, aka rematerialization, is a technique for trading off memory usage for compute time. +Instead of storing all the intermediate activations of a model, you store only a subset and recompute the rest +as needed. (XLA automatically recomputes the rest for you as needed.) + +[JAX's checkpointing mechanism]((https://docs.jax.dev/en/latest/gradient-checkpointing.html) is highly flexible, +and we provide a relatively simple interface to it for use with `Stacked`. + +### Simple Checkpointing +In the simplest case, you can enable a usually-good-enough checkpointing policy by passing `gradient_checkpointing=True` +to the `Stacked.init` call: + +```python +blocks = Stacked.init(Layers, TransformerBlock, gradient_checkpointing=True)( + config, + scale=hax.arange(Layers), + key=jax.random.split(key, Layers.size), +) +``` + +This will preserve the intermediate "carries" and the "outputs" of the scans, while rematerializing (i.e. recomputing) +the rest of the computation as needed during backpropagation. + +### Custom Checkpointing Policies + +If you need more control over the checkpointing policy, you can pass a [haliax.nn.StackedCheckpointPolicy][] object to +the Stacked init: + +```python +policy = StackedCheckpointPolicy( + save_carries=True, # default + save_outputs=True, # default + save_intermediates=False, # default +) +``` + +### Saving Block-Internal Values + +"`intermediates`" refers to the internal computation of the block. If you set `save_intermediates=True`, then +all internals of every block will be saved. This can be expensive. + +You can also pass a list of strings to `save_intermediates` to specify which intermediates to save. + +You could, for instance, save the output of the attention layer using [haliax.tree_checkpoint_name][]: + +```python +class TransformerBlock(eqx.Module): + def __call__(self, x): + y = self.attention(self.ln1(x)) + y = haliax.tree_checkpoint_name(y, "attn_out") + x = x + y + y = self.mlp(self.ln2(x)) + return x + y + +policy = StackedCheckpointPolicy(save_carries=True, save_block_internals=["attn_out"]) +``` + +With this policy, the output of the attention layer will be saved during the forward pass. + +This will save an extra attention computation in the backward pass, adding $`O(N * Pos * Hidden)`$ memory usage, +which is double that required by the default policy. + + +### Offloading Checkpointed Values + +Both `save_carries` and `save_outputs` can either be a boolean or the string "offload". If "offload", then the +checkpointed values will be offloaded to the host during the forward pass, and reloaded during the backward pass. + + +## API + +::: haliax.nn.Stacked +::: haliax.nn.BlockSeq +::: haliax.nn.scan.BlockFoldable + +::: haliax.nn.StackedCheckpointPolicy diff --git a/docs/state-dict.md b/docs/state-dict.md index 7cdc54e..10f53f3 100644 --- a/docs/state-dict.md +++ b/docs/state-dict.md @@ -157,4 +157,21 @@ to join the prefix to the keys of the state dict. ## API Reference -::: haliax.state_dict +::: haliax.state_dict.StateDict +::: haliax.state_dict.ModuleWithStateDictSerialization + +### Saving and Loading State Dicts +::: haliax.state_dict.save_state_dict +::: haliax.state_dict.load_state_dict + +### Converting betweewn State Dicts and Modules + +::: haliax.state_dict.from_state_dict +::: haliax.state_dict.to_state_dict + +### Torch Compatibility + +::: haliax.state_dict.from_torch_compatible_state_dict +::: haliax.state_dict.to_torch_compatible_state_dict +::: haliax.state_dict.flatten_linear_layers +::: haliax.state_dict.unflatten_linear_layers diff --git a/mkdocs.yml b/mkdocs.yml index 8de9b46..bcdd1fd 100644 --- a/mkdocs.yml +++ b/mkdocs.yml @@ -43,25 +43,34 @@ plugins: - https://jax.readthedocs.io/en/latest/objects.inv - https://docs.kidger.site/equinox/objects.inv - https://einops.rocks/objects.inv + selection: + inherited_members: true options: docstring_options: ignore_init_summary: true docstring_style: sphinx show_source: false - docstring_section_style: list - heading_level: 5 + filters: + - "!^_" + heading_level: 4 inherited_members: true + members_order: source merge_init_into_class: true + parameter_headings: true + separate_signature: false load_external_modules: true preload_modules: [haliax, haliax.core] -# separate_signature: true + show_if_no_docstring: true show_root_heading: true show_root_full_path: false -# show_signature_annotations: true - show_symbol_type_heading: false + show_signature_annotations: true + docstring_section_style: list + show_symbol_type_heading: true show_symbol_type_toc: false signature_crossrefs: true line_length: 100 + summary: true + - include-markdown extra_css: - css/material.css diff --git a/src/haliax/_src/state_dict.py b/src/haliax/_src/state_dict.py index e8b7a7d..a5325e4 100644 --- a/src/haliax/_src/state_dict.py +++ b/src/haliax/_src/state_dict.py @@ -395,7 +395,7 @@ def flatten_linear_layers(tree: T) -> T: new_In: Axis = flatten_axes(layer.In, "__IN__") if weight.array is not None: - out_first = layer.out_first + out_first = layer._out_first weight = weight.flatten_axes(layer.Out, new_Out).flatten_axes(layer.In, new_In) if out_first: diff --git a/src/haliax/axis.py b/src/haliax/axis.py index 7f0b367..af930fa 100644 --- a/src/haliax/axis.py +++ b/src/haliax/axis.py @@ -35,6 +35,8 @@ def make_axes(**kwargs: int) -> Tuple[Axis, ...]: Example: ``` X, Y = axes(X=10, Y=20) + ``` + """ return tuple(Axis(name, size) for name, size in kwargs.items()) diff --git a/src/haliax/nn/embedding.py b/src/haliax/nn/embedding.py index 54a121f..079007b 100644 --- a/src/haliax/nn/embedding.py +++ b/src/haliax/nn/embedding.py @@ -24,26 +24,60 @@ class Embedding(eqx.Module): @staticmethod def init(Vocab: Axis, Embed: AxisSpec, *, init_scale: float = 1, key, initializer_range: Optional[float] = None): + """ + Initialize an Embedding module. + + An embedding module is a simple lookup table that maps integer indices to vectors or tensors. + Weights are initialized with a truncated normal distribution with a standard deviation of + `init_scale / output_size`. + + Args: + Vocab: Size of the vocabulary + Embed: Shape of the embedding vectors. May be a single axis or a full AxisSpec + init_scale: Scale of the initialization + key: PRNG key + initializer_range: Deprecated. Use init_scale instead. + """ if initializer_range is not None: warnings.warn("initializer_range is deprecated. Use init_std instead.", DeprecationWarning) init_scale = initializer_range all_axes = (Vocab,) + ensure_tuple(Embed) output_size = hax.axis_size(Embed) - weight = hax.random.truncated_normal(key, all_axes, -3, 3) * (init_scale / math.sqrt(output_size)) + weight = hax.random.truncated_normal(key, all_axes, -3, 3) * (init_scale / output_size) return Embedding(weight=weight, Vocab=Vocab, Embed=Embed) - def __call__(self, input_ids, *, key: Optional[PRNGKeyArray] = None): + def __call__(self, input_ids: NamedArray, *, key: Optional[PRNGKeyArray] = None): + """Alias for `embed`. key is ignored.""" return self.embed(input_ids) @named_call - def embed(self, input_ids): + def embed(self, input_ids: NamedArray): + """ + Args: + input_ids: token IDs with shape > {Vocab} + """ input_embeds = self.weight.take(self.Vocab, input_ids) return input_embeds - def unembed(self, input_embeds): + def unembed(self, input_embeds: NamedArray): + """ + Unembed the input embeddings back to the vocabulary space. + + Equivalent to `input_embeds.dot(self.weight, axis=self.Embed)`. + """ return input_embeds.dot(self.weight, axis=self.Embed) def resize_embeddings(self, new_size: int, key: Optional[PRNGKeyArray] = None): + """ + Resize the embedding layer to a new size. + Args: + new_size: New size of the vocabulary + key: PRNG key for initialization of any new weights + + Returns: + Embedding: Resized embedding layer + + """ new_weights = resize_axis(self.weight, self.Vocab, new_size, key=key) return dataclasses.replace(self, Vocab=self.Vocab.resize(new_size), weight=new_weights) # type: ignore diff --git a/src/haliax/nn/linear.py b/src/haliax/nn/linear.py index cbf697e..e132e32 100644 --- a/src/haliax/nn/linear.py +++ b/src/haliax/nn/linear.py @@ -72,7 +72,10 @@ class Linear(eqx.Module): return q @property - def out_first(self): + def _out_first(self): + """ + Returns: bool: Whether the output axes are first in the weight matrix + """ # We do it this way because of scan layers if isinstance(self.Out, hax.Axis): return self.weight.axes[-1] != self.Out diff --git a/src/haliax/nn/normalization.py b/src/haliax/nn/normalization.py index ba19894..97dbf4e 100644 --- a/src/haliax/nn/normalization.py +++ b/src/haliax/nn/normalization.py @@ -58,6 +58,9 @@ def logsumexp(a: A, axis: Optional[AxisSelection] = None) -> A: return wrap_reduction_call(jnn.logsumexp, a, axis=axis, single_axis_only=False, supports_where=False) +# TODO: support where in softmax, etc + + def softmax(a: A, axis: Optional[AxisSelection] = None) -> A: return wrap_axiswise_call(jnn.softmax, a, axis=axis, single_axis_only=False) commit 5b23a1509dde17ddfb24da78c932795b35f8cd00 Date: 2025-03-10T09:55:14-07:00 try pinning all deps to see if it makes readthedocs happierwqa diff --git a/docs/requirements.txt b/docs/requirements.txt index e8b195d..2a6ec12 100644 --- a/docs/requirements.txt +++ b/docs/requirements.txt @@ -1,9 +1,12 @@ -mkdocs -mkdocstrings -mkdocstrings-python -mkdocs-material -mkdocs-material-extensions -mkdocs-autorefs -mkdocs-include-markdown-plugin -mkdocs-literate-nav -mkdocs-macros-plugin +mkdocs==1.6.1 +mkdocs-autorefs==1.4.1 +mkdocs-bootswatch==1.1 +mkdocs-gen-files==0.5.0 +mkdocs-get-deps==0.2.0 +mkdocs-include-markdown-plugin==7.1.5 +mkdocs-literate-nav==0.6.1 +mkdocs-macros-plugin==1.3.7 +mkdocs-material==9.6.7 +mkdocs-material-extensions==1.3.1 +mkdocstrings==0.29.0 +mkdocstrings-python==1.16.4 commit dbb4d077359ad48f44a56be14fbe47cddf4ff240 Date: 2025-03-10T09:57:20-07:00 i think this is the problem diff --git a/mkdocs.yml b/mkdocs.yml index bcdd1fd..3d846f2 100644 --- a/mkdocs.yml +++ b/mkdocs.yml @@ -34,9 +34,9 @@ plugins: - mkdocstrings: handlers: python: - setup_commands: - - import pytkdocs_tweaks - - pytkdocs_tweaks.main() +# setup_commands: +# - import pytkdocs_tweaks +# - pytkdocs_tweaks.main() paths: [src] import: - https://docs.python.org/3/objects.inv commit 3db535c8f15f4a64735395403ab126af73e3e69c Date: 2025-03-10T11:50:13-07:00 ok this works i think diff --git a/mkdocs.yml b/mkdocs.yml index 3d846f2..1de3b35 100644 --- a/mkdocs.yml +++ b/mkdocs.yml @@ -43,12 +43,9 @@ plugins: - https://jax.readthedocs.io/en/latest/objects.inv - https://docs.kidger.site/equinox/objects.inv - https://einops.rocks/objects.inv - selection: - inherited_members: true options: docstring_options: ignore_init_summary: true - docstring_style: sphinx show_source: false filters: - "!^_" commit 05ba27c6fbd746ec3ee5b41fa0ee2a2b62564a2c Date: 2025-03-10T13:09:06-07:00 Fix int8 export (#123) * Fix int8 export * fix import * fix import again diff --git a/src/haliax/quantization.py b/src/haliax/quantization.py index e23ef10..eaa76ee 100644 --- a/src/haliax/quantization.py +++ b/src/haliax/quantization.py @@ -14,9 +14,10 @@ import jax.random as jrandom from aqt.jax.v2.aqt_dot_general import DotGeneral from jax import numpy as jnp from jax.tree_util import DictKey, FlattenedIndexKey, GetAttrKey, SequenceKey -from jax.typing import DTypeLike +from jaxtyping import DTypeLike, PyTree import haliax.nn as hnn +from haliax.state_dict import StateDict from haliax.types import PrecisionLike from ._src.fp8 import dot_general_with_precision, in_qdq, out_qdq @@ -206,6 +207,10 @@ class Int8DotGeneralOp(OverwriteWithGradient): cfg = aqt_config.set_context(self.cfg, jrandom.PRNGKey(42), train_step=None) return cfg(lhs, rhs, dimension_numbers, precision, preferred_element_type) + def to_state_dict(tree: PyTree, prefix: Optional[str] = None) -> StateDict: + warnings.warn("Ignore all int8 states (if any) for now.") + return {} + @dataclass(frozen=True) class QuantizationConfig: commit 685e77d24197131016686c5bc1ee9553893e9aa5 Date: 2025-03-10T14:45:20-07:00 Revert "Support much deeper configuration for checkpointing in Stacked (#121)" This reverts commit 69f297fbaaf69d0a51f73b175a240baa6512c3c2. diff --git a/mkdocs.yml b/mkdocs.yml index 1de3b35..b925d13 100644 --- a/mkdocs.yml +++ b/mkdocs.yml @@ -91,7 +91,6 @@ nav: - Rearrange: 'rearrange.md' - Matrix Multiplication: 'matmul.md' - Neural Networks: 'nn.md' - - Module Stacks: 'stacked.md' - Partitioning: 'partitioning.md' - Higher Order Functions: 'hof.md' - FP8: 'fp8.md' diff --git a/src/haliax/__init__.py b/src/haliax/__init__.py index 433003b..c6f4fe6 100644 --- a/src/haliax/__init__.py +++ b/src/haliax/__init__.py @@ -61,7 +61,7 @@ from .core import ( updated_slice, ) from .hof import fold, map, scan, vmap -from .jax_utils import tree_checkpoint_name +from .jax_utils import filter_checkpoint from .ops import clip, isclose, pad_left, trace, tril, triu, where from .partitioning import auto_sharded, axis_mapping, fsdp, named_jit, shard, shard_with_axis_mapping from .specialized_fns import top_k @@ -887,6 +887,7 @@ def true_divide(x1: NamedOrNumeric, x2: NamedOrNumeric, /) -> NamedOrNumeric: # deprecated name concat_axis_specs = concat_axes + __all__ = [ "debug", "random", @@ -1070,5 +1071,4 @@ __all__ = [ "ravel", "flatten", "is_named_array", - "tree_checkpoint_name", ] diff --git a/src/haliax/jax_utils.py b/src/haliax/jax_utils.py index 6f0552b..cf1c12c 100644 --- a/src/haliax/jax_utils.py +++ b/src/haliax/jax_utils.py @@ -1,6 +1,5 @@ import functools as ft import typing -import warnings from typing import Any, Callable, Optional, Sequence, Union import equinox as eqx @@ -9,8 +8,8 @@ import numpy as np from jax import Array from jax import numpy as jnp from jax import random as jrandom -from jax.ad_checkpoint import checkpoint_name -from jax.typing import DTypeLike +from jax._src.numpy import lax_numpy +from jax._src.typing import DTypeLike from jaxtyping import PRNGKeyArray import haliax @@ -28,7 +27,6 @@ except ImportError: F = typing.TypeVar("F", bound=Callable[..., Any]) -T = typing.TypeVar("T") class Static(eqx.Module): @@ -72,9 +70,23 @@ def filter_eval_shape(*args, **kwargs): def filter_checkpoint(fun: Callable, *, prevent_cse: bool = True, policy: Optional[Callable[..., bool]] = None): """As `jax.checkpoint`, but allows any Python object as inputs and outputs""" - warnings.warn("filter_checkpoint is deprecated, use eqx.filter_checkpoint instead", DeprecationWarning) + @ft.wraps(fun) + def _fn(_static, _dynamic): + _args, _kwargs = eqx.combine(_static, _dynamic) + _out = fun(*_args, **_kwargs) + _dynamic_out, _static_out = eqx.partition(_out, is_jax_array_like) + return _dynamic_out, Static(_static_out) - return eqx.filter_checkpoint(fun, prevent_cse=prevent_cse, policy=policy) + checkpointed_fun = jax.checkpoint(_fn, prevent_cse=prevent_cse, policy=policy, static_argnums=(0,)) + + @ft.wraps(fun) + def wrapper(*args, **kwargs): + dynamic, static = eqx.partition((args, kwargs), is_jax_array_like) + dynamic_out, static_out = checkpointed_fun(static, dynamic) + + return eqx.combine(dynamic_out, static_out.value) + + return wrapper def is_jax_array_like(x): @@ -190,7 +202,7 @@ def _jittable_dg_einsum( contract_path = opt_einsum.contract_path else: ty = next(iter(non_constant_dim_types)) - contract_path = jax_einsum._poly_einsum_handlers.get(ty, jax_einsum._default_poly_einsum_handler) + contract_path = lax_numpy._poly_einsum_handlers.get(ty, lax_numpy._default_poly_einsum_handler) # using einsum_call=True here is an internal api for opt_einsum... sorry operands, contractions = contract_path(*operands, einsum_call=True, use_blas=True, optimize=optimize) @@ -200,23 +212,3 @@ def _jittable_dg_einsum( if spec is not None: einsum = jax.named_call(einsum, name=spec) return einsum(operands, contractions, precision, preferred_element_type, _dot_general) # type: ignore[operator] - - -def tree_checkpoint_name(x: T, name: str) -> T: - """ - Checkpoint a tree of arrays with a given name. This is useful for gradient checkpointing. - This is equivalent to calling [jax.ad_checkpoint.checkpoint_name][] - except that it works for any PyTree, not just arrays. - - See Also: - * [jax.ad_checkpoint.checkpoint_name][] - * [haliax.nn.StackedCheckpointPolicy][] - """ - - def _checkpoint_leaf(x): - if is_jax_array_like(x): - return checkpoint_name(x, name) - else: - return x - - return jax.tree.map(_checkpoint_leaf, x) diff --git a/src/haliax/nn/__init__.py b/src/haliax/nn/__init__.py index 8d0f892..c343449 100644 --- a/src/haliax/nn/__init__.py +++ b/src/haliax/nn/__init__.py @@ -38,7 +38,10 @@ from .loss import binary_cross_entropy_loss, cross_entropy_loss, cross_entropy_l from .mlp import MLP from .normalization import LayerNorm, log_softmax, logsumexp, softmax, standardize from .pool import max_pool, mean_pool, min_pool -from .scan import BlockSeq, Stacked, StackedCheckpointPolicy +from .scan import BlockSeq, Stacked + + +# TODO: support where in softmax, etc def one_hot(x: NamedArray | int, class_axis: Axis, *, dtype=None) -> NamedArray: diff --git a/src/haliax/nn/scan.py b/src/haliax/nn/scan.py index c012ce5..6dc04db 100644 --- a/src/haliax/nn/scan.py +++ b/src/haliax/nn/scan.py @@ -1,8 +1,6 @@ -import dataclasses import functools import re -import warnings -from typing import Any, Dict, Generic, Literal, Optional, Protocol, Sequence, Type, TypeVar, Union, cast +from typing import Any, Dict, Generic, Optional, Protocol, Sequence, Type, TypeVar, cast import equinox as eqx import jax @@ -10,7 +8,7 @@ from jax import numpy as jnp import haliax import haliax.util -from haliax.jax_utils import tree_checkpoint_name +from haliax.jax_utils import filter_checkpoint, is_jax_array_like from haliax.util import is_jax_or_hax_array_like from .._src.state_dict import ModuleWithStateDictSerialization, StateDict, with_prefix @@ -28,179 +26,6 @@ class ModuleInit(Protocol[M_co]): ... -@dataclasses.dataclass -class StackedCheckpointPolicy: - """ - A class that represents a gradient checkpoint policy for blocks in a Stacked module. This is used to control - gradient checkpointing in [haliax.nn.Stacked][] and [haliax.nn.BlockSeq][]. - - Gradient checkpointing is a technique for reducing memory usage in training large models. It works by saving only a - subset of the forward pass and recomputing the rest in the backward pass. (By doing parts of the forward pass again) - JAX suggests that this usually isn't necessary when not using scan-over-layers (i.e. Stacked), so this is mostly - useful for Stacked modules. - - A scan block takes a "carry" and some extra arguments, and returns a "carry" and an "output". The "carry" is passed - to the next block, and the "output" is concatenated into a final result (sort of like an RNN). - - Schematically it might look like this: - - ``` - I I I I - | | | | - C -> B -C-> B -C-> B -C-> B --> C - | | | | - O O O O - ``` - - where "C" is the carry and "O" is the output. A block will typically do some computation (e.g. a Transformer block) - as well, which might require saving or recomputing in the backward pass. - - Imagine we save just the carries, then during the backward pass, we can recompute the outputs using the carries - and the inputs (and the blocks), and then compute the gradient as usual. This requires O(N) memory and O(N) time, - where N is the number of blocks. This is the default behavior in Haliax and works well for most models. - - Alternatively, we could only save the initial and final carry. (This corresponds to - `StackedCheckpointPolicy(save_carries=False, save_outputs=False)` or `"recompute"`) - Then, during the backward pass, for each block we - can compute all blocks up to that point (to get its input carry) and then compute the block itself. - This requires O(1) memory and O(N^2) time. - - Intermediate approaches exist (including O(sqrt(N)) memory and O(N) time), but we don't support them yet. - - Another choice is to "offload" carries and outputs to the host, which can reduce memory usage on the device. - We support offloading carries and outputs to the host, but not internals. - - See Also: - * [JAX docs on gradient checkpointing](https://docs.jax.dev/en/latest/gradient-checkpointing.html) - """ - - save_carries: bool | Literal["offload"] = True - """ - Whether to save all carries in the forward pass. If True, carries are saved in the forward pass and used in the - backward pass. If "offload", carries are saved in the forward pass and offloaded to the host - """ - save_outputs: bool | Literal["offload"] = True - """ - Whether to save scan outputs in the forward pass. If True, outputs are saved in the forward pass and - used in the backward pass. If "offload", outputs are saved in the forward pass and offloaded to the host - """ - save_block_internals: bool | list[str] = True - """ - Whether to save internal state of blocks. If a list, only the listed names are saved, as - with [jax.checkpoint_policies.save_only_these_names][]. - - See Also: https://docs.jax.dev/en/latest/gradient-checkpointing.html#custom-policies-for-offload - """ - prevent_cse: bool = False - """ - Whether to prevent common subexpression elimination in the checkpointed function. - """ - - disable: bool = False - """ - Whether to disable gradient checkpointing entirely. This is useful for debugging. - """ - - @staticmethod - def from_bool_or_str(remat_policy: bool | str): - """ - Convert a boolean or string into a BlockCheckpointPolicy. This is useful for converting user input - into a BlockCheckpointPolicy. - - Choices: - * True: save outputs, don't save block internals. This is the classic Haliax behavior. - * False: save everything. - * "offload": offload outputs to the host, don't save block internals. - * "recompute" or "full": don't save outputs or block internals. - * "save_all": save outputs and block internals. Equivalent to False - """ - if remat_policy == "offload": - return StackedCheckpointPolicy(save_carries="offload", save_outputs="offload", save_block_internals=False) - elif remat_policy == "recompute" or remat_policy == "full": - return StackedCheckpointPolicy(save_carries=False, save_outputs=False, save_block_internals=False) - elif remat_policy == "save_all": - return StackedCheckpointPolicy(save_carries=True, save_outputs=True, save_block_internals=True) - elif remat_policy is True: - return StackedCheckpointPolicy(save_carries=True, save_outputs=True, save_block_internals=False) - elif remat_policy is False: - return StackedCheckpointPolicy(save_carries=True, save_outputs=True, save_block_internals=True) - else: - raise ValueError(f"Invalid checkpoint policy {remat_policy}") - - @staticmethod - def _mk(remat_policy: Union[bool, str, "StackedCheckpointPolicy"]) -> "StackedCheckpointPolicy": - if isinstance(remat_policy, StackedCheckpointPolicy): - return remat_policy - else: - return StackedCheckpointPolicy.from_bool_or_str(remat_policy) - - def checkpoint(self, carry_name: str, output_name: str, callable): - if self.disable: - return callable - policy = self._to_jax_policy(carry_name, output_name) - if policy is None: - return callable - else: - return eqx.filter_checkpoint(callable, policy=policy, prevent_cse=self.prevent_cse) - - def _to_jax_policy(self, carry_name: str, output_name: str): - our_names_to_save = [] - our_names_to_offload = [] - our_names_to_remat = [] - - if self.save_outputs is True: - our_names_to_save.append(output_name) - elif self.save_outputs == "offload": - our_names_to_offload.append(output_name) - else: - assert self.save_outputs is False, f"Invalid save_outputs {self.save_outputs}" - our_names_to_remat.append(output_name) - - if self.save_carries is True: - our_names_to_save.append(carry_name) - elif self.save_carries == "offload": - our_names_to_offload.append(carry_name) - else: - assert self.save_carries is False, f"Invalid save_carries {self.save_carries}" - our_names_to_remat.append(carry_name) - - if isinstance(self.save_block_internals, Sequence): - our_names_to_save.extend(self.save_block_internals) - - if len(our_names_to_offload) > 0: - if self.save_block_internals is True: - raise ValueError("Can't save all block internals and offload outputs. Use a list of names instead.") - - return jax.checkpoint_policies.save_and_offload_only_these_names( - names_which_can_be_saved=our_names_to_save, - names_which_can_be_offloaded=our_names_to_offload, - offload_src="device", - offload_dst="pinned_host", - ) - else: - if len(our_names_to_remat) > 0: - if self.save_block_internals is True: - p1 = jax.checkpoint_policies.save_anything_except_these_names(*our_names_to_remat) - if len(our_names_to_save) > 0: - p2 = jax.checkpoint_policies.save_only_these_names(*our_names_to_save) - return jax.checkpoint_policies.save_from_both_policies(p1, p2) - else: - return p1 - else: - return jax.checkpoint_policies.save_only_these_names(*our_names_to_save) - elif len(our_names_to_save) > 0: - p1 = jax.checkpoint_policies.save_only_these_names(*our_names_to_save) - if self.save_block_internals is True: - p2 = jax.checkpoint_policies.save_anything_except_these_names(*our_names_to_remat) - return jax.checkpoint_policies.save_from_both_policies(p1, p2) - else: - return p1 - elif self.save_block_internals is True: - return jax.checkpoint_policies.save_anything_except_these_names(*our_names_to_remat) - else: - return None - - class BlockFoldable(Protocol[M]): """ A superclass for [haliax.nn.Stacked][] and [haliax.nn.BlockSeq][] that exposes the fold and scan methods, as @@ -214,12 +39,7 @@ class BlockFoldable(Protocol[M]): @classmethod def init( - cls: Type[S], - Block: Axis, - module: Type[M], - *, - gradient_checkpointing: bool | StackedCheckpointPolicy = False, - prevent_cse: bool = False, + cls: Type[S], Block: Axis, module: Type[M], *, gradient_checkpointing: bool = False, prevent_cse: bool = False ) -> ModuleInit[S]: ... @@ -250,37 +70,23 @@ class BlockSeq(ModuleWithStateDictSerialization, Generic[M]): blocks: Sequence[M] Block: Axis = eqx.static_field() - gradient_checkpointing: StackedCheckpointPolicy = eqx.static_field() + gradient_checkpointing: bool = eqx.static_field() @classmethod def init( - cls: Type[S], - Block: Axis, - module: Type[M], - *, - gradient_checkpointing: bool | StackedCheckpointPolicy = False, - prevent_cse: bool | None = None, + cls: Type[S], Block: Axis, module: Type[M], *, gradient_checkpointing: bool = False, prevent_cse: bool = False ) -> ModuleInit[S]: """ This is a curried init method that takes the Block and module and returns a function that takes the arguments to the module's init method. Any NamedArrays in the arguments will be sliced along the Block axis (if it exists). JAX arrays will be sliced along the first axis. """ - - gradient_checkpointing = StackedCheckpointPolicy._mk(gradient_checkpointing) - - if prevent_cse is not None: - warnings.warn( - "The prevent_cse argument is deprecated and will be removed in a future version of Haliax. Use the" - " StackedCheckpointPolicy instead.", - DeprecationWarning, - ) - gradient_checkpointing = dataclasses.replace(gradient_checkpointing, prevent_cse=prevent_cse) + del prevent_cse # not needed, but kept for compat with Stacked @functools.wraps(module) def fn(*args, **kwargs): # The only complexity here is that the args and kwargs might have a Block axis in them, - # in which case we need to loop over them to slice them out. + # in which case we need to loop over them them to slice them out. def init_block(i): (block_args, block_kwargs) = haliax.tree_util.tree_map( @@ -295,50 +101,38 @@ class BlockSeq(ModuleWithStateDictSerialization, Generic[M]): return fn def scan(self, init: T, *extra_args, **extra_kwargs): - def do_scan(init, *extra_args, **extra_kwargs): - out = [] - carry = init - - for i, block in enumerate(self.blocks): + out = [] + carry = init - (block_args, block_kwargs) = haliax.tree_util.tree_map( - functools.partial(BlockSeq._slice_out, self.Block, i), (extra_args, extra_kwargs) + for i, block in enumerate(self.blocks): + if self.gradient_checkpointing: + block = filter_checkpoint(block) + (block_args, block_kwargs) = haliax.tree_util.tree_map( + functools.partial(BlockSeq._slice_out, self.Block, i), (extra_args, extra_kwargs) + ) + block_result = block(carry, *block_args, **block_kwargs) + if not isinstance(block_result, (tuple, list)) or len(block_result) != 2: + raise ValueError( + f"BlockSeq.scan expects the block to return a pair of (carry, extra), got {block_result}" ) - block_result = block(carry, *block_args, **block_kwargs) + carry, extra = block_result - if not isinstance(block_result, (tuple, list)) or len(block_result) != 2: - raise ValueError( - f"BlockSeq.scan expects the block to return a pair of (carry, extra), got {block_result}" - ) + out.append(extra) - carry, extra = block_result - - carry = tree_checkpoint_name(carry, self._carry_ckpt_name) - extra = tree_checkpoint_name(extra, self._output_ckpt_name) - - out.append(extra) - - return carry, haliax.tree_util.tree_map(lambda *x: haliax.stack(self.Block, x), *out) - - do_scan = self.gradient_checkpointing.checkpoint(self._carry_ckpt_name, self._output_ckpt_name, do_scan) - - return do_scan(init, *extra_args, **extra_kwargs) + # TODO: do we want to stack the outputs? + return carry, out def fold(self, init: T, *args, **kwargs) -> T: - def do_fold(init, *args, **kwargs): - carry = init - for i, block in enumerate(self.blocks): - (block_args, block_kwargs) = haliax.tree_util.tree_map( - functools.partial(BlockSeq._slice_out, self.Block, i), (args, kwargs) - ) - carry = block(carry, *block_args, **block_kwargs) - carry = tree_checkpoint_name(carry, self._carry_ckpt_name) - return carry - - do_fold = self.gradient_checkpointing.checkpoint(self._carry_ckpt_name, self._output_ckpt_name, do_fold) - - return do_fold(init, *args, **kwargs) + carry = init + for i, block in enumerate(self.blocks): + if self.gradient_checkpointing: + block = filter_checkpoint(block) + (block_args, block_kwargs) = haliax.tree_util.tree_map( + functools.partial(BlockSeq._slice_out, self.Block, i), (args, kwargs) + ) + carry = block(carry, *block_args, **block_kwargs) + return carry def unstacked(self) -> Sequence[M]: return self.blocks @@ -380,14 +174,6 @@ class BlockSeq(ModuleWithStateDictSerialization, Generic[M]): return state_dict - @property - def _output_ckpt_name(self): - return f"BlockSeq[{self.Block}, {self.blocks[0].__class__.__name__}].outputs" - - @property - def _carry_ckpt_name(self): - return f"BlockSeq[{self.Block}, {self.blocks[0].__class__.__name__}].carry" - class Stacked(ModuleWithStateDictSerialization, Generic[M]): """ @@ -406,12 +192,12 @@ class Stacked(ModuleWithStateDictSerialization, Generic[M]): that the function has the same control flow for every element of the stack. Stacked supports both "fold" and "scan" semantics. "fold" is the same as a for loop that accumulates a single - output, while "scan" is the same as a for loop that accumulates a list of outputs as well as the final output. + output, while "scan" is the same as a for loop that accumulates a list of intermediates as well as the final output. Stacked also supports gradient checkpointing, which is useful for very large models that don't fit in memory. Typically only one of "fold" or "scan" can be used with a given Stacked module, depending on the what the module - returns: if the module returns a single output, use "fold"; if the module returns a sequence of outputs and + returns: if the module returns a single output, use "fold"; if the module returns a sequence of intermediates and an output to be passed to the next layer, use "scan". More concretely, for a transformer, you would use "scan" if you wanted to return a kv cache (or the attention matrix) as well as the output of the transformer. If you just wanted the output of the transformer, you would use "fold". @@ -441,65 +227,48 @@ class Stacked(ModuleWithStateDictSerialization, Generic[M]): stacked: M Block: Axis = eqx.static_field() - gradient_checkpointing: StackedCheckpointPolicy = eqx.static_field() + # TODO: support fancier gradient checkpointing + gradient_checkpointing: bool = eqx.static_field() + prevent_cse: bool = eqx.static_field() @classmethod def init( - cls, - Block: Axis, - module: Type[M], - *, - gradient_checkpointing: bool | StackedCheckpointPolicy | str = False, - prevent_cse: bool | None = None, + cls, Block: Axis, module: Type[M], *, gradient_checkpointing: bool = False, prevent_cse: bool = False ) -> ModuleInit["Stacked[M]"]: """ Initialize a Stacked module. This method is curried: you can pass in the Block and module, and it will return a function that takes (batched) arguments to the vmapped module's init method. - - Args: - Block: The axis that will be stacked over. This is typically a "layer" axis, but could be any axis. - module: The module that will be stacked. This module must take a batched input and return a batched output. - gradient_checkpointing: Whether to use gradient checkpointing. If True, uses the default policy. If a string, - uses the policy specified by the string. If a StackedCheckpointPolicy, uses that policy. - prevent_cse: Whether to prevent common subexpression elimination in the checkpointed function. This is useful - for debugging, but may slow down the function. + :param Block: + :param module: + :param gradient_checkpointing: + :param prevent_cse: + :return: """ - gradient_checkpointing = StackedCheckpointPolicy._mk(gradient_checkpointing) - - if prevent_cse is not None: - warnings.warn( - "The prevent_cse argument is deprecated and will be removed in a future version of Haliax. Use the" - " StackedCheckpointPolicy instead.", - DeprecationWarning, - ) - - gradient_checkpointing = dataclasses.replace(gradient_checkpointing, prevent_cse=prevent_cse) - @functools.wraps(module) def fn(*args, **kwargs): stacked = haliax.vmap(module.init, Block)(*args, **kwargs) - return Stacked(stacked, Block, gradient_checkpointing) + return Stacked(stacked, Block, gradient_checkpointing, prevent_cse) return fn def scan(self, init, *extra_args, **extra_kwargs): """ Scan over the stacked module. This is the same as a for loop that applies each instance of the module in sequence - to the input, passing the output of one instance to the next instance. It returns a stack of outputs as + to the input, passing the output of one instance to the next instance. It returns a stack of intermediates as well as the final output. That is, it behaves similarly to the following Python code: ```python carry = init - outputs = [] + intermediates = [] for block in self.stacked: carry, extra = block(carry) - outputs.append(extra) + intermediates.append(extra) - return carry, hax.stack(Block, outputs) + return carry, hax.stack(Block, intermediates) ``` Args: @@ -510,24 +279,11 @@ class Stacked(ModuleWithStateDictSerialization, Generic[M]): Returns: """ - carry_name = self._carry_ckpt_name - output_name = self._output_ckpt_name - - def do_block(carry, block, *args, **kwargs): - carry, out = block(carry, *args, **kwargs) - carry = tree_checkpoint_name(carry, carry_name) - out = tree_checkpoint_name(out, output_name) - return carry, out - - def do_scan(init, *extra_args, **extra_kwargs): - carry, out = haliax.scan(do_block, self.Block)(init, self.stacked, *extra_args, **extra_kwargs) - # carry = _tree_checkpoint_name(carry, carry_name) - # out = _tree_checkpoint_name(out, output_name) - return carry, out - - do_scan = self.gradient_checkpointing.checkpoint(carry_name, output_name, do_scan) - - return do_scan(init, *extra_args, **extra_kwargs) + if self.gradient_checkpointing: + do_block = filter_checkpoint(self._do_block, prevent_cse=self.prevent_cse) + else: + do_block = self._do_block + return haliax.scan(do_block, self.Block)(init, self.stacked, *extra_args, **extra_kwargs) def fold(self, init, *args, **kwargs): """ @@ -544,26 +300,19 @@ class Stacked(ModuleWithStateDictSerialization, Generic[M]): ``` Args: - init: The initial value of carry to pass to the first block - *args: Extra arguments to pass to the blocks. These are passed directly to the blocks - **kwargs: Extra keyword arguments to pass to the blocks. These are passed directly to the blocks + init: + *args: + **kwargs: Returns: """ - carry_name = self._carry_ckpt_name - - def do_block(carry, block, *args, **kwargs): - carry = block(carry, *args, **kwargs) - carry = tree_checkpoint_name(carry, carry_name) - return carry - - def do_fold(init, *extra_args, **extra_kwargs): - return haliax.fold(do_block, self.Block)(init, self.stacked, *extra_args, **extra_kwargs) - - do_scan = self.gradient_checkpointing.checkpoint(carry_name, self._output_ckpt_name, do_fold) + if self.gradient_checkpointing: + do_block = filter_checkpoint(self._do_block, prevent_cse=self.prevent_cse) + else: + do_block = self._do_block - return do_scan(init, *args, **kwargs) + return haliax.fold(do_block, self.Block)(init, self.stacked, *args, **kwargs) @staticmethod def _do_block(carry, block, *extra_args, **extra_kwargs): @@ -614,14 +363,6 @@ class Stacked(ModuleWithStateDictSerialization, Generic[M]): out = super().from_state_dict(stacked, prefix=prefix) # type: ignore return out - @property - def _carry_ckpt_name(self): - return f"Stacked[{self.Block}, {self.stacked.__class__.__name__}].carry" - - @property - def _output_ckpt_name(self): - return f"Stacked[{self.Block}, {self.stacked.__class__.__name__}].outputs" - def _stack_state_dict(state_dict: StateDict, prefix: Optional[str] = None) -> StateDict: """ diff --git a/src/haliax/random.py b/src/haliax/random.py index 9d2c4ea..68f276f 100644 --- a/src/haliax/random.py +++ b/src/haliax/random.py @@ -24,6 +24,7 @@ def uniform( minval = broadcast_to(minval, shape).array maxval = broadcast_to(maxval, shape).array jax_shape = _to_jax_shape(shape) + print(jax_shape, minval, maxval) jax_array = jrandom.uniform(key=key, shape=jax_shape, dtype=dtype, minval=minval, maxval=maxval) return haliax.auto_sharded(NamedArray(jax_array, shape)) diff --git a/tests/test_scan.py b/tests/test_scan.py index e1d4377..a7b6cf6 100644 --- a/tests/test_scan.py +++ b/tests/test_scan.py @@ -1,11 +1,9 @@ import equinox as eqx import jax import pytest -from equinox import filter_value_and_grad import haliax as hax -from haliax.jax_utils import tree_checkpoint_name -from haliax.nn.scan import BlockSeq, Stacked, StackedCheckpointPolicy +from haliax.nn.scan import BlockSeq, Stacked def test_unstacked(): @@ -132,6 +130,8 @@ def test_scan_with_aux_named_args(): z_seq, z_seq_scan = m_seq.scan(x, initial_y, key=jax.random.split(jax.random.PRNGKey(2), Block.size)) assert hax.all(hax.isclose(z, z_seq, atol=1e-5)) + z_seq_scan = hax.stack(Block, z_seq_scan) + assert hax.all(hax.isclose(z_scan, z_seq_scan, atol=1e-5)) @@ -164,56 +164,3 @@ def test_stacked_to_state_dict(): y2 = m2.fold(input, key=key) assert hax.all(hax.equal(y, y2)) - - -def test_checkpoint_carries(): - class Module(eqx.Module): - named: hax.NamedArray - - def __call__(self, x): - y = tree_checkpoint_name(hax.sin(x + self.named), "sin") - y = tree_checkpoint_name(hax.cos(y + x), "cos") - return y + x - - @staticmethod - def init(named): - return Module(named=named) - - Block = hax.Axis("block", 4) - E = hax.Axis("E", 10) - - initial_named = hax.random.uniform(jax.random.PRNGKey(0), (Block, E)) - - carry_policy = StackedCheckpointPolicy(save_carries=True, save_outputs=False, save_block_internals=False) - save_nothing = StackedCheckpointPolicy(save_carries=False, save_outputs=False, save_block_internals=False) - save_everything = StackedCheckpointPolicy(save_carries=True, save_outputs=True, save_block_internals=True) - save_internals = StackedCheckpointPolicy(save_carries=False, save_outputs=False, save_block_internals=True) - save_cos = StackedCheckpointPolicy(save_carries=False, save_outputs=False, save_block_internals=["cos"]) - save_sin_carry = StackedCheckpointPolicy(save_carries=True, save_outputs=False, save_block_internals=["sin"]) - - for name, (policy, expected_scan_shapes) in { - "carry": (carry_policy, [(E.size,), (Block.size, E.size)]), - "nothing": (save_nothing, [(E.size,)]), - "everything": (save_everything, [(E.size,), (Block.size, E.size), (Block.size, E.size)]), - "internals": (save_internals, [(E.size,), (Block.size, E.size), (Block.size, E.size)]), - "cos": (save_cos, [(E.size,), (Block.size, E.size)]), - "sin": (save_sin_carry, [(E.size,), (Block.size, E.size), (Block.size, E.size)]), - }.items(): - m = Stacked.init( - Block, - Module, - gradient_checkpointing=policy, - )(named=initial_named) - - def loss_fn(m, x): - y = m.fold(x) - return hax.sum(y).scalar() - - grad_fn = filter_value_and_grad(loss_fn) - - jaxpr = jax.make_jaxpr(grad_fn)(m, hax.random.uniform(jax.random.PRNGKey(1), (E,))) - closed_call = next(eqn for eqn in jaxpr.jaxpr.eqns if eqn.primitive == jax.core.closed_call_p) - out_shapes = [out.aval.shape for out in closed_call.outvars] - - # saved_residuals doesn't give me sensible results, so I'm doing this by hand - assert out_shapes == expected_scan_shapes, f"{name}: Expected {expected_scan_shapes}, got {out_shapes}" commit f9415109610fe20fe0af7b6bc1f95ce1169c91f1 Date: 2025-03-10T14:45:34-07:00 Merge remote-tracking branch 'origin/main' commit 00a1703e0fa769776558e0841c61e43fa5a2d43a Date: 2025-03-13T23:48:32-07:00 Fix docstring (#124) diff --git a/src/haliax/nn/linear.py b/src/haliax/nn/linear.py index e132e32..c4ece92 100644 --- a/src/haliax/nn/linear.py +++ b/src/haliax/nn/linear.py @@ -41,7 +41,7 @@ class Linear(eqx.Module): key: PRNGKeyArray: The PRNG key to use for initialization use_bias: bool: Whether to use a bias term out_first: bool: Whether to put output axes first in the weight matrix. out_first is how PyTorch does it. - dot_general: Callable: The dot_general function to use. Defaults to jax.lax.dot_general. For fp8 or int8 + dot_general: Callable: The dot_general function to use. Defaults to jax.lax.dot_general. init_scale: float: The scale to use for initialization. We scale init by 1/sqrt(Input.size)*init_scale """ joint_spec = hax.concat_axis_specs(Out, In) if out_first else hax.concat_axis_specs(In, Out) commit 6b791713222795a99c3c0ea5c03716f39a6f2f97 Date: 2025-03-19T15:33:43-07:00 Add RmsNorm, generalize pytorch export flattening stuff to make it pluggable (#125) * wip * extend the flattening/unflattening module system to be pluggable, add support for LayerNorms * explictly test layer norm flattening * wip * fix tests? * grr * madkmalkd. diff --git a/.github/workflows/run_quick_levanter_tests.yaml b/.github/workflows/run_quick_levanter_tests.yaml index 333cbbf..68ec21c 100644 --- a/.github/workflows/run_quick_levanter_tests.yaml +++ b/.github/workflows/run_quick_levanter_tests.yaml @@ -17,19 +17,21 @@ jobs: run: | python -m pip install --upgrade pip pip install flake8 pytest - pip install --upgrade "jax[cpu]==0.4.35" "jaxlib[cpu]==0.4.35" + pip install "jax[cpu]==0.5.3" "jaxlib[cpu]==0.5.3" .[dev] - name: Install Levanter from source run: | cd .. git clone https://github.com/stanford-crfm/levanter.git cd levanter - pip install -e . + pip install -e .[tests] + pip install -r tests/requirements.txt + # i don't know why this is necessary + pip install tensorboardX - name: Install Haliax on top run: | # install second since levanter will install a built version of haliax cd ../haliax - pip install "jax[cpu]==0.4.35" "jaxlib[cpu]==0.4.35" .[dev] - name: Test levanter with pytest run: | cd ../levanter diff --git a/docs/nn.md b/docs/nn.md index 78ddb4c..5e39c3f 100644 --- a/docs/nn.md +++ b/docs/nn.md @@ -18,7 +18,10 @@ of the same module (e.g. transformer blocks), which is a common pattern in deep ::: haliax.nn.Dropout ### Normalization + +::: haliax.nn.normalization.LayerNormBase ::: haliax.nn.LayerNorm +::: haliax.nn.RmsNorm ### Meta diff --git a/docs/state-dict.md b/docs/state-dict.md index 10f53f3..395c1ce 100644 --- a/docs/state-dict.md +++ b/docs/state-dict.md @@ -122,6 +122,7 @@ For example, below is the implementation of `to_state_dict()` in [levanter.model In this class, we want to preserve HF compatibility by saving untied output embeddings. (We chose not to implement non-weight-tied embeddings.) + ```python from typing import Optional @@ -155,8 +156,69 @@ to join the prefix to the keys of the state dict. ``` +#### Flattening and Unflattening + +Haliax differs from many NN frameworks, and PyTorch in particular, in supporting multiple axes as inputs and outputs +for linear transformations and layer norms. This means that a Linear layer's weight might have shape `(Heads, Dim, Out)` +rather than just `(In, Out)` (where `In = Heads * Dim`). To facilitate compatibility with PyTorch, we provide +two functions, `flatten_modules_for_export` and `unflatten_modules_from_export`, that can be used to convert +modules to and from a format that is compatible with PyTorch. These functions are used internally by +`to_torch_compatible_state_dict` and `from_torch_compatible_state_dict` and we expose them for advanced users. + +If you are adding a new module, you can plug into this system by inheriting from [haliax.state_dict.ModuleWithStateDictSerialization][] +and overriding the `flatten_for_export` and `unflatten_from_export` methods. Here is an example from [haliax.nn.LayerNorm][]: + +```python +Mod = TypeVar("Mod") + +class LayerNormBase(ModuleWithStateDictSerialization): + def flatten_for_export(self: Mod) -> Mod: + if isinstance(self.axis, hax.Axis): + return self + + if self.weight is not None: + weight = self.weight.flatten("__OUT") + else: + weight = None + + if self.bias is not None: + bias = self.bias.flatten("__OUT") + else: + bias = None + + return dataclasses.replace( + self, weight=weight, bias=bias, axis=hax.flatten_axes(self.axis, "__OUT") + ) + + def unflatten_from_export(self: Mod, template: Mod) -> Mod: + if template.axis == self.axis: + return self + + if self.weight is not None: + assert isinstance(self.axis, hax.Axis), "Cannot unflatten weight with non-axis axis" + weight = hax.unflatten_axis(self.weight, self.axis, template.axis) + else: + weight = None + + if self.bias is not None: + assert isinstance(self.axis, hax.Axis), "Cannot unflatten weight with non-axis axis" + bias = hax.unflatten_axis(self.bias, self.axis, template.axis) + + else: + bias = None + + return dataclasses.replace( + self, weight=weight, bias=bias, axis=template.axis + ) +``` + +The code is a bit boilerplate-y but the idea is to find articulated axes in arrays and flatten them, while updating +any Axis members to match the new shape. + ## API Reference +### Types + ::: haliax.state_dict.StateDict ::: haliax.state_dict.ModuleWithStateDictSerialization @@ -173,5 +235,5 @@ to join the prefix to the keys of the state dict. ::: haliax.state_dict.from_torch_compatible_state_dict ::: haliax.state_dict.to_torch_compatible_state_dict -::: haliax.state_dict.flatten_linear_layers -::: haliax.state_dict.unflatten_linear_layers +::: haliax.state_dict.flatten_modules_for_export +::: haliax.state_dict.unflatten_modules_from_export diff --git a/src/haliax/_src/state_dict.py b/src/haliax/_src/state_dict.py index a5325e4..b76e4f6 100644 --- a/src/haliax/_src/state_dict.py +++ b/src/haliax/_src/state_dict.py @@ -18,6 +18,7 @@ from haliax._src.util import index_where from haliax.axis import Axis from haliax.core import NamedArray, flatten_axes, named from haliax.jax_utils import is_jax_array_like, is_scalarish +from haliax.tree_util import scan_aware_tree_map try: @@ -32,14 +33,16 @@ T = TypeVar("T") def from_torch_compatible_state_dict( - t: T, state_dict: StateDict, *, unflatten_linear: bool = True, prefix: Optional[str] = None + t: T, state_dict: StateDict, *, unflatten: bool = True, prefix: Optional[str] = None ) -> T: """ Convert a state dict to a tree that is compatible with the structure of `t`. - This applies [haliax.state_dict.from_state_dict][] followed by [haliax.state_dict.unflatten_linear_layers][]. + If unflatten is true, then the weights in the state dict are assumed to have been flattened (as by flatten_modules_for_export). + + This applies [haliax.state_dict.from_state_dict][] """ - if unflatten_linear: + if unflatten: t = _flatten_to_unflatten(t, state_dict, prefix) else: t = from_state_dict(t, state_dict, prefix=prefix) @@ -47,6 +50,45 @@ def from_torch_compatible_state_dict( return t +def flatten_modules_for_export(t: T) -> T: + """ + Flatten all modules in a tree for export to torch. + """ + + def _flatten_module(module): + if isinstance(module, ModuleWithStateDictSerialization): + module = module.flatten_for_export() + module = jax.tree.map( + _flatten_module, + module, + is_leaf=lambda x: x is not module and isinstance(x, ModuleWithStateDictSerialization), + ) + return module + + return scan_aware_tree_map(_flatten_module, t, is_leaf=lambda x: isinstance(x, ModuleWithStateDictSerialization)) + + +def unflatten_modules_from_export(t: T, template: T) -> T: + """ + Unflatten all modules in a tree after import from torch. + """ + + def _unflatten_module(module, template): + if isinstance(module, ModuleWithStateDictSerialization): + module = module.unflatten_from_export(template) + module = jax.tree.map( + _unflatten_module, + module, + template, + is_leaf=lambda x: x is not module and isinstance(x, ModuleWithStateDictSerialization), + ) + return module + + return scan_aware_tree_map( + _unflatten_module, t, template, is_leaf=lambda x: isinstance(x, ModuleWithStateDictSerialization) + ) + + def _flatten_to_unflatten(t, state_dict, prefix): """ Flatten the torch compatible state_dict before loading into t, and then recover the unflattened layers. @@ -59,9 +101,9 @@ def _flatten_to_unflatten(t, state_dict, prefix): return jnp.zeros(struct.shape, struct.dtype) t = jax.tree.map(_dt_struct_to_array, t) - flat_t = flatten_linear_layers(t) + flat_t = flatten_modules_for_export(t) flat_t = from_state_dict(flat_t, state_dict, prefix=prefix) - t = unflatten_linear_layers(t, flat_t) + t = unflatten_modules_from_export(flat_t, t) return t @@ -103,6 +145,25 @@ class ModuleWithStateDictSerialization(eqx.Module): """Returns a dict mapping eqx.Module keys to torch keys that need to be renamed for serialization""" return {} + def flatten_for_export(self: Mod) -> Mod: + """ + Flatten articulated named arrays for export to torch. In general this method should, for a linear layer, flatten + all input axes into a single axis, and all output axes into a single axis. You can do whatever else + you want to support pytorch-compatible serialization if you want. + + This method is less general than to_state_dict and is only called when using to_torch_compatible_state_dict. + """ + return self + + def unflatten_from_export(self: Mod, template: Mod) -> Mod: + """ + Unflatten the module after import from torch. + + Template has the proper structure (e.g. articulated named axes) but the values are meaningless. + """ + del template + return self + def from_state_dict(tree: T, state_dict: StateDict, prefix: Optional[str] = None) -> T: """ @@ -372,78 +433,3 @@ def load_state_dict(path): """ state_dict = safetensors.numpy.load_file(path) return state_dict - - -def flatten_linear_layers(tree: T) -> T: - """ - In PyTorch, linear layers are stored as a 2d weight matrix and a 1d bias vector. In Haliax, - linear layers can have arbitrary dimensions, grouped into input and output axes. This function - flattens the linear layers in a tree to be compatible with PyTorch-style state dicts. - - :param tree: - """ - from haliax.nn import Linear - - def _flatten_linear(layer): - if not isinstance(layer, Linear): - return layer - - weight = layer.weight - bias = layer.bias - - new_Out: Axis = flatten_axes(layer.Out, "__OUT__") - new_In: Axis = flatten_axes(layer.In, "__IN__") - - if weight.array is not None: - out_first = layer._out_first - weight = weight.flatten_axes(layer.Out, new_Out).flatten_axes(layer.In, new_In) - - if out_first: - weight = weight.rearrange((..., "__OUT__", "__IN__")) - else: - weight = weight.rearrange((..., "__IN__", "__OUT__")) - - if isinstance(bias, NamedArray): - bias = bias.flatten_axes(layer.Out, new_Out) - - return dataclasses.replace(layer, weight=weight, bias=bias, In=new_In, Out=new_Out) # type: ignore - - return jax.tree.map(_flatten_linear, tree, is_leaf=lambda x: isinstance(x, Linear)) - - -def unflatten_linear_layers(template: T, tree_with_flattened_linears: T) -> T: - """ - Unflattens linear layers in a tree that was flattened with [haliax.state_dict.flatten_linear_layers][]. - Template has the same structure as the tree that was flattened, but with the original (unflattened) - linear layers. - - Returns: - The same tree as `tree_with_flattened_linears`, but with the linear layers unflattened to match - the structure of `template`. - """ - - from haliax.nn import Linear - - def _unflatten_linear(template, flattened): - assert isinstance(template, Linear) == isinstance(flattened, Linear) - - if not isinstance(template, Linear): - return flattened - - weight = flattened.weight - bias = flattened.bias - - if weight.array is not None: - weight = weight.unflatten_axis("__OUT__", template.Out).unflatten_axis("__IN__", template.In) - weight = weight.rearrange(template.weight.axes) - - if isinstance(bias, NamedArray): - bias = bias.unflatten_axis("__OUT__", template.Out) - assert template.bias is not None, "Flattened bias but template has no bias" - bias = bias.rearrange(template.bias.axes) - - return dataclasses.replace(template, weight=weight, bias=bias) # type: ignore - - return jax.tree.map( - _unflatten_linear, template, tree_with_flattened_linears, is_leaf=lambda x: isinstance(x, Linear) - ) diff --git a/src/haliax/nn/__init__.py b/src/haliax/nn/__init__.py index c343449..01662da 100644 --- a/src/haliax/nn/__init__.py +++ b/src/haliax/nn/__init__.py @@ -36,14 +36,11 @@ from .embedding import Embedding from .linear import Linear from .loss import binary_cross_entropy_loss, cross_entropy_loss, cross_entropy_loss_and_log_normalizers, reduce_loss from .mlp import MLP -from .normalization import LayerNorm, log_softmax, logsumexp, softmax, standardize +from .normalization import LayerNorm, RmsNorm, log_softmax, logsumexp, softmax, standardize from .pool import max_pool, mean_pool, min_pool from .scan import BlockSeq, Stacked -# TODO: support where in softmax, etc - - def one_hot(x: NamedArray | int, class_axis: Axis, *, dtype=None) -> NamedArray: """ Convert an integer to a one-hot vector. This is basically a generalization of [jax.nn.one_hot][] @@ -87,6 +84,7 @@ __all__ = [ "LayerNorm", "Linear", "Embedding", + "RmsNorm", "Stacked", "BlockSeq", "MLP", diff --git a/src/haliax/nn/linear.py b/src/haliax/nn/linear.py index c4ece92..7c8c1ee 100644 --- a/src/haliax/nn/linear.py +++ b/src/haliax/nn/linear.py @@ -1,3 +1,4 @@ +import dataclasses import math from typing import Optional @@ -6,13 +7,14 @@ from jax.random import PRNGKey import haliax as hax +from .._src.state_dict import Mod, ModuleWithStateDictSerialization from ..axis import AxisSpec from ..core import NamedArray from ..jax_utils import named_call from ..quantization import DotGeneralOp -class Linear(eqx.Module): +class Linear(ModuleWithStateDictSerialization): """A named Linear layer. This module allows you to specify multiple named axes for both input and output, which is occasionally useful.""" @@ -71,6 +73,47 @@ class Linear(eqx.Module): return q + def flatten_for_export(self: Mod) -> Mod: + if isinstance(self.Out, hax.Axis) and isinstance(self.In, hax.Axis): + return self + + weight = self.weight + bias = self.bias + + new_Out = hax.flatten_axes(self.Out, "__OUT__") + new_In = hax.flatten_axes(self.In, "__IN__") + + if weight.array is not None: + out_first = self._out_first + weight = weight.flatten_axes(self.Out, new_Out).flatten_axes(self.In, new_In) + + if out_first: + weight = weight.rearrange((..., "__OUT__", "__IN__")) + else: + weight = weight.rearrange((..., "__IN__", "__OUT__")) + + if isinstance(bias, NamedArray): + bias = bias.flatten_axes(self.Out, new_Out) + + return dataclasses.replace(self, weight=weight, bias=bias, In=new_In, Out=new_Out) + + def unflatten_from_export(self: Mod, template: Mod) -> Mod: + weight = self.weight + bias = self.bias + + if (template.In, template.Out) == (self.In, self.Out): + return self + + if weight.array is not None: + weight = weight.unflatten_axis("__OUT__", template.Out).unflatten_axis("__IN__", template.In) + weight = weight.rearrange(template.weight.axes) + + if isinstance(bias, NamedArray): + bias = bias.unflatten_axis("__OUT__", template.Out) + bias = bias.rearrange(template.bias.axes) + + return dataclasses.replace(template, weight=weight, bias=bias) + @property def _out_first(self): """ diff --git a/src/haliax/nn/normalization.py b/src/haliax/nn/normalization.py index 97dbf4e..8622c66 100644 --- a/src/haliax/nn/normalization.py +++ b/src/haliax/nn/normalization.py @@ -1,3 +1,5 @@ +import dataclasses +from abc import abstractmethod from typing import Optional, TypeVar import equinox as eqx @@ -7,6 +9,7 @@ from jax import numpy as jnp import haliax import haliax as hax +from .._src.state_dict import Mod, ModuleWithStateDictSerialization from ..axis import AxisSelection, AxisSpec from ..core import NamedArray from ..types import Scalar @@ -16,35 +19,114 @@ from ..wrap import unwrap_namedarrays, wrap_axiswise_call, wrap_reduction_call A = TypeVar("A", Scalar, NamedArray, jnp.ndarray) -class LayerNorm(eqx.Module): - r""" - Normalises the input along the specified axis (or axes), using the mean and variance of the - input along that axis. - """ +class LayerNormBase(ModuleWithStateDictSerialization): axis: AxisSpec = eqx.static_field() weight: Optional[NamedArray] bias: Optional[NamedArray] - eps: float = eqx.static_field(default=1e-5) + dtype: Optional[jnp.dtype] = eqx.field(default=None, static=True) - @staticmethod - def init(axis: AxisSpec, eps: float = 1e-5, use_weight: bool = True, use_bias: bool = True): + @abstractmethod + def __call__(self, x: NamedArray) -> NamedArray: + pass + + @classmethod + def init( + cls, + axis: AxisSpec, + eps: float = 1e-5, + *, + use_weight: bool = True, + use_bias: bool = True, + dtype: Optional[jnp.dtype] = None, + ): if use_weight: weight = hax.ones(axis) else: weight = None + if use_bias: bias = hax.zeros(axis) else: bias = None - return LayerNorm(axis, weight, bias, eps) + return cls(axis, weight, bias, eps, dtype) + + def flatten_for_export(self: Mod) -> Mod: + if isinstance(self.axis, hax.Axis): + return self + + if self.weight is not None: + weight = self.weight.flatten("__OUT") + else: + weight = None + + if self.bias is not None: + bias = self.bias.flatten("__OUT") + else: + bias = None + + return dataclasses.replace(self, weight=weight, bias=bias, axis=hax.flatten_axes(self.axis, "__OUT")) + + def unflatten_from_export(self: Mod, template: Mod) -> Mod: + if template.axis == self.axis: + return self + + if self.weight is not None: + assert isinstance(self.axis, hax.Axis), "Cannot unflatten weight with non-axis axis" + weight = hax.unflatten_axis(self.weight, self.axis, template.axis) + else: + weight = None + + if self.bias is not None: + assert isinstance(self.axis, hax.Axis), "Cannot unflatten weight with non-axis axis" + bias = hax.unflatten_axis(self.bias, self.axis, template.axis) + + else: + bias = None + + return dataclasses.replace(self, weight=weight, bias=bias, axis=template.axis) + + +class LayerNorm(LayerNormBase): + r""" + Normalises the input along the specified axis (or axes), using the mean and variance of the + input along that axis. + """ + axis: AxisSpec = eqx.field(static=True) + weight: Optional[NamedArray] + bias: Optional[NamedArray] + + eps: float = eqx.field(default=1e-5, static=True) + dtype: Optional[jnp.dtype] = eqx.field(default=None, static=True) def __call__(self, x: NamedArray) -> NamedArray: + dtype = x.dtype mean = x.mean(self.axis) var = x.var(self.axis) inv = hax.rsqrt(var + self.eps) out = (x - mean) * inv + out = out.astype(dtype) + + if self.weight is not None: + out = self.weight * out + if self.bias is not None: + out = out + self.bias + return out + + +class RmsNorm(LayerNormBase): + r""" + Implements RMS normalization, which normalizes the input by dividing by the root mean square of the input. + """ + + def __call__(self, x: NamedArray) -> NamedArray: + in_dtype = x.dtype + x = x.astype(self.dtype) + var = hax.mean(hax.square(x), axis=self.axis) + inv = hax.rsqrt(var + self.eps) + out = x * inv + out = out.astype(in_dtype) if self.weight is not None: out = self.weight * out diff --git a/src/haliax/state_dict.py b/src/haliax/state_dict.py index fdf7a70..6863d00 100644 --- a/src/haliax/state_dict.py +++ b/src/haliax/state_dict.py @@ -8,14 +8,14 @@ from haliax.types import FilterSpec from ._src.state_dict import ( ModuleWithStateDictSerialization, StateDict, - flatten_linear_layers, + flatten_modules_for_export, from_state_dict, from_torch_compatible_state_dict, load_state_dict, save_state_dict, to_numpy_state_dict, to_state_dict, - unflatten_linear_layers, + unflatten_modules_from_export, with_prefix, ) @@ -24,23 +24,23 @@ T = TypeVar("T") def to_torch_compatible_state_dict( - t: T, *, flatten_linear: bool = True, prefix: Optional[str] = None, filter: FilterSpec = is_jax_array_like + t: T, *, flatten: bool = True, prefix: Optional[str] = None, filter: FilterSpec = is_jax_array_like ) -> StateDict: """ Convert a tree to a state dict that is compatible with torch-style state dicts. - This applies [haliax.state_dict.flatten_linear_layers][] followed by [haliax.state_dict.to_state_dict][] + This applies the same logic as [to_state_dict][] but also uses [haliax.state_dict.ModuleWithStateDictSerialization.flatten_for_export][] to flatten Args: t: The tree to convert - flatten_linear: Whether to flatten linear layers + flatten: Whether to flatten axes using flatten_for_export prefix: The prefix to use for the state dict keys filter: The filter to use for selecting which nodes to include in the state dict. By default, this includes only array-like objects (e.g. JAX and NumPy arrays). """ t = equinox.filter(t, filter) - if flatten_linear: - t = flatten_linear_layers(t) + if flatten: + t = flatten_modules_for_export(t) return to_numpy_state_dict(t, prefix=prefix) @@ -50,11 +50,11 @@ __all__ = [ "load_state_dict", "save_state_dict", "from_state_dict", - "flatten_linear_layers", - "unflatten_linear_layers", "with_prefix", "to_state_dict", "to_numpy_state_dict", "StateDict", "to_torch_compatible_state_dict", + "flatten_modules_for_export", + "unflatten_modules_from_export", ] diff --git a/src/haliax/tree_util.py b/src/haliax/tree_util.py index 3c21c72..c72d276 100644 --- a/src/haliax/tree_util.py +++ b/src/haliax/tree_util.py @@ -30,17 +30,10 @@ def tree_map(fn, tree, *rest, is_leaf=None): def scan_aware_tree_map(fn, tree, *rest, is_leaf=None): """ - Version of [haliax.tree_util.tree_map][] that is aware of the scan-layer pattern, specifically as implmeneted + Version of [haliax.tree_util.tree_map][] that is aware of the scan-layer pattern, specifically as implemented in hax.nn.Stacked. This function will (implicitly) apply the transform to each layer in each Stacked module (using vmap). If there are no Stacked modules in the tree, this function is equivalent to [haliax.tree_util.tree_map][]. - Args: - fn: - tree: - *rest: - is_leaf: - - Returns: """ old_is_leaf = is_leaf if is_leaf is None: @@ -55,7 +48,7 @@ def scan_aware_tree_map(fn, tree, *rest, is_leaf=None): new_inner = haliax.vmap(mapped_fn, x.Block)(x.stacked, *[r.stacked for r in rest]) return dataclasses.replace(x, stacked=new_inner) # type: ignore else: - return fn(x) + return fn(x, *rest) return tree_map(rec_fn, tree, *rest, is_leaf=is_leaf) diff --git a/tests/test_state_dict.py b/tests/test_state_dict.py index fe08962..90d72db 100644 --- a/tests/test_state_dict.py +++ b/tests/test_state_dict.py @@ -1,3 +1,4 @@ +import dataclasses from typing import Any import equinox as eqx @@ -8,7 +9,7 @@ import pytest import haliax as hax from haliax.nn import Linear from haliax.nn.scan import _stack_state_dict, _unstack_state_dict -from haliax.state_dict import flatten_linear_layers, from_state_dict, to_state_dict, unflatten_linear_layers +from haliax.state_dict import from_state_dict, to_state_dict @pytest.mark.parametrize("out_dims_first", [True, False]) @@ -24,7 +25,7 @@ def test_flatten_linear_layers(out_dims_first: bool): else: assert linear.weight.axes == (H, W, D, B) - flat_linear = flatten_linear_layers(linear) + flat_linear = linear.flatten_for_export() flat_state_dict = to_state_dict(flat_linear) if out_dims_first: @@ -36,7 +37,7 @@ def test_flatten_linear_layers(out_dims_first: bool): # now unflatten it linear2 = Linear.init((H, W), (D, B), key=jax.random.PRNGKey(1), use_bias=True, out_first=out_dims_first) - new_linear = unflatten_linear_layers(linear2, flat_linear) + new_linear = flat_linear.unflatten_from_export(linear2) if out_dims_first: assert new_linear.weight.axes == (D, B, H, W) @@ -127,3 +128,26 @@ def test_to_from_state_dict(): m2 = from_state_dict(m2, state_dict) assert jnp.all(m2.a == a) assert jnp.all(m2.b == b) + + +def test_export_layer_norm(): + D = hax.Axis("D", 10) + E = hax.Axis("E", 20) + layer_norm = hax.nn.LayerNorm.init((D, E), eps=1e-5, use_weight=True, use_bias=True) + + flat_layer_norm = layer_norm.flatten_for_export() + + flat_state_dict = to_state_dict(flat_layer_norm) + + assert flat_state_dict["weight"].shape == (D.size * E.size,) + assert flat_state_dict["bias"].shape == (D.size * E.size,) + assert flat_state_dict["weight"].dtype == flat_state_dict["bias"].dtype == layer_norm.weight.dtype + + # now unflatten it + layer_norm2 = hax.nn.LayerNorm.init((D, E), eps=1e-5, use_weight=True, use_bias=True) + # ensure we have different weights + layer_norm2 = dataclasses.replace(layer_norm2, weight=layer_norm2.weight + 1, bias=layer_norm2.bias + 1) + + new_layer_norm = flat_layer_norm.unflatten_from_export(layer_norm2) + + assert layer_norm == new_layer_norm commit 1882172fba6a619e286eabc88e7642e7cc92622c Date: 2025-03-20T09:44:39-07:00 missed some scan_aware tree_maps (#126) * wip * extend the flattening/unflattening module system to be pluggable, add support for LayerNorms * explictly test layer norm flattening * wip * fix tests? * grr * madkmalkd. * missed some scan_aware tree_maps * test for recursive unflatten diff --git a/src/haliax/_src/state_dict.py b/src/haliax/_src/state_dict.py index b76e4f6..576a256 100644 --- a/src/haliax/_src/state_dict.py +++ b/src/haliax/_src/state_dict.py @@ -58,7 +58,7 @@ def flatten_modules_for_export(t: T) -> T: def _flatten_module(module): if isinstance(module, ModuleWithStateDictSerialization): module = module.flatten_for_export() - module = jax.tree.map( + module = scan_aware_tree_map( _flatten_module, module, is_leaf=lambda x: x is not module and isinstance(x, ModuleWithStateDictSerialization), @@ -76,7 +76,7 @@ def unflatten_modules_from_export(t: T, template: T) -> T: def _unflatten_module(module, template): if isinstance(module, ModuleWithStateDictSerialization): module = module.unflatten_from_export(template) - module = jax.tree.map( + module = scan_aware_tree_map( _unflatten_module, module, template, diff --git a/tests/test_state_dict.py b/tests/test_state_dict.py index 90d72db..ed3e888 100644 --- a/tests/test_state_dict.py +++ b/tests/test_state_dict.py @@ -7,8 +7,9 @@ import jax.numpy as jnp import pytest import haliax as hax +from haliax._src.state_dict import flatten_modules_for_export, unflatten_modules_from_export from haliax.nn import Linear -from haliax.nn.scan import _stack_state_dict, _unstack_state_dict +from haliax.nn.scan import Stacked, _stack_state_dict, _unstack_state_dict from haliax.state_dict import from_state_dict, to_state_dict @@ -151,3 +152,26 @@ def test_export_layer_norm(): new_layer_norm = flat_layer_norm.unflatten_from_export(layer_norm2) assert layer_norm == new_layer_norm + + +def test_stacked_layer_norm(): + L = hax.Axis("L", 4) + D = hax.Axis("D", 10) + E = hax.Axis("E", 20) + + norms = Stacked.init(L, hax.nn.LayerNorm)((D, E), eps=1e-5, use_weight=True, use_bias=True) + + norms_flat = flatten_modules_for_export(norms) + + flat_state_dict = to_state_dict(norms_flat) + + assert flat_state_dict["0.weight"].shape == (D.size * E.size,) + assert flat_state_dict["0.bias"].shape == (D.size * E.size,) + assert flat_state_dict["1.weight"].shape == (D.size * E.size,) + + # now unflatten it + norms2 = Stacked.init(L, hax.nn.LayerNorm)((D, E), eps=1e-5, use_weight=True, use_bias=True) + + new_norms = unflatten_modules_from_export(norms_flat, norms2) + + assert norms == new_norms commit 23284432bbe0bbcf41af8f2e6c0ba28f7c2f8875 Date: 2025-03-26T12:03:07-07:00 Fancier Checkpointing Strategies, again (#127) * Reapply "Support much deeper configuration for checkpointing in Stacked (#121)" This reverts commit 685e77d24197131016686c5bc1ee9553893e9aa5. * ok this works i think * wip * add checkpointed_scan * move stuff * docs, cleanup * made a mistake * wip * document nested scans a bit more. * more docs! diff --git a/docs/api.md b/docs/api.md index be4bcfd..1dd3fc6 100644 --- a/docs/api.md +++ b/docs/api.md @@ -295,7 +295,7 @@ See also the section on [Partitioning](partitioning.md). Haliax mainly just defers to JAX and [equinox.filter_checkpoint][] for gradient checkpointing. However, we provide a few utilities to make it easier to use. -See also [haliax.nn.StackedCheckpointPolicy][]. +See also [haliax.nn.ScanCheckpointPolicy][]. ::: haliax.tree_checkpoint_name diff --git a/docs/hof.md b/docs/hof.md deleted file mode 100644 index 64b7656..0000000 --- a/docs/hof.md +++ /dev/null @@ -1,16 +0,0 @@ -# Higher-Order Functions - -JAX has a number of higher order functions (e.g. [jax.vmap][], [jax.lax.scan][]) that correspond to traditional -functional programming concepts. Haliax provides named versions of these functions that operate on named arrays/named -axes. - -## Vectorization - -::: haliax.vmap - - -## Looping and Scanning - -::: haliax.fold -::: haliax.scan -::: haliax.map diff --git a/docs/nn.md b/docs/nn.md index 5e39c3f..fcb16c7 100644 --- a/docs/nn.md +++ b/docs/nn.md @@ -29,7 +29,7 @@ of the same module (e.g. transformer blocks), which is a common pattern in deep ### Stacked -See the full documentation of [Stacked](stacked.md). +See the full documentation of [Stacked](scan.md#stacked). ### Convolution diff --git a/docs/scan.md b/docs/scan.md new file mode 100644 index 0000000..86b5494 --- /dev/null +++ b/docs/scan.md @@ -0,0 +1,456 @@ +# Scan and Fold + +A common pattern in deep learning is to apply a sequence of layers to an input, feeding the output from one +layer to the next. In JAX, this is often done with [jax.lax.scan][]. + +As the docs say, scan does an operation sort of like this in Python: + +```python +def scan(f, init, xs, length=None): + if xs is None: + xs = [None] * length + carry = init + ys = [] + for x in xs: + carry, y = f(carry, x) + ys.append(y) + return carry, np.stack(ys) +``` + +Haliax provides two versions of this pattern: [haliax.fold][] and [haliax.scan][]. haliax.scan works much like JAX's scan, +except it is curried and it works with NamedArrays. haliax.fold is a more restricted version of scan that is easier to +use if you don't need the full generality of scan. (It works with functions that only return `carry`, not `carry, output`.) + +## `haliax.scan` + +Unlike JAX's scan, Haliax's scan is curried - it takes the function and configuration first, then the initial carry and scan arguments as a separate call: `scan(f, axis)(init, xs)`. + +### Key Features +* Works with named axes using [haliax.NamedArray][] +* Supports gradient checkpointing for memory efficiency, including several advanced checkpointing policies +* Integrates with [equinox.Module][] for building neural networks + +### Basic Example + +Here's a practical example of using `haliax.scan` to sum values along an axis while keeping track of intermediates: + +```python +Time = Axis("Time", 100) +Features = Axis("Features", 16) + +# Create time series data +data = hax.random.normal(PRNGKey(0), (Time, Features)) + +def running_stats(state, x): + count, mean, min_val, max_val = state + count += 1 + # this is a common pattern to improve the robustness of the mean calculation + delta = x - mean + mean = mean + delta / count + min_val = hax.minimum(min_val, x) + max_val = hax.maximum(max_val, x) + + return (count, mean, min_val, max_val), mean + + +# Initialize state: (count, mean, min, max) +init_state = ( + 0.0, + hax.zeros((Features,)), + hax.full((Features,), float('inf')), + hax.full((Features,), float('-inf')) +) + +final_state, running_means = hax.scan(running_stats, Time)(init_state, data) +``` + +Note that: + +* `scan` is curried: `scan(f, axis)(init, xs)` +* `running_stats` returns a tuple of `(carry, output)`, which is why we have two return values from `scan` +* the running_means will have shape `(Time, Features)`, with the mean at each time step +* the final_state will have the same shape as the initial state + + +### Using `scan` with no inputs +You can also use scan without any inputs if you want: + +```python +Time = Axis("Time", 100) +Features = Axis("Features", 16) + +def simulate_brownian_motion(state, _): + return state + hax.random.normal(PRNGKey(0), Features), state + +init_state = hax.zeros((Features,)) + +final_state, path = hax.scan(simulate_brownian_motion, Time)(init_state, None) +``` + +More commonly, you might use this for an RNN or Transformer model. (See [haliax.nn.Stacked][].) + +## `haliax.fold` + +`haliax.fold` is a simpler version of `haliax.scan` that is easier to use when you don't need the full generality of `scan`. +Specifically, `fold` is for functions that only return a `carry`, not a `carry, output`. + +Morally, `fold` is like this Python code: + +```python +def fold(f, init, xs): + carry = init + for x in xs: + carry = f(carry, x) + return carry +``` + +### Basic Example + +Same example, but we only care about the final state: + +```python +Time = Axis("Time", 100) +Features = Axis("Features", 16) + +# Create time series data +data = hax.random.normal(PRNGKey(0), (Time, Features)) + +def running_stats(state, x): + count, mean, min_val, max_val = state + count += 1 + # this is a common pattern to improve the robustness of the mean calculation + delta = x - mean + mean = mean + delta / count + min_val = hax.minimum(min_val, x) + max_val = hax.maximum(max_val, x) + + return (count, mean, min_val, max_val) + + +# Initialize state: (count, mean, min, max) +init_state = ( + 0.0, + hax.zeros((Features,)), + hax.full((Features,), float('inf')), + hax.full((Features,), float('-inf')) +) + +final_state = hax.fold(running_stats, Time)(init_state, data) +``` + +## `haliax.map` + +`haliax.map` is a convenience function that applies a function to each element of an axis. It is similar +to [jax.lax.map][] but works with NamedArrays, providing a similar interface to `haliax.scan` and `haliax.fold`. + +```python + +Time = Axis("Time", 100) + +data = hax.random.normal(PRNGKey(0), (Time,)) + +def my_fn(x): + return x + 1 + +result = hax.map(my_fn, Time)(data) +``` + +You should generally prefer to use [haliax.vmap][] instead of `haliax.map`, but it's there if you need it. +(It uses less memory than `haliax.vmap` but is slower.) + + +## Gradient Checkpointing / Rematerialization + +Both `haliax.scan` and `haliax.fold` support gradient checkpointing, which can be useful for deep models. +Typically, you'd use this as part of [haliax.nn.Stacked][] or [haliax.nn.BlockSeq][] but you can also use it directly. + +Gradient checkpointing is a technique for reducing memory usage during backpropagation by recomputing some +intermediate values during the backward pass. This can be useful when you have a deep model with many layers. + +### TL;DR Guidance + +Here is some guidance on when to use gradient checkpointing: + +* Use `remat=False` if you need to reduce computation and have lots of memory. This is the default in [haliax.scan][]. +* Use `remat=True` for most models. It's usually good enough. This is the default in [haliax.nn.Stacked][]. +* Use `remat="nested"` if you need to reduce memory usage. +* Use `save_block_internals` sparingly, but it is your best tool for trading increased memory usage for reduced computation +if you need something between `remat=True` and `remat=False`. +* Use `save_carries="offload"` if you need to reduce memory usage at the cost of recomputation. This is a new feature +in JAX and doesn't seem to reliably work yet. + + +### Simple Checkpointing + +In the simplest case, you can enable a usually-good-enough checkpointing policy by passing `remat=True`: + +```python +final_state = hax.fold(running_stats, Time, remat=True)(init_state, data) +``` + +("remat" is short for "rematerialization", which is another term for gradient checkpointing.) + +This will preserve the intermediate "carries" and other inputs the fold function needs, while rematerializing +(i.e. recomputing) the internal state of each block (i.e. call to the running_stats function) as needed during +backpropagation. + + +### Nested Scan + +Simple checkpointing requires `O(N)` memory where $N$ is the number of blocks. A nested scan lets you reduce +this to `O(sqrt(N))` memory, at the cost of a bit more computation. You can enable this by passing `remat="nested"`: + +```python +final_state = hax.fold(running_stats, Time, remat="nested")(init_state, data) +``` + +This will break the scan into a double loop, where the outer loop has `sqrt(N)` blocks and the inner loop has +`sqrt(N)` blocks (with appropriate rounding). + +Functionally, it does something like: + +``` +outer_size = int(sqrt(N)) # ensuring outer_size divides N +blocks = haliax.rearrange("block -> (outer inner)", blocks, outer=outer_size) + +state = init_state +for o in range(outer_size): + inner_blocks = blocks["outer", o] + + for i in range(inner_size): + state = f(state, inner_blocks["inner", i]) + + # not real jax + state = save_for_backward(state) +``` + +where we save only the carries from the outer loop, and fully rematerialize the inner loop. + +If `C` is the amount of memory needed for the carry, and `N` is the number of blocks, then the memory usage +of the nested scan is `2 * C * sqrt(N)`. In addition, you need enough memory to do backward in one block. + +In practice, nested scan is about 20% slower than simple checkpointing (for Transformers), but uses much less memory. + +#### Advanced: customizing the number of blocks + +You can also customize the number of blocks in the outer loop by using a policy: + +```python +policy = ScanCheckpointPolicy(nested=4) # 4 outer blocks +``` + +Note that by itself this doesn't help you at all except potentially requiring more memory. You can potentially +combine it with other policy options to make things faster though. + + +### Custom Checkpointing Policies + +If you need more control over the checkpointing policy, you can pass a [haliax.nn.ScanCheckpointPolicy][] object to +the `scan` or `fold` call: + +```python +policy = ScanCheckpointPolicy( + save_carries=True, # default + save_inputs=True, # default + save_block_internals=False, # default +) +``` + +### Saving Block-Internal Values + +"`internals`" refers to the internal computation of the block. If you set `save_block_internals=True`, then +all internals of every block will be saved. This can be expensive and mostly negates the benefits of checkpointing. + +Instead you can choose which internals to save by passing a list of strings to `save_block_internals`: + +```python +def my_complex_fn(state, x): + y = x + state + y = hax.sin(y) + x + y = hax.tree_checkpoint_name(y, "y") + y = hax.cos(y) + x + y = hax.tree_checkpoint_name(y, "z") + return y + +policy = ScanCheckpointPolicy(save_carries=True, save_block_internals=["y"]) + +final_state = hax.fold(my_complex_fn, Time, remat=policy)(init_state, data) + +``` + +With this policy, the output of the `sin` function will be saved during the forward pass. + +This will save an extra `sin` computation in the backward pass, adding $`O(N * Pos * Hidden)`$ memory usage, +which is double that required by the default policy, but it reduces the amount of recomputation needed. +(It's probably not worth it in this case.) + +### Offloading Checkpointed Values + +Both `save_carries` and `save_inputs` can either be a boolean or the string "offload". If "offload", then the +checkpointed values will be offloaded to the host during the forward pass, and reloaded during the backward pass. + + +### Summary of String and Boolean Aliases + +* `remat=True` is the same as `remat=ScanCheckpointPolicy(save_carries=True, save_inputs=True)` +* `remat="full"` is the same as `remat=True` +* `remat=False` is the same as `remat=ScanCheckpointPolicy(disable=True)` +* `remat="nested"` is the same as `remat=ScanCheckpointPolicy(nested=True)` +* `remat="offload"` is the same as `remat=ScanCheckpointPolicy(save_carries="offload", save_inputs="offload")` +* `remat="save_all"` is the same as `remat=ScanCheckpointPolicy(save_carries=True, save_inputs=True, save_block_internals=True)`, +which should be the same as not using remat at all... + + +### Memory and Computation Tradeoffs + +Let `N` be the number of blocks, `C` be the memory needed for the carry, and `I` be the internal memory needed +for each block. Let F be the amount of computation needed for each block. Constants are added for a bit more precision +but are not exact. This is assuming that backward requires ~twice the flops as forward, which is roughly right for +Transformers. + +| Policy | Memory Usage | Computation | +|------------------|--------------------------|----------------| +| `remat=False` | `O(N * C + N * I)` | `O(3 * N * F)` | +| `remat=True` | `O(N * C + I)` | `O(4 * N * F)` | +| `remat="nested"` | `O(2 * sqrt(N) * C + I)` | `O(5 * N * F)` | + + +(Which shows why nested scan is about 20% slower than simple checkpointing. The math says 25% but it's more like 20% in +practice.) Any nested remat will require `5 * N * F` computation, which is about 25% more than simple remat. + + +## Module Stacks + +A core pattern for larger models in JAX is the "scan-over-layers" pattern, where you have a sequence of layers +that get stacked together, and you use [jax.lax.scan][] or [haliax.fold][] or [haliax.scan][] to apply them to a +sequence of inputs. In Haliax, layers are represented as [equinox.nn.Module][]s, and the [haliax.nn.Stacked][] module +provides a way to create a sequence of layers that can be applied to a sequence of inputs that implements the +scan-over-layers pattern. + +### Stacked + +[haliax.nn.Stacked][] lets you apply a layer sequentially to an input, scanning over a "Layers" axis. For instance, +a Transformer might use a Stacked for its Transformer blocks: + + +```python +class TransformerBlock(eqx.Module): + + def __init__(self, config: TransformerConfig, layer_index, *, key): + attn_key, mlp_key = jax.random.split(key) + self.attention = Attention.init(config, key=attn_key) + self.mlp = MLP.init(config, key=mlp_key) + self.ln1 = LayerNorm.init(config.Hidden) + self.ln2 = LayerNorm.init(config.Hidden) + self.layer_index = layer_index + + def __call__(self, x): + y = self.attention(self.ln1(x)) + x = x + y + y = self.mlp(self.ln2(x)) + return x + y + +class Transformer(eqx.Module): + def __init__(self, config: TransformerConfig): + self.blocks = Stacked.init(Layers, TransformerBlock)( + config, # static configuration + scale=hax.arange(Layers), # dynamic configuration. Each layer gets a scalar scale value [0, 1, 2, ...] + key=jax.random.split(key, Layers), # dynamic configuration. Each layer gets a different key + ) + + def __call__(self, x: NamedArray) -> NamedArray: + # morally the equivalent of: + # for block in self.blocks: + # x = block(x) + # Except that it works better with JAX compile times. + + return self.blocks.fold(x) +``` + +You can think of [haliax.nn.Stacked][] as an analog to PyTorch's +[torch.nn.Sequential](https://pytorch.org/docs/stable/generated/torch.nn.Sequential.html), except that +every layer in the sequence must have exactly the same shape and configuration. + +Internally, a Stacked is a single copy of the module, except that every NamedArray inside that module +has a Block axis prepended (as though they were stacked with [haliax.stack][]). Similarly, every JAX array +inside the module has its first axis prepended with an axis of the same size as the Block axis, as though +they were stacked with [jax.numpy.stack][]. + +When you call the Stacked, it scans over the Block axis, applying the module to each element of the Block. + +#### Creating a Stacked + +To create a Stacked, we provide `Stacked.init`, which takes a "Layers" [haliax.Axis][] and another Module as +well as args and kwargs for that module. The Layer is the axis that the Stacked will scan over, and the `args` +and `kwargs` are implicitly vmapped over the Layers. + +For instance, to create a stack of GPT2 blocks, you might do: + +```python +import jax.random + +blocks = Stacked.init(Layers, Gpt2Block)( + config, # static configuration + scale=hax.arange(Layers), # dynamic configuration. Each layer gets a scalar scale value [0, 1, 2, ...] + key=jax.random.split(key, Layers.size), # dynamic configuration. Each layer gets a different key +) +``` + +Any NamedArray passed to the Stacked init will have its Layers axis (if present) vmapped over. Any +JAX array will have its first axis vmapped over. + + +#### Fold Blocks vs Scan Blocks + +The Stacked module provides two ways to apply the layers: `fold` and `scan`. A fold is the moral equivalent of this for loop: + +```python +for block in self.blocks: + x = block(x) +``` + +while a scan is the moral equivalent of this for loop: + +```python +out = [] +for block in self.blocks: + x, y = block(x) + out.append(y) + +return x, stack(out) +``` + +Blocks can be coded to either support fold or scan, but not both. +A "fold Block" should have the signature `def __call__(self, x: Carry) -> Carry`, +while a "scan Block" should have the signature `def __call__(self, x: Carry) -> Tuple[Carry, Output]`. + +(See also [jax.lax.scan][], [haliax.fold][], and [haliax.scan][].) + +#### Requirements for Stacked Blocks + +As we said above, the Stacked module requires that all the layers have the same shape and configuration. + +A further constraint is that the elements of the stack must have the same Python control flow. This is the usual +constraint imposed on jit-compiled functions in JAX. All control flow must use `jax.lax` primitives like +[jax.lax.cond][], [jax.lax.while_loop][], and [jax.lax.scan][]. You can't use Python control flow like `if` or `for` +except for static control flow that is the same for all elements of the stack. + +### BlockSeq and BlockFoldable + +We also provide a way to create a sequence of layers that can be applied to a sequence of inputs that implements the +same interface as [haliax.nn.Stacked][], but with a different implementation. This is the [haliax.nn.BlockSeq][] module. +BlockSeq implements those for loops directly, rather than using [haliax.fold][] or [haliax.scan][]. + +[haliax.nn.scan.BlockFoldable][] is an interface that both [haliax.nn.Stacked][] and [haliax.nn.BlockSeq][] implement. + +## API + +::: haliax.fold +::: haliax.scan +::: haliax.map +::: haliax.ScanCheckpointPolicy + +### Modules +::: haliax.nn.Stacked +::: haliax.nn.BlockSeq +::: haliax.nn.scan.BlockFoldable diff --git a/docs/stacked.md b/docs/stacked.md deleted file mode 100644 index 389aeb0..0000000 --- a/docs/stacked.md +++ /dev/null @@ -1,203 +0,0 @@ -# Module Stacks - -A core pattern for larger models in JAX is the "scan-over-layers" pattern, where you have a sequence of layers -that get stacked together, and you use [jax.lax.scan][] or [haliax.fold][] or [haliax.scan][] to apply them to a -sequence of inputs. In Haliax, layers are represented as [equinox.nn.Module][]s, and the [haliax.nn.Stacked][] module -provides a way to create a sequence of layers that can be applied to a sequence of inputs that implements the -scan-over-layers pattern. - -## Stacked - -[haliax.nn.Stacked][] lets you apply a layer sequentially to an input, scanning over a "Layers" axis. For instance, -a Transformer might use a Stacked for its Transformer blocks: - - -```python -class TransformerBlock(eqx.Module): - - def __init__(self, config: TransformerConfig, layer_index, *, key): - attn_key, mlp_key = jax.random.split(key) - self.attention = Attention.init(config, key=attn_key) - self.mlp = MLP.init(config, key=mlp_key) - self.ln1 = LayerNorm.init(config.Hidden) - self.ln2 = LayerNorm.init(config.Hidden) - self.layer_index = layer_index - - def __call__(self, x): - y = self.attention(self.ln1(x)) - x = x + y - y = self.mlp(self.ln2(x)) - return x + y - -class Transformer(eqx.Module): - def __init__(self, config: TransformerConfig): - self.blocks = Stacked.init(Layers, TransformerBlock)( - config, # static configuration - scale=hax.arange(Layers), # dynamic configuration. Each layer gets a scalar scale value [0, 1, 2, ...] - key=jax.random.split(key, Layers), # dynamic configuration. Each layer gets a different key - ) - - def __call__(self, x: NamedArray) -> NamedArray: - # morally the equivalent of: - # for block in self.blocks: - # x = block(x) - # Except that it works better with JAX compile times. - - return self.blocks.fold(x) -``` - -You can think of [haliax.nn.Stacked][] as an analog to PyTorch's -[torch.nn.Sequential](https://pytorch.org/docs/stable/generated/torch.nn.Sequential.html), except that -every layer in the sequence must have exactly the same shape and configuration. - -Internally, a Stacked is a single copy of the module, except that every NamedArray inside that module -has a Block axis prepended (as though they were stacked with [haliax.stack][]). Similarly, every JAX array -inside the module has its first axis prepended with an axis of the same size as the Block axis, as though -they were stacked with [jax.numpy.stack][]. - -When you call the Stacked, it scans over the Block axis, applying the module to each element of the Block. - -### Creating a Stacked - -To create a Stacked, we provide `Stacked.init`, which takes a "Layers" [haliax.Axis][] and another Module as -well as args and kwargs for that module. The Layer is the axis that the Stacked will scan over, and the `args` -and `kwargs` are implicitly vmapped over the Layers. - -For instance, to create a stack of GPT2 blocks, you might do: - -```python -import jax.random - -blocks = Stacked.init(Layers, Gpt2Block)( - config, # static configuration - scale=hax.arange(Layers), # dynamic configuration. Each layer gets a scalar scale value [0, 1, 2, ...] - key=jax.random.split(key, Layers.size), # dynamic configuration. Each layer gets a different key -) -``` - -Any NamedArray passed to the Stacked init will have its Layers axis (if present) vmapped over. Any -JAX array will have its first axis vmapped over. - - -### Fold Blocks vs Scan Blocks - -The Stacked module provides two ways to apply the layers: `fold` and `scan`. A fold is the moral equivalent of this for loop: - -```python -for block in self.blocks: - x = block(x) -``` - -while a scan is the moral equivalent of this for loop: - -```python -out = [] -for block in self.blocks: - x, y = block(x) - out.append(y) - -return x, stack(out) -``` - -Blocks can be coded to either support fold or scan, but not both. -A "fold Block" should have the signature `def __call__(self, x: Carry) -> Carry`, -while a "scan Block" should have the signature `def __call__(self, x: Carry) -> Tuple[Carry, Output]`. - -(See also [jax.lax.scan][], [haliax.fold][], and [haliax.scan][].) - -### Requirements for Stacked Blocks - -As we said above, the Stacked module requires that all the layers have the same shape and configuration. - -A further constraint is that the elements of the stack must have the same Python control flow. This is the usual -constraint imposed on jit-compiled functions in JAX. All control flow must use `jax.lax` primitives like -[jax.lax.cond][], [jax.lax.while_loop][], and [jax.lax.scan][]. You can't use Python control flow like `if` or `for` -except for static control flow that is the same for all elements of the stack. - -## BlockSeq and BlockFoldable - -We also provide a way to create a sequence of layers that can be applied to a sequence of inputs that implements the -same interface as [haliax.nn.Stacked][], but with a different implementation. This is the [haliax.nn.BlockSeq][] module. -BlockSeq implements those for loops directly, rather than using [haliax.fold][] or [haliax.scan][]. - -[haliax.nn.scan.BlockFoldable][] is an interface that both [haliax.nn.Stacked][] and [haliax.nn.BlockSeq][] implement. - -## Gradient Checkpointing - -The [haliax.nn.Stacked][] module also provides a way to do gradient checkpointing, which can be useful for deep models. - -Gradient checkpointing, aka rematerialization, is a technique for trading off memory usage for compute time. -Instead of storing all the intermediate activations of a model, you store only a subset and recompute the rest -as needed. (XLA automatically recomputes the rest for you as needed.) - -[JAX's checkpointing mechanism]((https://docs.jax.dev/en/latest/gradient-checkpointing.html) is highly flexible, -and we provide a relatively simple interface to it for use with `Stacked`. - -### Simple Checkpointing -In the simplest case, you can enable a usually-good-enough checkpointing policy by passing `gradient_checkpointing=True` -to the `Stacked.init` call: - -```python -blocks = Stacked.init(Layers, TransformerBlock, gradient_checkpointing=True)( - config, - scale=hax.arange(Layers), - key=jax.random.split(key, Layers.size), -) -``` - -This will preserve the intermediate "carries" and the "outputs" of the scans, while rematerializing (i.e. recomputing) -the rest of the computation as needed during backpropagation. - -### Custom Checkpointing Policies - -If you need more control over the checkpointing policy, you can pass a [haliax.nn.StackedCheckpointPolicy][] object to -the Stacked init: - -```python -policy = StackedCheckpointPolicy( - save_carries=True, # default - save_outputs=True, # default - save_intermediates=False, # default -) -``` - -### Saving Block-Internal Values - -"`intermediates`" refers to the internal computation of the block. If you set `save_intermediates=True`, then -all internals of every block will be saved. This can be expensive. - -You can also pass a list of strings to `save_intermediates` to specify which intermediates to save. - -You could, for instance, save the output of the attention layer using [haliax.tree_checkpoint_name][]: - -```python -class TransformerBlock(eqx.Module): - def __call__(self, x): - y = self.attention(self.ln1(x)) - y = haliax.tree_checkpoint_name(y, "attn_out") - x = x + y - y = self.mlp(self.ln2(x)) - return x + y - -policy = StackedCheckpointPolicy(save_carries=True, save_block_internals=["attn_out"]) -``` - -With this policy, the output of the attention layer will be saved during the forward pass. - -This will save an extra attention computation in the backward pass, adding $`O(N * Pos * Hidden)`$ memory usage, -which is double that required by the default policy. - - -### Offloading Checkpointed Values - -Both `save_carries` and `save_outputs` can either be a boolean or the string "offload". If "offload", then the -checkpointed values will be offloaded to the host during the forward pass, and reloaded during the backward pass. - - -## API - -::: haliax.nn.Stacked -::: haliax.nn.BlockSeq -::: haliax.nn.scan.BlockFoldable - -::: haliax.nn.StackedCheckpointPolicy diff --git a/docs/vmap.md b/docs/vmap.md new file mode 100644 index 0000000..e2c7394 --- /dev/null +++ b/docs/vmap.md @@ -0,0 +1,5 @@ +## Vectorization + +(This is a work in progress. Please contact dlwh for more information.) + +::: haliax.vmap diff --git a/mkdocs.yml b/mkdocs.yml index b925d13..e0f61fe 100644 --- a/mkdocs.yml +++ b/mkdocs.yml @@ -90,9 +90,11 @@ nav: - Indexing and Slicing: 'indexing.md' - Rearrange: 'rearrange.md' - Matrix Multiplication: 'matmul.md' + - Higher Order Functions: + - Scan and Fold: 'scan.md' + - Vectorization: 'vmap.md' - Neural Networks: 'nn.md' - Partitioning: 'partitioning.md' - - Higher Order Functions: 'hof.md' - FP8: 'fp8.md' - Serialization: 'state-dict.md' - API Reference: 'api.md' diff --git a/src/haliax/__init__.py b/src/haliax/__init__.py index c6f4fe6..e99e977 100644 --- a/src/haliax/__init__.py +++ b/src/haliax/__init__.py @@ -21,6 +21,7 @@ import haliax.util as util from ._src.dot import dot from ._src.einsum import einsum from ._src.rearrange import rearrange +from ._src.scan import ScanCheckpointPolicy from .axis import ( Axis, AxisSelection, @@ -61,7 +62,7 @@ from .core import ( updated_slice, ) from .hof import fold, map, scan, vmap -from .jax_utils import filter_checkpoint +from .jax_utils import tree_checkpoint_name from .ops import clip, isclose, pad_left, trace, tril, triu, where from .partitioning import auto_sharded, axis_mapping, fsdp, named_jit, shard, shard_with_axis_mapping from .specialized_fns import top_k @@ -887,7 +888,6 @@ def true_divide(x1: NamedOrNumeric, x2: NamedOrNumeric, /) -> NamedOrNumeric: # deprecated name concat_axis_specs = concat_axes - __all__ = [ "debug", "random", @@ -1071,4 +1071,6 @@ __all__ = [ "ravel", "flatten", "is_named_array", + "tree_checkpoint_name", + "ScanCheckpointPolicy", ] diff --git a/src/haliax/_src/scan.py b/src/haliax/_src/scan.py new file mode 100644 index 0000000..f1d4dfa --- /dev/null +++ b/src/haliax/_src/scan.py @@ -0,0 +1,613 @@ +import dataclasses +import functools as ft +from typing import Any, Callable, Literal, ParamSpec, Protocol, Sequence, Tuple, TypeVar, Union, overload + +import equinox as eqx +import jax +from jaxtyping import PyTree + +import haliax +import haliax.tree_util as htu +from haliax._src.util import index_where +from haliax.axis import Axis, AxisSelector, selects_axis +from haliax.core import NamedArray +from haliax.jax_utils import is_jax_array_like, multilevel_scan, tree_checkpoint_name +from haliax.util import is_jax_or_hax_array_like, is_named_array + + +BoolAxisSpec = Union[bool, Callable[[Any], bool]] +Carry = TypeVar("Carry") +X = TypeVar("X", contravariant=True) +Y = TypeVar("Y", covariant=True) +Args = ParamSpec("Args") + + +def is_named_or_shaped_array_like(x): + return (is_jax_array_like(x) and x.ndim >= 1) or is_named_array(x) + + +class ScanFn(Protocol[Carry, Args, Y]): + """ """ + + def __call__(self, carry: Carry, *args: Args.args, **kwargs: Args.kwargs) -> tuple[Carry, Y]: + ... + + +@dataclasses.dataclass +class ScanCheckpointPolicy: + """ + A class that represents a gradient checkpoint policy for blocks in a Stacked module. This is used to control + gradient checkpointing in [haliax.scan][], [haliax.fold][], [haliax.nn.Stacked][] and [haliax.nn.BlockSeq][]. + + Gradient checkpointing is a technique for reducing memory usage in training large models. It works by saving only a + subset of the forward pass and recomputing the rest in the backward pass. (By doing parts of the forward pass again) + JAX suggests that this usually isn't necessary when not using scan-over-layers (i.e. Stacked), so this is mostly + useful for Stacked modules. + + A scan block takes a "carry" and some extra arguments, and returns a "carry" and an "output". The "carry" is passed + to the next block, and the "output" is concatenated into a final result (sort of like an RNN). + + Schematically it might look like this: + + ``` + I I I I + | | | | + C -> B -C-> B -C-> B -C-> B --> C + | | | | + O O O O + ``` + + where "C" is the carry and "O" is the output. A block will typically do some computation (e.g. a Transformer block) + as well, which might require saving or recomputing in the backward pass. + + Without checkpointing, we will save all block inputs and outputs, and use them to compute the gradient. This requires + memory, of course. With checkpointing, we can save only some of the computation. Typically, to compute the gradient + of the scan, we need the inputs to each block, the intermediates within each block, as well as the carries (which + are inputs to the next block). We can save all of these, or we can save only some of them. + + With this class, you can specify if you want to save the carries, or the internals/inputs. You can also offload + the carries to the host, which can reduce memory usage on the device. + + #### Nested Remat + + Alternatively, we can do something a bit more clever. We can break the computation into "blocks" of size "B", and + save the carries and outputs of each block. Then, during the backward pass, we can recompute the outputs of each + block using the carries and inputs, and then compute the gradient as usual. This requires O(B) memory and O(N) + time. When B = sqrt(N), this is O(sqrt(N)) memory and O(N) time. This is the "nested scan" policy. + In practice, this is about 20% slower than the O(N) memory policy, but it can be worth it for large models. + + #### Offloading + + Another choice is to "offload" carries and outputs to the host, which can reduce memory usage on the device. + We support offloading carries and outputs to the host, but not internals. + + See Also: + * [JAX docs on gradient checkpointing](https://docs.jax.dev/en/latest/gradient-checkpointing.html) + """ + + save_carries: bool | Literal["offload"] = True + """ + Whether to save all carries in the forward pass. If True, (input) carries are saved in the forward pass and used in the + backward pass. If "offload", carries are saved in the forward pass and offloaded to the host + + If False, carries are recomputed in the backward pass. + """ + + save_inputs: bool | Literal["offload"] = False + """ + Whether to save all non-carry inputs in the forward pass. If True, inputs are saved in the forward pass and used in + the backward pass. If "offload", inputs are saved in the forward pass and offloaded to the host. + """ + + save_block_internals: bool | list[str] = False + """ + Whether to save internal state of blocks. If a list, only the listed names are saved, as + with [jax.checkpoint_policies.save_only_these_names][]. + + See Also: https://docs.jax.dev/en/latest/gradient-checkpointing.html#custom-policies-for-offload + """ + prevent_cse: bool = False + """ + Whether to prevent common subexpression elimination in the checkpointed function. + """ + + disable: bool = False + """ + Whether to disable gradient checkpointing entirely. This is useful for debugging. + """ + + simple: bool = False + """ + Whether to use the simple gradient checkpointing policy. This is useful for debugging. + """ + + nested: bool | int = False + """ + Allows for nested remat with a double scan. We reshape the stack into [nested_remat, -1] and then scan over both + in sequence. If True, we find the closest int to sqrt(len(stack)) such that len(stack) % int == 0. + If False, we don't do anything. + """ + + @staticmethod + def from_bool_or_str(remat_policy: bool | str): + """ + Convert a boolean or string into a BlockCheckpointPolicy. This is useful for converting user input + into a BlockCheckpointPolicy. + + Choices: + * True: save outputs, don't save block internals. This is the classic Haliax behavior. + * False: save everything. + * "offload": offload outputs to the host, don't save block internals. + * "recompute" or "full": don't save outputs or block internals. + * "save_all": save outputs and block internals. Equivalent to False + * "nested": use nested remat. Equivalent to True + """ + if remat_policy == "offload": + return ScanCheckpointPolicy(save_carries="offload", save_inputs="offload", save_block_internals=False) + elif remat_policy == "recompute" or remat_policy == "full": + return ScanCheckpointPolicy(save_carries=False, save_inputs=False, save_block_internals=False) + elif remat_policy == "save_all": + return ScanCheckpointPolicy(save_carries=True, save_inputs=True, save_block_internals=True) + elif remat_policy == "nested": + return ScanCheckpointPolicy(nested=True) + elif remat_policy is True: + return ScanCheckpointPolicy(simple=True) + elif remat_policy is False: + return ScanCheckpointPolicy(save_carries=True, save_inputs=True, save_block_internals=True, disable=True) + else: + raise ValueError(f"Invalid checkpoint policy {remat_policy}") + + @staticmethod + def _mk(remat_policy: Union[bool, str, "ScanCheckpointPolicy"]) -> "ScanCheckpointPolicy": + if isinstance(remat_policy, ScanCheckpointPolicy): + return remat_policy + else: + return ScanCheckpointPolicy.from_bool_or_str(remat_policy) + + def checkpoint(self, carry_name: str, input_name: str, callable): + if self.disable: + return callable + elif self.simple: + print("simple") + return eqx.filter_checkpoint(callable, prevent_cse=self.prevent_cse) + else: + policy = self._to_jax_policy(carry_name, input_name) + return eqx.filter_checkpoint(callable, policy=policy, prevent_cse=self.prevent_cse) + + def _to_jax_policy(self, carry_name: str, input_name: str): + assert isinstance(carry_name, str) + assert isinstance(input_name, str) + our_names_to_save = [] + our_names_to_offload = [] + our_names_to_remat = [] + + # return jax.checkpoint_policies.save_only_these_names(carry_name, output_name) + + if self.save_inputs is True: + our_names_to_save.append(input_name) + elif self.save_inputs == "offload": + our_names_to_offload.append(input_name) + else: + assert self.save_inputs is False, f"Invalid save_inputs {self.save_inputs}" + our_names_to_remat.append(input_name) + + if self.save_carries is True: + our_names_to_save.append(carry_name) + elif self.save_carries == "offload": + our_names_to_offload.append(carry_name) + else: + assert self.save_carries is False, f"Invalid save_carries {self.save_carries}" + our_names_to_remat.append(carry_name) + + if isinstance(self.save_block_internals, Sequence): + our_names_to_save.extend(self.save_block_internals) + + if not our_names_to_save and not our_names_to_offload and not self.save_block_internals: + return None + + if len(our_names_to_offload) > 0: + if self.save_block_internals is True: + raise ValueError("Can't save all block internals and offload too. Use a list of names instead.") + + return jax.checkpoint_policies.save_and_offload_only_these_names( + names_which_can_be_saved=our_names_to_save, + names_which_can_be_offloaded=our_names_to_offload, + offload_src="device", + offload_dst="pinned_host", + ) + else: + if len(our_names_to_remat) > 0: + if self.save_block_internals is True: + p1 = jax.checkpoint_policies.save_anything_except_these_names(*our_names_to_remat) + if len(our_names_to_save) > 0: + p2 = jax.checkpoint_policies.save_only_these_names(*our_names_to_save) + return jax.checkpoint_policies.save_from_both_policies(p1, p2) + else: + return p1 + else: + return jax.checkpoint_policies.save_only_these_names(*our_names_to_save) + elif len(our_names_to_save) > 0: + p1 = jax.checkpoint_policies.save_only_these_names(*our_names_to_save) + if self.save_block_internals is True: + p2 = jax.checkpoint_policies.save_anything_except_these_names(*our_names_to_remat) + return jax.checkpoint_policies.save_from_both_policies(p1, p2) + else: + return p1 + elif self.save_block_internals is True: + return jax.checkpoint_policies.save_anything_except_these_names(*our_names_to_remat) + else: + return None + + +ScanCheckpointSpec = Union[ScanCheckpointPolicy, bool, Literal["offload", "recompute", "full", "save_all", "nested"]] + + +@overload +def scan( + f: Callable[[Carry, X], tuple[Carry, Y]], + axis: AxisSelector, + *, + remat: ScanCheckpointSpec = False, + reverse: bool = False, + unroll: int = 1, + is_scanned: BoolAxisSpec = is_named_or_shaped_array_like, +) -> Callable[[Carry, PyTree[X]], tuple[Carry, PyTree[Y]]]: + ... + + +@overload +def scan( + f: Callable, + axis: AxisSelector, + *, + remat: ScanCheckpointSpec = False, + reverse: bool = False, + unroll: int = 1, + is_scanned: BoolAxisSpec = is_named_or_shaped_array_like, +) -> Callable: + ... + + +def scan( + f: Callable, # : ScanFn[Carry, Args, Y], This confuses mypy too much + axis: AxisSelector, + *, + remat: ScanCheckpointSpec = False, + reverse=False, + unroll=1, + is_scanned: BoolAxisSpec = is_named_or_shaped_array_like, +): + """ + Scan over a named axis. Non-scalar unnamed arrays will have their first axis scanned over. + + Unlike [jax.lax.scan][], this function is curried: it takes the function, axis, and configuration arguments first, and + then the initial carry and then any arguments to scan over as a separate curried function call. + + That is, `scan(f, axis)(init, xs)` is equivalent to `jax.lax.scan(f, init, xs)` + + Args: + f (Callable): function to scan over + axis (AxisSelector): axis to scan over + reverse (bool): if True, scan in reverse + unroll (int): unroll the loop by this amount + remat: a ScanCheckpointPolicy or a boolean. If True, rematerialize block internals during + gradient computation. If False, rematerialize nothing. If "offload", offload all carries and inputs. + See [haliax.ScanCheckpointPolicy][] for more information. + is_scanned (BoolAxisSpec): a function that takes a leaf of the tree and returns True if it should be scanned + over, False otherwise. Behaves similarly to the `default` argument in filter_jit + """ + checkpoint = ScanCheckpointPolicy._mk(remat) + + if isinstance(is_scanned, bool): + q = is_scanned # this is to make mypy happy + is_scanned = lambda _: q + + def is_scanned_with_axis(leaf): + if is_named_array(leaf): + return selects_axis(leaf.axes, axis) and is_scanned(leaf) + else: + return is_scanned(leaf) + + def scanned_f(init, *args, **kwargs): + # This implementation is a bit tricky. + + # first we want to partition the arguments into scanned and unscanned + # unscanned arguments are just passed through, essentially captured as part of a lambda + # scanned arguments are passed through the scan, which means we need to hoist the axis to the front + xs = (args, kwargs) + scanned_xs, unscanned_xs = eqx.partition(xs, is_scanned_with_axis, is_leaf=is_named_array) + + carry_name = f"scan({haliax.axis_name(axis)})__carry" + input_name = f"scan({haliax.axis_name(axis)})__input" + + # Next we have to hoist the axis we're scanning over to the front of the array, because that's what scan + # expects. Then we have to scan over the 0th dim of the arrays (as flattened non-pytrees) + # We have to be careful that we don't try to create NamedArrays that have the shape of the scanned result + # but don't yet have the scanned axis as ones of `axes`, so we use _ScannedArrayResult that doesn't check + # invariants until we're ready to create the result. + axis_first_xs = htu.tree_map(_ensure_first(axis), scanned_xs) + + # now get a template of an element of "X" + x_elem = htu.tree_map(_select_0th(axis), axis_first_xs) + # NB: we don't want to use htu.tree_structure here because we want to eliminate the leading axis + x_elem_structure = jax.tree_util.tree_structure(x_elem) + + # now we can fold over the axis + @ft.wraps(f) + def wrapped_fn(carry, scanned_x_leaves): + scanned_x = jax.tree_util.tree_unflatten(x_elem_structure, scanned_x_leaves) + scanned_x = tree_checkpoint_name(scanned_x, input_name) + carry = tree_checkpoint_name(carry, carry_name) + + # this part is the most delicate: combining the scanned x with the unscanned x + scanned_x = eqx.combine(scanned_x, unscanned_xs, is_leaf=is_named_array) + args, kwargs = scanned_x + carry, y = f(carry, *args, **kwargs) + y = htu.tree_map(_pacify_named_arrays, y) + + return carry, y + + true_axis = _infer_axis_size_from_tree(axis_first_xs, axis) + axis_size = _infer_axis_size_from_tree(axis_first_xs, axis).size + + nested_scan = checkpoint.nested + outer_block_size = nested_scan_outer_block(nested_scan, axis_size) + + checkpointed_fn = checkpoint.checkpoint(carry_name, input_name, wrapped_fn) + + # as above, we don't want to use htu.tree_leaves here because we want to eliminate the leading axis + leaves = jax.tree_util.tree_leaves(axis_first_xs) + + with jax.named_scope(f"scan({haliax.axis_name(axis)})"): + if outer_block_size is not None: + carry, ys = multilevel_scan( + checkpointed_fn, init, leaves, outer_block_size, reverse=reverse, unroll=unroll, length=axis_size + ) + else: + carry, ys = jax.lax.scan( + checkpointed_fn, init, leaves, reverse=reverse, unroll=unroll, length=axis_size + ) + + ys = jax.tree_util.tree_map(_prepend_named_batch_axis(true_axis), ys, is_leaf=_is_passive_array) + + return carry, ys + + def nested_scan_outer_block(nested_remat, axis_size): + outer_block_size: int | None + if nested_remat is True: + outer_block_size = find_closest_divisible_int_to_sqrt(axis_size) + elif nested_remat is False: + outer_block_size = None + else: + outer_block_size = nested_remat + return outer_block_size + + return scanned_f + + +@overload +def fold( + fn: Callable[[Carry, X], Carry], + axis: AxisSelector, + *, + remat: ScanCheckpointSpec = False, + reverse: bool = False, + unroll: int = 1, + is_scanned: BoolAxisSpec = is_named_or_shaped_array_like, +) -> Callable[[Carry, PyTree[X]], Carry]: + ... + + +@overload +def fold( + fn: Callable, + axis: AxisSelector, + *, + remat: ScanCheckpointSpec = False, + reverse: bool = False, + unroll: int = 1, + is_scanned: BoolAxisSpec = is_named_or_shaped_array_like, +) -> Callable: + ... + + +def fold( + fn: Callable, + axis: AxisSelector, + *, + remat: ScanCheckpointSpec = False, + reverse: bool = False, + unroll: int = 1, + is_scanned: BoolAxisSpec = is_named_or_shaped_array_like, +) -> Callable: + """ + Slightly simpler implementation of scan that folds over the named axis of the array, not returning intermediates. + + As with scan, this function is curried: it takes the function, axis, and configuration arguments first, and + then the initial carry and then any arguments to scan over as a separate curried function call. + + Unnamed arrays will have their first axis scanned over, unless they are scalars, in which case they will be passed + through unchanged. + + Args: + fn: function to reduce over + axis: axis to reduce over + reverse: if True, reduce in reverse + unroll: unroll the loop by this amount + nested_scan: Use nested scans to reduce memory usage. If an integer, use that many nested scans. + If true, use the closest int to sqrt(axis.size) that divides axis.size, which gives + O(sqrt(N)) memory and O(N) time. + is_scanned: a function that takes a leaf of the tree and returns True if it should be scanned over, + False otherwise. Behaves similarly to the `default` argument in filter_jit + + Returns: + A function that takes the initial carry and then the arguments to reduce over, and returns the final carry + """ + + def scan_compatible_fn(carry, *args, **kwargs): + return fn(carry, *args, **kwargs), None + + scan_preconfig = scan(scan_compatible_fn, axis, reverse=reverse, unroll=unroll, is_scanned=is_scanned, remat=remat) + + def scanned_f(init, *args, **kwargs): + return scan_preconfig(init, *args, **kwargs)[0] + + return scanned_f + + +def map( + fn: Callable[[X], Y], + axis: Axis, + *, + remat: ScanCheckpointSpec = False, + reverse: bool = False, + unroll: int = 1, + is_mapped: BoolAxisSpec = is_jax_or_hax_array_like, +) -> Callable[[PyTree[X]], PyTree[Y]]: + """ + NamedArray aware version of jax.lax.map. Normal arrays are mapped according to the specs as in equinox.filter_map, + except that the output axis is always 0 b/c it's annoying to make anything else work. + + You'll typically want to use map (instead of a vmap or just vectorized code) when you want to encourage XLA to + loop over the axis to control memory. + + Args: + fn (Callable): function to map over + axis (Axis): axis to map over + reverse (bool): if True, map in reverse + unroll (int): unroll the loop by this amount + + """ + + def scan_compatible_fn(_, x): + del _ + return None, fn(x) + + scan_preconfig = scan(scan_compatible_fn, axis, reverse=reverse, unroll=unroll, is_scanned=is_mapped, remat=remat) + + def scanned_f(*args, **kwargs): + return scan_preconfig(None, *args, **kwargs)[1] + + return scanned_f + + +ResolvedUnnamedAxisSpec = Union[int, None] +UnnamedAxisSpec = Union[ResolvedUnnamedAxisSpec, Callable[[Any], ResolvedUnnamedAxisSpec]] + + +def _zero_if_array_else_none(x: Any) -> ResolvedUnnamedAxisSpec: + return 0 if is_jax_array_like(x) else None + + +def _infer_axis_size_from_tree(result, axis): + if isinstance(axis, str): + result_leaves = jax.tree_util.tree_leaves(result, is_leaf=_is_passive_array) + if len(result_leaves) == 0: + # this really shouldn't happen + return None + if isinstance(result_leaves[0], _PassiveNamedArray): + true_axis_size = result_leaves[0].array.shape[0] # batch axis is defined to be 0 above + true_axis = Axis(axis, true_axis_size) + else: + true_axis_size = result_leaves[0].shape[0] # batch axis is defined to be 0 above + true_axis = Axis(axis, true_axis_size) + else: + true_axis = axis + return true_axis + + +@jax.tree_util.register_pytree_node_class +@dataclasses.dataclass(frozen=True) +class _PassiveNamedArray: + """For some higher-order jax manipulations, jax will insert/remove an axis at the beginning of the array (or + sometimes elsewhere). Jax doesn't know about our NamedArray wrapper, so we need a variant of NamedArray + that doesn't care about the axis names. This is that variant.This class is a 'chill' version of NamedArray + that doesn't check invariants until we're ready to create the result + + For example, with scan in NamedArray, we can't just have the scan tree prepend the scanned axis to the result, + because we don't have a way to feed it the name of the scanned axis. + """ + + array: jax.numpy.ndarray + main_axes: Tuple[Axis, ...] + + def as_scanned_result(self, scan_axis: Axis): + return NamedArray(self.array, (scan_axis,) + self.main_axes) + + def strip_axis(self, axis: AxisSelector): + if isinstance(axis, Axis): + index = self.main_axes.index(axis) + else: + index = index_where(lambda a: a.name == axis, self.main_axes) + return NamedArray(self.array, self.main_axes[:index] + self.main_axes[index + 1 :]) + + def to_named_array(self): + return NamedArray(self.array, self.main_axes) + + def tree_flatten(self) -> Any: + return ((self.array,), self.main_axes) + + @classmethod + def tree_unflatten(cls, aux, tree: Any) -> Any: + assert len(tree) == 1 + return cls(tree[0], main_axes=aux) + + +def _pacify_named_arrays(leaf): + if isinstance(leaf, NamedArray): + return _PassiveNamedArray(leaf.array, leaf.axes) + elif isinstance(leaf, _PassiveNamedArray): + assert False, "PassiveNamedArray should not be present in the tree" + else: + return leaf + + +def _select_0th(axis): + def select_0th(leaf): + if isinstance(leaf, NamedArray): + return leaf.take(axis, 0) + elif isinstance(leaf, _PassiveNamedArray): + assert False, "PassiveNamedArray should not be present in the tree" + else: + # other leaves don't matter + return leaf + + return select_0th + + +def _ensure_first(axis): + def ensure_first(leaf): + if isinstance(leaf, NamedArray): + return leaf.rearrange((axis, ...)) + elif isinstance(leaf, _PassiveNamedArray): + assert False, "PassiveNamedArray should not be present in the tree" + else: + return leaf + + return ensure_first + + +def find_closest_divisible_int_to_sqrt(n: int) -> int: + """ + Find the closest integer to the square root of n (less than or equal to sqrt(n)) that divides n. + """ + assert n > 0, f"Expected n > 0, got {n}" + for i in range(int(n**0.5), 0, -1): + if n % i == 0: + return i + + return 1 + + +def _is_passive_array(arr): + return isinstance(arr, _PassiveNamedArray) + + +def _prepend_named_batch_axis(leading_axis: Axis): + def to_active_named_array(leaf): + if isinstance(leaf, _PassiveNamedArray): + return leaf.as_scanned_result(leading_axis) + else: + return leaf + + return to_active_named_array diff --git a/src/haliax/hof.py b/src/haliax/hof.py index f90ef7c..87eb90f 100644 --- a/src/haliax/hof.py +++ b/src/haliax/hof.py @@ -1,249 +1,29 @@ -import dataclasses import inspect from functools import wraps -from typing import Any, Callable, ParamSpec, Protocol, Tuple, TypeVar, Union, overload import equinox as eqx import jax -import jax.lax as lax from jaxtyping import PyTree -import haliax import haliax.tree_util as htu -from ._src.util import index_where +from ._src.scan import ( + UnnamedAxisSpec, + _infer_axis_size_from_tree, + _is_passive_array, + _pacify_named_arrays, + _PassiveNamedArray, + _prepend_named_batch_axis, + _zero_if_array_else_none, + fold, + map, + scan, +) from .axis import Axis, AxisSelector, selects_axis from .core import NamedArray from .jax_utils import Static, broadcast_prefix, is_jax_array_like from .partitioning import physical_axis_name -from .util import is_jax_or_hax_array_like, is_named_array - - -BoolAxisSpec = Union[bool, Callable[[Any], bool]] -Carry = TypeVar("Carry") -X = TypeVar("X", contravariant=True) -Y = TypeVar("Y", covariant=True) -Args = ParamSpec("Args") - - -def is_named_or_shaped_array_like(x): - return (is_jax_array_like(x) and x.ndim >= 1) or is_named_array(x) - - -class ScanFn(Protocol[Carry, Args, Y]): - """ """ - - def __call__(self, carry: Carry, *args: Args.args, **kwargs: Args.kwargs) -> Tuple[Carry, Y]: - ... - - -@overload -def scan( - f: Callable[[Carry, X], Tuple[Carry, Y]], - axis: AxisSelector, - *, - reverse: bool = False, - unroll: int = 1, - is_scanned: BoolAxisSpec = is_named_or_shaped_array_like, -) -> Callable[[Carry, PyTree[X]], Tuple[Carry, PyTree[Y]]]: - ... - - -@overload -def scan( - f: Callable, - axis: AxisSelector, - *, - reverse: bool = False, - unroll: int = 1, - is_scanned: BoolAxisSpec = is_named_or_shaped_array_like, -) -> Callable: - ... - - -def scan( - f: Callable, # : ScanFn[Carry, Args, Y], This confuses mypy too much - axis: AxisSelector, - *, - reverse=False, - unroll=1, - is_scanned: BoolAxisSpec = is_named_or_shaped_array_like, -): - """ - Scan over a named axis. Non-scalar unnamed arrays will have their first axis scanned over. - - Unlike [jax.lax.scan][], this function is curried: it takes the function, axis, and configuration arguments first, and - then the initial carry and then any arguments to scan over as a separate curried function call. - - That is, `scan(f, axis)(init, xs)` is equivalent to `jax.lax.scan(f, init, xs)` - - Args: - f (Callable): function to scan over - axis (AxisSelector): axis to scan over - reverse (bool): if True, scan in reverse - unroll (int): unroll the loop by this amount - is_scanned (BoolAxisSpec): a function that takes a leaf of the tree and returns True if it should be scanned over, - False otherwise. Behaves similarly to the `default` argument in filter_jit - """ - - if isinstance(is_scanned, bool): - q = is_scanned # this is to make mypy happy - is_scanned = lambda _: q - - def is_scanned_with_axis(leaf): - if is_named_array(leaf): - return selects_axis(leaf.axes, axis) and is_scanned(leaf) - else: - return is_scanned(leaf) - - def scanned_f(init, *args, **kwargs): - # This implementation is a bit tricky. - - # first we want to partition the arguments into scanned and unscanned - # unscanned arguments are just passed through, essentially captured as part of a lambda - # scanned arguments are passed through the scan, which means we need to hoist the axis to the front - xs = (args, kwargs) - scanned_xs, unscanned_xs = eqx.partition(xs, is_scanned_with_axis, is_leaf=is_named_array) - - # Next we have to hoist the axis we're scanning over to the front of the array, because that's what scan - # expects. Then we have to scan over the 0th dim of the arrays (as flattened non-pytrees) - # We have to be careful that we don't try to create NamedArrays that have the shape of the scanned result - # but don't yet have the scanned axis as ones of `axes`, so we use _ScannedArrayResult that doesn't check - # invariants until we're ready to create the result. - axis_first_xs = htu.tree_map(_ensure_first(axis), scanned_xs) - - # now get a template of an element of "X" - x_elem = htu.tree_map(_select_0th(axis), axis_first_xs) - # NB: we don't want to use htu.tree_structure here because we want to eliminate the leading axis - x_elem_structure = jax.tree_util.tree_structure(x_elem) - - # now we can fold over the axis - @wraps(f) - def wrapped_fn(carry, scanned_x_leaves): - scanned_x = jax.tree_util.tree_unflatten(x_elem_structure, scanned_x_leaves) - # this part is the most delicate: combining the scanned x with the unscanned x - scanned_x = eqx.combine(scanned_x, unscanned_xs, is_leaf=is_named_array) - args, kwargs = scanned_x - carry, y = f(carry, *args, **kwargs) - y = htu.tree_map(_pacify_named_arrays, y) - return carry, y - - # as above, we don't want to use htu.tree_leaves here because we want to eliminate the leading axis - leaves = jax.tree_util.tree_leaves(axis_first_xs) - with jax.named_scope(f"scan({haliax.axis_name(axis)})"): - carry, ys = lax.scan(wrapped_fn, init, leaves, reverse=reverse, unroll=unroll) - true_axis = _infer_axis_size_from_result(ys, axis) - ys = jax.tree_util.tree_map(_prepend_named_batch_axis(true_axis), ys, is_leaf=_is_passive_array) - - return carry, ys - - return scanned_f - - -@overload -def fold( - fn: Callable[[Carry, X], Carry], - axis: AxisSelector, - *, - reverse: bool = False, - unroll: int = 1, - is_scanned: BoolAxisSpec = is_jax_or_hax_array_like, -) -> Callable[[Carry, PyTree[X]], Carry]: - ... - - -@overload -def fold( - fn: Callable, - axis: AxisSelector, - *, - reverse: bool = False, - unroll: int = 1, - is_scanned: BoolAxisSpec = is_jax_or_hax_array_like, -) -> Callable: - ... - - -def fold( - fn: Callable, - axis: AxisSelector, - *, - reverse: bool = False, - unroll: int = 1, - is_scanned: BoolAxisSpec = is_named_or_shaped_array_like, -) -> Callable: - """ - Slightly simpler implementation of scan that folds over the named axis of the array, not returning intermediates. - - As with scan, this function is curried: it takes the function, axis, and configuration arguments first, and - then the initial carry and then any arguments to scan over as a separate curried function call. - - Unnamed arrays will have their first axis scanned over, unless they are scalars, in which case they will be passed - through unchanged. - - Args: - fn: function to reduce over - axis: axis to reduce over - reverse: if True, reduce in reverse - unroll: unroll the loop by this amount - is_scanned: a function that takes a leaf of the tree and returns True if it should be scanned over, - False otherwise. Behaves similarly to the `default` argument in filter_jit - - Returns: - A function that takes the initial carry and then the arguments to reduce over, and returns the final carry - """ - - def scan_compatible_fn(carry, *args, **kwargs): - return fn(carry, *args, **kwargs), None - - scan_preconfig = scan(scan_compatible_fn, axis, reverse=reverse, unroll=unroll, is_scanned=is_scanned) - - def scanned_f(init, *args, **kwargs): - return scan_preconfig(init, *args, **kwargs)[0] - - return scanned_f - - -def map( - fn: Callable[[X], Y], - axis: Axis, - reverse: bool = False, - unroll: int = 1, - is_mapped: BoolAxisSpec = is_jax_or_hax_array_like, -) -> Callable[[PyTree[X]], PyTree[Y]]: - """ - NamedArray aware version of jax.lax.map. Normal arrays are mapped according to the specs as in equinox.filter_map, - except that the output axis is always 0 b/c it's annoying to make anything else work. - - You'll typically want to use map (instead of a vmap or just vectorized code) when you want to encourage XLA to - loop over the axis to control memory. - - Args: - fn (Callable): function to map over - axis (Axis): axis to map over - reverse (bool): if True, map in reverse - unroll (int): unroll the loop by this amount - - """ - - def scan_compatible_fn(_, x): - del _ - return None, fn(x) - - scan_preconfig = scan(scan_compatible_fn, axis, reverse=reverse, unroll=unroll, is_scanned=is_mapped) - - def scanned_f(*args, **kwargs): - return scan_preconfig(None, *args, **kwargs)[1] - - return scanned_f - - -ResolvedUnnamedAxisSpec = Union[int, None] -UnnamedAxisSpec = Union[ResolvedUnnamedAxisSpec, Callable[[Any], ResolvedUnnamedAxisSpec]] - - -def _zero_if_array_else_none(x: Any) -> ResolvedUnnamedAxisSpec: - return 0 if is_jax_array_like(x) else None +from .util import is_named_array def vmap( @@ -359,7 +139,7 @@ def vmap( result = eqx.combine(result_dynamic, result_static.value) # if we were passed in a string arg, we need to get its axis size out from some result - true_axis = _infer_axis_size_from_result(result, axis) + true_axis = _infer_axis_size_from_tree(result, axis) if true_axis is None: raise ValueError("vmap failed to infer axis size from result") @@ -369,74 +149,6 @@ def vmap( return wrapped_vmap_fn -def _infer_axis_size_from_result(result, axis): - if isinstance(axis, str): - result_leaves = jax.tree_util.tree_leaves(result, is_leaf=_is_passive_array) - if len(result_leaves) == 0: - # this really shouldn't happen - return None - if isinstance(result_leaves[0], _PassiveNamedArray): - true_axis_size = result_leaves[0].array.shape[0] # batch axis is defined to be 0 above - true_axis = Axis(axis, true_axis_size) - else: - true_axis_size = result_leaves[0].shape[0] # batch axis is defined to be 0 above - true_axis = Axis(axis, true_axis_size) - else: - true_axis = axis - return true_axis - - -@jax.tree_util.register_pytree_node_class -@dataclasses.dataclass(frozen=True) -class _PassiveNamedArray: - """For some higher-order jax manipulations, jax will insert/remove an axis at the beginning of the array (or - sometimes elsewhere). Jax doesn't know about our NamedArray wrapper, so we need a variant of NamedArray - that doesn't care about the axis names. This is that variant.This class is a 'chill' version of NamedArray - that doesn't check invariants until we're ready to create the result - - For example, with scan in NamedArray, we can't just have the scan tree prepend the scanned axis to the result, - because we don't have a way to feed it the name of the scanned axis. - """ - - array: jax.numpy.ndarray - main_axes: Tuple[Axis, ...] - - def as_scanned_result(self, scan_axis: Axis): - return NamedArray(self.array, (scan_axis,) + self.main_axes) - - def strip_axis(self, axis: AxisSelector): - if isinstance(axis, Axis): - index = self.main_axes.index(axis) - else: - index = index_where(lambda a: a.name == axis, self.main_axes) - return NamedArray(self.array, self.main_axes[:index] + self.main_axes[index + 1 :]) - - def to_named_array(self): - return NamedArray(self.array, self.main_axes) - - def tree_flatten(self) -> Any: - return ((self.array,), self.main_axes) - - @classmethod - def tree_unflatten(cls, aux, tree: Any) -> Any: - assert len(tree) == 1 - return cls(tree[0], main_axes=aux) - - -def _is_passive_array(arr): - return isinstance(arr, _PassiveNamedArray) - - -def _prepend_named_batch_axis(leading_axis: Axis): - def to_active_named_array(leaf): - if isinstance(leaf, _PassiveNamedArray): - return leaf.as_scanned_result(leading_axis) - else: - return leaf - - return to_active_named_array - - def _to_unbatched_named_array(axis_to_strip: AxisSelector): def to_unbatched_named_array(leaf): if isinstance(leaf, _PassiveNamedArray): @@ -450,38 +162,4 @@ def _to_unbatched_named_array(axis_to_strip: AxisSelector): return to_unbatched_named_array -def _pacify_named_arrays(leaf): - if isinstance(leaf, NamedArray): - return _PassiveNamedArray(leaf.array, leaf.axes) - elif isinstance(leaf, _PassiveNamedArray): - assert False, "PassiveNamedArray should not be present in the tree" - else: - return leaf - - -def _select_0th(axis): - def select_0th(leaf): - if isinstance(leaf, NamedArray): - return leaf.take(axis, 0) - elif isinstance(leaf, _PassiveNamedArray): - assert False, "PassiveNamedArray should not be present in the tree" - else: - # other leaves don't matter - return leaf - - return select_0th - - -def _ensure_first(axis): - def ensure_first(leaf): - if isinstance(leaf, NamedArray): - return leaf.rearrange((axis, ...)) - elif isinstance(leaf, _PassiveNamedArray): - assert False, "PassiveNamedArray should not be present in the tree" - else: - return leaf - - return ensure_first - - __all__ = ["scan", "fold", "vmap", "map"] diff --git a/src/haliax/jax_utils.py b/src/haliax/jax_utils.py index cf1c12c..21ac651 100644 --- a/src/haliax/jax_utils.py +++ b/src/haliax/jax_utils.py @@ -1,5 +1,6 @@ import functools as ft import typing +import warnings from typing import Any, Callable, Optional, Sequence, Union import equinox as eqx @@ -8,8 +9,8 @@ import numpy as np from jax import Array from jax import numpy as jnp from jax import random as jrandom -from jax._src.numpy import lax_numpy -from jax._src.typing import DTypeLike +from jax.ad_checkpoint import checkpoint_name +from jax.typing import DTypeLike from jaxtyping import PRNGKeyArray import haliax @@ -27,6 +28,7 @@ except ImportError: F = typing.TypeVar("F", bound=Callable[..., Any]) +T = typing.TypeVar("T") class Static(eqx.Module): @@ -70,23 +72,9 @@ def filter_eval_shape(*args, **kwargs): def filter_checkpoint(fun: Callable, *, prevent_cse: bool = True, policy: Optional[Callable[..., bool]] = None): """As `jax.checkpoint`, but allows any Python object as inputs and outputs""" - @ft.wraps(fun) - def _fn(_static, _dynamic): - _args, _kwargs = eqx.combine(_static, _dynamic) - _out = fun(*_args, **_kwargs) - _dynamic_out, _static_out = eqx.partition(_out, is_jax_array_like) - return _dynamic_out, Static(_static_out) + warnings.warn("filter_checkpoint is deprecated, use eqx.filter_checkpoint instead", DeprecationWarning) - checkpointed_fun = jax.checkpoint(_fn, prevent_cse=prevent_cse, policy=policy, static_argnums=(0,)) - - @ft.wraps(fun) - def wrapper(*args, **kwargs): - dynamic, static = eqx.partition((args, kwargs), is_jax_array_like) - dynamic_out, static_out = checkpointed_fun(static, dynamic) - - return eqx.combine(dynamic_out, static_out.value) - - return wrapper + return eqx.filter_checkpoint(fun, prevent_cse=prevent_cse, policy=policy) def is_jax_array_like(x): @@ -202,7 +190,7 @@ def _jittable_dg_einsum( contract_path = opt_einsum.contract_path else: ty = next(iter(non_constant_dim_types)) - contract_path = lax_numpy._poly_einsum_handlers.get(ty, lax_numpy._default_poly_einsum_handler) + contract_path = jax_einsum._poly_einsum_handlers.get(ty, jax_einsum._default_poly_einsum_handler) # using einsum_call=True here is an internal api for opt_einsum... sorry operands, contractions = contract_path(*operands, einsum_call=True, use_blas=True, optimize=optimize) @@ -212,3 +200,66 @@ def _jittable_dg_einsum( if spec is not None: einsum = jax.named_call(einsum, name=spec) return einsum(operands, contractions, precision, preferred_element_type, _dot_general) # type: ignore[operator] + + +def tree_checkpoint_name(x: T, name: str) -> T: + """ + Checkpoint a tree of arrays with a given name. This is useful for gradient checkpointing. + This is equivalent to calling [jax.ad_checkpoint.checkpoint_name][] + except that it works for any PyTree, not just arrays. + + See Also: + * [jax.ad_checkpoint.checkpoint_name][] + * [haliax.nn.ScanCheckpointPolicy][] + """ + + def _checkpoint_leaf(x): + if is_jax_array_like(x): + return checkpoint_name(x, name) + else: + return x + + return jax.tree.map(_checkpoint_leaf, x) + + +def multilevel_scan(f, carry, xs, outer_size, length, reverse=False, unroll=1): + """ + + Similar to jax.lax.scan, but "nested". You take your scanned axis and break it up into outer_size chunks, then + scan each chunk with a scan. + + You use this if you want to save memory by, e.g., implementing the sqrt(N) memory trick for checkpointing. + + This is typically ~20% slower than the O(n) memory thing, but it's often worthwhile. + + Credit to Roy and Matt. + """ + + inner_size = length // outer_size + + if inner_size * outer_size != length: + raise ValueError(f"Length {length} must be divisible by outer_size {outer_size}") + + def _reshape(x): + if is_jax_array_like(x) and x.shape != (): + return x.reshape([outer_size, inner_size, *x.shape[1:]]) + else: + return x + + xs_shaped = jax.tree.map(_reshape, xs) + + carry, scanned = jax.lax.scan( + jax.remat(ft.partial(jax.lax.scan, f, reverse=reverse, unroll=unroll)), + carry, + xs_shaped, + reverse=reverse, + unroll=True, + ) + + def _deshape(x): + if is_jax_array_like(x) and x.shape != (): + return x.reshape([length, *x.shape[2:]]) + else: + return x + + return carry, jax.tree.map(_deshape, scanned) diff --git a/src/haliax/nn/__init__.py b/src/haliax/nn/__init__.py index 01662da..23029e2 100644 --- a/src/haliax/nn/__init__.py +++ b/src/haliax/nn/__init__.py @@ -38,7 +38,7 @@ from .loss import binary_cross_entropy_loss, cross_entropy_loss, cross_entropy_l from .mlp import MLP from .normalization import LayerNorm, RmsNorm, log_softmax, logsumexp, softmax, standardize from .pool import max_pool, mean_pool, min_pool -from .scan import BlockSeq, Stacked +from .scan import BlockSeq, ScanCheckpointPolicy, Stacked def one_hot(x: NamedArray | int, class_axis: Axis, *, dtype=None) -> NamedArray: @@ -114,4 +114,5 @@ __all__ = [ "max_pool", "mean_pool", "min_pool", + "ScanCheckpointPolicy", ] diff --git a/src/haliax/nn/scan.py b/src/haliax/nn/scan.py index 6dc04db..a199e51 100644 --- a/src/haliax/nn/scan.py +++ b/src/haliax/nn/scan.py @@ -1,6 +1,8 @@ +import dataclasses import functools import re -from typing import Any, Dict, Generic, Optional, Protocol, Sequence, Type, TypeVar, cast +import warnings +from typing import Any, Dict, Generic, Literal, Optional, Protocol, Sequence, Type, TypeVar, Union, cast import equinox as eqx import jax @@ -8,9 +10,10 @@ from jax import numpy as jnp import haliax import haliax.util -from haliax.jax_utils import filter_checkpoint, is_jax_array_like +from haliax.jax_utils import tree_checkpoint_name from haliax.util import is_jax_or_hax_array_like +from .._src.scan import ScanCheckpointPolicy, ScanCheckpointSpec from .._src.state_dict import ModuleWithStateDictSerialization, StateDict, with_prefix from ..axis import Axis @@ -39,7 +42,12 @@ class BlockFoldable(Protocol[M]): @classmethod def init( - cls: Type[S], Block: Axis, module: Type[M], *, gradient_checkpointing: bool = False, prevent_cse: bool = False + cls: Type[S], + Block: Axis, + module: Type[M], + *, + gradient_checkpointing: ScanCheckpointSpec = False, + prevent_cse: bool = False, ) -> ModuleInit[S]: ... @@ -70,23 +78,37 @@ class BlockSeq(ModuleWithStateDictSerialization, Generic[M]): blocks: Sequence[M] Block: Axis = eqx.static_field() - gradient_checkpointing: bool = eqx.static_field() + gradient_checkpointing: ScanCheckpointPolicy = eqx.static_field() @classmethod def init( - cls: Type[S], Block: Axis, module: Type[M], *, gradient_checkpointing: bool = False, prevent_cse: bool = False + cls: Type[S], + Block: Axis, + module: Type[M], + *, + gradient_checkpointing: ScanCheckpointSpec = False, + prevent_cse: bool | None = None, ) -> ModuleInit[S]: """ This is a curried init method that takes the Block and module and returns a function that takes the arguments to the module's init method. Any NamedArrays in the arguments will be sliced along the Block axis (if it exists). JAX arrays will be sliced along the first axis. """ - del prevent_cse # not needed, but kept for compat with Stacked + + gradient_checkpointing = ScanCheckpointPolicy._mk(gradient_checkpointing) + + if prevent_cse is not None: + warnings.warn( + "The prevent_cse argument is deprecated and will be removed in a future version of Haliax. Use the" + " ScanCheckpointPolicy instead.", + DeprecationWarning, + ) + gradient_checkpointing = dataclasses.replace(gradient_checkpointing, prevent_cse=prevent_cse) @functools.wraps(module) def fn(*args, **kwargs): # The only complexity here is that the args and kwargs might have a Block axis in them, - # in which case we need to loop over them them to slice them out. + # in which case we need to loop over them to slice them out. def init_block(i): (block_args, block_kwargs) = haliax.tree_util.tree_map( @@ -101,38 +123,46 @@ class BlockSeq(ModuleWithStateDictSerialization, Generic[M]): return fn def scan(self, init: T, *extra_args, **extra_kwargs): - out = [] - carry = init + def do_scan(init, *extra_args, **extra_kwargs): + out = [] + carry = init - for i, block in enumerate(self.blocks): - if self.gradient_checkpointing: - block = filter_checkpoint(block) - (block_args, block_kwargs) = haliax.tree_util.tree_map( - functools.partial(BlockSeq._slice_out, self.Block, i), (extra_args, extra_kwargs) - ) - block_result = block(carry, *block_args, **block_kwargs) - if not isinstance(block_result, (tuple, list)) or len(block_result) != 2: - raise ValueError( - f"BlockSeq.scan expects the block to return a pair of (carry, extra), got {block_result}" + for i, block in enumerate(self.blocks): + + (block_args, block_kwargs) = haliax.tree_util.tree_map( + functools.partial(BlockSeq._slice_out, self.Block, i), (extra_args, extra_kwargs) ) - carry, extra = block_result + block_result = block(carry, *block_args, **block_kwargs) + + if not isinstance(block_result, (tuple, list)) or len(block_result) != 2: + raise ValueError( + f"BlockSeq.scan expects the block to return a pair of (carry, extra), got {block_result}" + ) + + carry, extra = block_result - out.append(extra) + carry = tree_checkpoint_name(carry, self._carry_ckpt_name) + extra = tree_checkpoint_name(extra, self._output_ckpt_name) - # TODO: do we want to stack the outputs? - return carry, out + out.append(extra) + + return carry, haliax.tree_util.tree_map(lambda *x: haliax.stack(self.Block, x), *out) + + return do_scan(init, *extra_args, **extra_kwargs) def fold(self, init: T, *args, **kwargs) -> T: - carry = init - for i, block in enumerate(self.blocks): - if self.gradient_checkpointing: - block = filter_checkpoint(block) - (block_args, block_kwargs) = haliax.tree_util.tree_map( - functools.partial(BlockSeq._slice_out, self.Block, i), (args, kwargs) - ) - carry = block(carry, *block_args, **block_kwargs) - return carry + def do_fold(init, *args, **kwargs): + carry = init + for i, block in enumerate(self.blocks): + (block_args, block_kwargs) = haliax.tree_util.tree_map( + functools.partial(BlockSeq._slice_out, self.Block, i), (args, kwargs) + ) + carry = block(carry, *block_args, **block_kwargs) + carry = tree_checkpoint_name(carry, self._carry_ckpt_name) + return carry + + return do_fold(init, *args, **kwargs) def unstacked(self) -> Sequence[M]: return self.blocks @@ -174,6 +204,14 @@ class BlockSeq(ModuleWithStateDictSerialization, Generic[M]): return state_dict + @property + def _output_ckpt_name(self): + return f"BlockSeq[{self.Block}, {self.blocks[0].__class__.__name__}].outputs" + + @property + def _carry_ckpt_name(self): + return f"BlockSeq[{self.Block}, {self.blocks[0].__class__.__name__}].carry" + class Stacked(ModuleWithStateDictSerialization, Generic[M]): """ @@ -192,12 +230,12 @@ class Stacked(ModuleWithStateDictSerialization, Generic[M]): that the function has the same control flow for every element of the stack. Stacked supports both "fold" and "scan" semantics. "fold" is the same as a for loop that accumulates a single - output, while "scan" is the same as a for loop that accumulates a list of intermediates as well as the final output. + output, while "scan" is the same as a for loop that accumulates a list of outputs as well as the final output. Stacked also supports gradient checkpointing, which is useful for very large models that don't fit in memory. Typically only one of "fold" or "scan" can be used with a given Stacked module, depending on the what the module - returns: if the module returns a single output, use "fold"; if the module returns a sequence of intermediates and + returns: if the module returns a single output, use "fold"; if the module returns a sequence of outputs and an output to be passed to the next layer, use "scan". More concretely, for a transformer, you would use "scan" if you wanted to return a kv cache (or the attention matrix) as well as the output of the transformer. If you just wanted the output of the transformer, you would use "fold". @@ -227,48 +265,65 @@ class Stacked(ModuleWithStateDictSerialization, Generic[M]): stacked: M Block: Axis = eqx.static_field() - # TODO: support fancier gradient checkpointing - gradient_checkpointing: bool = eqx.static_field() - prevent_cse: bool = eqx.static_field() + gradient_checkpointing: ScanCheckpointPolicy = eqx.static_field() @classmethod def init( - cls, Block: Axis, module: Type[M], *, gradient_checkpointing: bool = False, prevent_cse: bool = False + cls, + Block: Axis, + module: Type[M], + *, + gradient_checkpointing: ScanCheckpointSpec = False, + prevent_cse: bool | None = None, ) -> ModuleInit["Stacked[M]"]: """ Initialize a Stacked module. This method is curried: you can pass in the Block and module, and it will return a function that takes (batched) arguments to the vmapped module's init method. - :param Block: - :param module: - :param gradient_checkpointing: - :param prevent_cse: - :return: + + Args: + Block: The axis that will be stacked over. This is typically a "layer" axis, but could be any axis. + module: The module that will be stacked. This module must take a batched input and return a batched output. + gradient_checkpointing: Whether to use gradient checkpointing. If True, uses the default policy. If a string, + uses the policy specified by the string. If a ScanCheckpointPolicy, uses that policy. + prevent_cse: Whether to prevent common subexpression elimination in the checkpointed function. This is useful + for debugging, but may slow down the function. """ + gradient_checkpointing = ScanCheckpointPolicy._mk(gradient_checkpointing) + + if prevent_cse is not None: + warnings.warn( + "The prevent_cse argument is deprecated and will be removed in a future version of Haliax. Use the" + " ScanCheckpointPolicy instead.", + DeprecationWarning, + ) + + gradient_checkpointing = dataclasses.replace(gradient_checkpointing, prevent_cse=prevent_cse) + @functools.wraps(module) def fn(*args, **kwargs): stacked = haliax.vmap(module.init, Block)(*args, **kwargs) - return Stacked(stacked, Block, gradient_checkpointing, prevent_cse) + return Stacked(stacked, Block, gradient_checkpointing) return fn def scan(self, init, *extra_args, **extra_kwargs): """ Scan over the stacked module. This is the same as a for loop that applies each instance of the module in sequence - to the input, passing the output of one instance to the next instance. It returns a stack of intermediates as + to the input, passing the output of one instance to the next instance. It returns a stack of outputs as well as the final output. That is, it behaves similarly to the following Python code: ```python carry = init - intermediates = [] + outputs = [] for block in self.stacked: carry, extra = block(carry) - intermediates.append(extra) + outputs.append(extra) - return carry, hax.stack(Block, intermediates) + return carry, hax.stack(Block, outputs) ``` Args: @@ -279,11 +334,18 @@ class Stacked(ModuleWithStateDictSerialization, Generic[M]): Returns: """ - if self.gradient_checkpointing: - do_block = filter_checkpoint(self._do_block, prevent_cse=self.prevent_cse) - else: - do_block = self._do_block - return haliax.scan(do_block, self.Block)(init, self.stacked, *extra_args, **extra_kwargs) + + def do_block(carry, block, *args, **kwargs): + carry, out = block(carry, *args, **kwargs) + return carry, out + + def do_scan(init, *extra_args, **extra_kwargs): + carry, out = haliax.scan(do_block, self.Block, remat=self.gradient_checkpointing)( + init, self.stacked, *extra_args, **extra_kwargs + ) + return carry, out + + return do_scan(init, *extra_args, **extra_kwargs) def fold(self, init, *args, **kwargs): """ @@ -300,19 +362,25 @@ class Stacked(ModuleWithStateDictSerialization, Generic[M]): ``` Args: - init: - *args: - **kwargs: + init: The initial value of carry to pass to the first block + *args: Extra arguments to pass to the blocks. These are passed directly to the blocks + **kwargs: Extra keyword arguments to pass to the blocks. These are passed directly to the blocks Returns: """ - if self.gradient_checkpointing: - do_block = filter_checkpoint(self._do_block, prevent_cse=self.prevent_cse) - else: - do_block = self._do_block - return haliax.fold(do_block, self.Block)(init, self.stacked, *args, **kwargs) + def do_block(carry, block, *args, **kwargs): + carry = block(carry, *args, **kwargs) + return carry + + def do_fold(init, *extra_args, **extra_kwargs): + carry = haliax.fold(do_block, self.Block, remat=self.gradient_checkpointing)( + init, self.stacked, *extra_args, **extra_kwargs + ) + return carry + + return do_fold(init, *args, **kwargs) @staticmethod def _do_block(carry, block, *extra_args, **extra_kwargs): diff --git a/src/haliax/random.py b/src/haliax/random.py index 68f276f..9d2c4ea 100644 --- a/src/haliax/random.py +++ b/src/haliax/random.py @@ -24,7 +24,6 @@ def uniform( minval = broadcast_to(minval, shape).array maxval = broadcast_to(maxval, shape).array jax_shape = _to_jax_shape(shape) - print(jax_shape, minval, maxval) jax_array = jrandom.uniform(key=key, shape=jax_shape, dtype=dtype, minval=minval, maxval=maxval) return haliax.auto_sharded(NamedArray(jax_array, shape)) diff --git a/tests/test_hof.py b/tests/test_hof.py index dfde01f..ad80303 100644 --- a/tests/test_hof.py +++ b/tests/test_hof.py @@ -119,7 +119,24 @@ def test_scan_doesnt_scan_init(): assert jnp.all(jnp.isclose(total.array, init + jnp.sum(named1.array * 4.0))) -def test_reduce(): +def test_scan_hierarchical(): + Height = Axis("Height", 10) + Width = Axis("Width", 3) + Depth = Axis("Depth", 4) + named1 = hax.random.uniform(PRNGKey(0), (Height, Width, Depth)) + + def scan_fun(acc, x): + return acc + jnp.sum(x.array), x.take("Width", 2) + + total, selected = hax.scan(scan_fun, "Height")(0.0, named1) + ckpt = hax.ScanCheckpointPolicy(nested=True) + total_blocked, selected_blocked = hax.scan(scan_fun, "Height", remat=ckpt)(0.0, named1) + + assert jnp.all(jnp.isclose(total, total_blocked)) + assert jnp.all(jnp.equal(selected.array, selected_blocked.array)) + + +def test_fold(): Height = Axis("Height", 10) Width = Axis("Width", 3) Depth = Axis("Depth", 4) @@ -132,7 +149,7 @@ def test_reduce(): assert jnp.all(jnp.isclose(total.rearrange(acc.axes).array, jnp.sum(named1.array, axis=2))) -def test_reduce_str_args(): +def test_fold_str_args(): Height = Axis("Height", 10) Width = Axis("Width", 3) Depth = Axis("Depth", 4) @@ -145,7 +162,7 @@ def test_reduce_str_args(): assert jnp.all(jnp.isclose(total.rearrange(acc.axes).array, jnp.sum(named1.array, axis=2))) -def test_reduce_static_args(): +def test_fold_static_args(): Height = Axis("Height", 10) Width = Axis("Width", 3) Depth = Axis("Depth", 4) @@ -163,7 +180,7 @@ def test_reduce_static_args(): assert jnp.all(jnp.isclose(total.rearrange(acc.axes).array, jnp.sum(named1.array, axis=2))) -def test_reduce_doesnt_reduce_scalars(): +def test_fold_doesnt_reduce_scalars(): Height = Axis("Height", 10) named1 = hax.random.uniform(PRNGKey(0), (Height,)) diff --git a/tests/test_scan.py b/tests/test_scan.py index a7b6cf6..c1e7383 100644 --- a/tests/test_scan.py +++ b/tests/test_scan.py @@ -1,9 +1,11 @@ import equinox as eqx import jax import pytest +from equinox import filter_grad import haliax as hax -from haliax.nn.scan import BlockSeq, Stacked +from haliax.jax_utils import tree_checkpoint_name +from haliax.nn.scan import BlockSeq, ScanCheckpointPolicy, Stacked def test_unstacked(): @@ -130,8 +132,6 @@ def test_scan_with_aux_named_args(): z_seq, z_seq_scan = m_seq.scan(x, initial_y, key=jax.random.split(jax.random.PRNGKey(2), Block.size)) assert hax.all(hax.isclose(z, z_seq, atol=1e-5)) - z_seq_scan = hax.stack(Block, z_seq_scan) - assert hax.all(hax.isclose(z_scan, z_seq_scan, atol=1e-5)) @@ -164,3 +164,82 @@ def test_stacked_to_state_dict(): y2 = m2.fold(input, key=key) assert hax.all(hax.equal(y, y2)) + + +Block = hax.Axis("block", 4) +E = hax.Axis("E", 10) + + +@pytest.mark.parametrize( + "name,policy,expected_scan_shapes", + [ + ("disabled", ScanCheckpointPolicy(disable=True), [(E.size,), (Block.size, E.size), (Block.size, E.size)]), + ("carry_true", True, [(E.size,), (Block.size, E.size)]), + ( + "carry", + ScanCheckpointPolicy(save_carries=True, save_block_internals=False), + [(E.size,), (Block.size, E.size)], + ), + ( + "everything", + ScanCheckpointPolicy(save_carries=True, save_inputs=True, save_block_internals=True), + [(E.size,), (Block.size, E.size), (Block.size, E.size)], + ), + ( + "internals", + ScanCheckpointPolicy(save_carries=False, save_block_internals=True), + [(E.size,), (Block.size, E.size), (Block.size, E.size)], + ), + ( + "cos", + ScanCheckpointPolicy(save_carries=False, save_block_internals=["cos"]), + [(E.size,), (Block.size, E.size)], + ), + ( + "sin", + ScanCheckpointPolicy(save_carries=True, save_block_internals=["sin"]), + [(E.size,), (Block.size, E.size), (Block.size, E.size)], + ), + ("simple", ScanCheckpointPolicy(simple=True), [(E.size,), (Block.size, E.size)]), + ("nested", ScanCheckpointPolicy(simple=True, nested=2), [(E.size,), (2, E.size)]), + ], +) +def test_checkpoint_carries(name, policy, expected_scan_shapes): + class Module(eqx.Module): + named: hax.NamedArray + + def __call__(self, x): + y = tree_checkpoint_name(hax.sin(x + self.named), "sin") + y = tree_checkpoint_name(hax.cos(y + x), "cos") + return y + x + + @staticmethod + def init(named): + return Module(named=named) + + initial_named = hax.random.uniform(jax.random.PRNGKey(0), (Block, E)) + + m = Stacked.init( + Block, + Module, + gradient_checkpointing=policy, # type: ignore + )(named=initial_named) + + def loss_fn(m, x): + y = m.fold(x) + return hax.sum(y).scalar() + + grad_fn = filter_grad(loss_fn) + + jaxpr = jax.make_jaxpr(grad_fn)(m, hax.random.uniform(jax.random.PRNGKey(1), (E,))) + closed_call = next(eqn for eqn in jaxpr.jaxpr.eqns if eqn.primitive in [jax.lax.scan_p]) + out_shapes = [out.aval.shape for out in closed_call.outvars] + + print(name) + print(jaxpr) + from jax._src.ad_checkpoint import saved_residuals + + for residual in saved_residuals(loss_fn, m, hax.random.uniform(jax.random.PRNGKey(1), (E,))): + print(residual) + + assert out_shapes == expected_scan_shapes, f"{name}: Expected {expected_scan_shapes}, got {out_shapes}" commit b58b1c975f201f5eeed881272270da32dde3af99 Date: 2025-03-28T14:22:25-07:00 shaped arange (#128) diff --git a/src/haliax/__init__.py b/src/haliax/__init__.py index e99e977..ca1d0ec 100644 --- a/src/haliax/__init__.py +++ b/src/haliax/__init__.py @@ -121,13 +121,38 @@ def full_like(a: NamedArray, fill_value: T, dtype: Optional[DTypeLike] = None) - return NamedArray(jnp.full_like(a.array, fill_value, dtype=dtype), a.axes) -def arange(axis: Axis, *, start=0, step=1, dtype: Optional[DTypeLike] = None) -> NamedArray: - """Version of jnp.arange that returns a NamedArray""" +def arange(axis: AxisSpec, *, start=0, step=1, dtype: Optional[DTypeLike] = None) -> NamedArray: + """ + Version of jnp.arange that returns a NamedArray. + + This version differs from jnp.arange (beyond the obvious NamedArray) in two ways: + + 1) It can work with a start that is a tracer (i.e. a JAX expression), whereas jax arange is not able to handle + tracers. + 2) Axis can be more than one axis, in which case it's equivalent to arange of the product of sizes, followed by + reshape. + + Examples + + ```python + X, Y = hax.make_axes(X=3, Y=4) + # Create a NamedArray along a single axis + arr = hax.arange(X) # equivalent to jnp.arange(0, 3, 1) + # 2D + arr = hax.arange((X, Y)) # equivalent to jnp.arange(0, 12, 1).reshape(3, 4) + ``` + + """ + from haliax.jax_utils import to_jax_shape + from haliax.util import ensure_tuple + # if start is a tracer, we need to be a bit cleverer since arange doesn't support tracers # return NamedArray(jnp.arange(start, stop, step, dtype=dtype), (axis,)) + size = axis_size(axis) - arr = jax.lax.iota(dtype=dtype or jnp.result_type(start), size=axis.size) * step + start - return NamedArray(arr, (axis,)) + arr = jax.lax.iota(dtype=dtype or jnp.result_type(start), size=size) * step + start + arr = arr.reshape(to_jax_shape(axis)) + return NamedArray(arr, ensure_tuple(axis)) # TODO: add overrides for arraylike start/stop to linspace, logspace, geomspace diff --git a/src/haliax/jax_utils.py b/src/haliax/jax_utils.py index 21ac651..06066da 100644 --- a/src/haliax/jax_utils.py +++ b/src/haliax/jax_utils.py @@ -263,3 +263,10 @@ def multilevel_scan(f, carry, xs, outer_size, length, reverse=False, unroll=1): return x return carry, jax.tree.map(_deshape, scanned) + + +def to_jax_shape(shape): + from haliax.core import Axis, ensure_tuple + + shape = ensure_tuple(shape) + return tuple(axis.size if isinstance(axis, Axis) else axis for axis in shape) diff --git a/src/haliax/random.py b/src/haliax/random.py index 9d2c4ea..ad461f3 100644 --- a/src/haliax/random.py +++ b/src/haliax/random.py @@ -12,7 +12,7 @@ from haliax.core import NamedArray, NamedOrNumeric, broadcast_to from haliax.util import ensure_tuple from .axis import Axis, AxisSelector, AxisSpec, selects_axis -from .jax_utils import named_call +from .jax_utils import named_call, to_jax_shape from .partitioning import physical_axis_name, physical_axis_size, pspec_for_axis @@ -23,7 +23,7 @@ def uniform( shape = ensure_tuple(shape) minval = broadcast_to(minval, shape).array maxval = broadcast_to(maxval, shape).array - jax_shape = _to_jax_shape(shape) + jax_shape = to_jax_shape(shape) jax_array = jrandom.uniform(key=key, shape=jax_shape, dtype=dtype, minval=minval, maxval=maxval) return haliax.auto_sharded(NamedArray(jax_array, shape)) @@ -31,7 +31,7 @@ def uniform( @named_call def normal(key, shape: AxisSpec, dtype=float): shape = ensure_tuple(shape) - jax_shape = _to_jax_shape(shape) + jax_shape = to_jax_shape(shape) jax_array = jrandom.normal(key=key, shape=jax_shape, dtype=dtype) return haliax.auto_sharded(NamedArray(jax_array, shape)) @@ -40,7 +40,7 @@ def normal(key, shape: AxisSpec, dtype=float): def bernoulli(key, shape: AxisSpec, p: NamedOrNumeric): shape = ensure_tuple(shape) p = broadcast_to(p, shape).array - jax_shape = _to_jax_shape(shape) + jax_shape = to_jax_shape(shape) jax_array = jrandom.bernoulli(key=key, p=p, shape=jax_shape) return haliax.auto_sharded(NamedArray(jax_array, shape)) @@ -50,7 +50,7 @@ def randint(key, shape: AxisSpec, minval: NamedOrNumeric, maxval: NamedOrNumeric shape = ensure_tuple(shape) minval = broadcast_to(minval, shape).array maxval = broadcast_to(maxval, shape).array - jax_shape = _to_jax_shape(shape) + jax_shape = to_jax_shape(shape) jax_array = jrandom.randint(key=key, shape=jax_shape, minval=minval, maxval=maxval, dtype=dtype) return haliax.auto_sharded(NamedArray(jax_array, shape)) @@ -59,7 +59,7 @@ def randint(key, shape: AxisSpec, minval: NamedOrNumeric, maxval: NamedOrNumeric def poisson(key, shape: AxisSpec, lam: NamedOrNumeric, dtype=int): shape = ensure_tuple(shape) lam = broadcast_to(lam, shape).array - jax_shape = _to_jax_shape(shape) + jax_shape = to_jax_shape(shape) jax_array = jrandom.poisson(key=key, lam=lam, shape=jax_shape, dtype=dtype) return haliax.auto_sharded(NamedArray(jax_array, shape)) @@ -67,7 +67,7 @@ def poisson(key, shape: AxisSpec, lam: NamedOrNumeric, dtype=int): @named_call def exponential(key, shape: AxisSpec, dtype=float): shape = ensure_tuple(shape) - jax_shape = _to_jax_shape(shape) + jax_shape = to_jax_shape(shape) jax_array = jrandom.exponential(key=key, shape=jax_shape, dtype=dtype) return haliax.auto_sharded(NamedArray(jax_array, shape)) @@ -76,7 +76,7 @@ def exponential(key, shape: AxisSpec, dtype=float): def gamma(key, shape: AxisSpec, a: NamedOrNumeric, dtype=float): shape = ensure_tuple(shape) a = broadcast_to(a, shape).array - jax_shape = _to_jax_shape(shape) + jax_shape = to_jax_shape(shape) jax_array = jrandom.gamma(key=key, a=a, shape=jax_shape, dtype=dtype) return haliax.auto_sharded(NamedArray(jax_array, shape)) @@ -86,7 +86,7 @@ def beta(key, shape: AxisSpec, a: NamedOrNumeric, b: NamedOrNumeric, dtype=float shape = ensure_tuple(shape) a = broadcast_to(a, shape).array b = broadcast_to(b, shape).array - jax_shape = _to_jax_shape(shape) + jax_shape = to_jax_shape(shape) jax_array = jrandom.beta(key=key, a=a, b=b, shape=jax_shape, dtype=dtype) return haliax.auto_sharded(NamedArray(jax_array, shape)) @@ -94,7 +94,7 @@ def beta(key, shape: AxisSpec, a: NamedOrNumeric, b: NamedOrNumeric, dtype=float @named_call def laplace(key, shape: AxisSpec, dtype=float): shape = ensure_tuple(shape) - jax_shape = _to_jax_shape(shape) + jax_shape = to_jax_shape(shape) jax_array = jrandom.laplace(key=key, shape=jax_shape, dtype=dtype) return haliax.auto_sharded(NamedArray(jax_array, shape)) @@ -102,7 +102,7 @@ def laplace(key, shape: AxisSpec, dtype=float): @named_call def cauchy(key, shape: AxisSpec, dtype=float): shape = ensure_tuple(shape) - jax_shape = _to_jax_shape(shape) + jax_shape = to_jax_shape(shape) jax_array = jrandom.cauchy(key=key, shape=jax_shape, dtype=dtype) return haliax.auto_sharded(NamedArray(jax_array, shape)) @@ -110,7 +110,7 @@ def cauchy(key, shape: AxisSpec, dtype=float): @named_call def logistic(key, shape: AxisSpec, dtype=float): shape = ensure_tuple(shape) - jax_shape = _to_jax_shape(shape) + jax_shape = to_jax_shape(shape) jax_array = jrandom.logistic(key=key, shape=jax_shape, dtype=dtype) return haliax.auto_sharded(NamedArray(jax_array, shape)) @@ -120,7 +120,7 @@ def truncated_normal(key, shape: AxisSpec, lower: NamedOrNumeric, upper: NamedOr shape = ensure_tuple(shape) lower = broadcast_to(lower, shape).array upper = broadcast_to(upper, shape).array - jax_shape = _to_jax_shape(shape) + jax_shape = to_jax_shape(shape) jax_array = jrandom.truncated_normal(key=key, lower=lower, upper=upper, shape=jax_shape, dtype=dtype) return haliax.auto_sharded(NamedArray(jax_array, shape)) @@ -201,7 +201,7 @@ def generate_sharded(fn, axis: Optional[AxisSelector] = None): @named_call def ball(key, shape: AxisSpec, D: Axis, p: float = 2.0, dtype=float): shape = ensure_tuple(shape) - jax_shape = _to_jax_shape(shape) + jax_shape = to_jax_shape(shape) jax_array = jrandom.ball(key=key, shape=jax_shape, d=D.size, p=p, dtype=dtype) return haliax.auto_sharded(NamedArray(jax_array, shape + (D,))) @@ -225,7 +225,7 @@ def choice( if p is not None: assert p.resolve_axis(ensure_tuple(axis)) == p.axes, f"p must be 1D with axis {axis} or be None" - jax_shape = _to_jax_shape(shape) + jax_shape = to_jax_shape(shape) jax_p = p.array if p is not None else None jax_array = jrandom.choice(key, a.array, jax_shape, replace=replace, p=jax_p, axis=index) @@ -264,7 +264,7 @@ def categorical(key, logits: NamedArray, axis: AxisSelector, shape: Optional[Axi index = logits._lookup_indices(axis) assert index is not None, f"axis {axis} not in logits" - jax_shape = _to_jax_shape(shape) + jax_shape = to_jax_shape(shape) jax_array = jrandom.categorical(key, logits.array, axis=index, shape=jax_shape) return haliax.auto_sharded(NamedArray(jax_array, shape)) @@ -273,7 +273,7 @@ def categorical(key, logits: NamedArray, axis: AxisSelector, shape: Optional[Axi @named_call def gumbel(key, shape: AxisSpec, dtype=float): shape = ensure_tuple(shape) - jax_shape = _to_jax_shape(shape) + jax_shape = to_jax_shape(shape) jax_array = jrandom.gumbel(key, jax_shape, dtype=dtype) return haliax.auto_sharded(NamedArray(jax_array, shape)) @@ -288,7 +288,7 @@ def permutation(key, x: NamedArray, axis: AxisSelector, independent: bool = Fals @named_call def rademacher(key, shape: AxisSpec, dtype=float): shape = ensure_tuple(shape) - jax_shape = _to_jax_shape(shape) + jax_shape = to_jax_shape(shape) jax_array = jrandom.rademacher(key, jax_shape, dtype=dtype) return haliax.auto_sharded(NamedArray(jax_array, shape)) @@ -297,7 +297,7 @@ def rademacher(key, shape: AxisSpec, dtype=float): def t(key, shape: AxisSpec, df: NamedOrNumeric, dtype=float): shape = ensure_tuple(shape) df = broadcast_to(df, shape) - jax_shape = _to_jax_shape(shape) + jax_shape = to_jax_shape(shape) jax_array = jrandom.t(key, df.array, jax_shape, dtype=dtype) return haliax.auto_sharded(NamedArray(jax_array, shape)) @@ -307,7 +307,7 @@ def weibull_min(key, shape: AxisSpec, scale: NamedOrNumeric, concentration: Name shape = ensure_tuple(shape) scale = broadcast_to(scale, shape) concentration = broadcast_to(concentration, shape) - jax_shape = _to_jax_shape(shape) + jax_shape = to_jax_shape(shape) jax_array = jrandom.weibull_min(key, scale.array, concentration.array, jax_shape, dtype=dtype) return haliax.auto_sharded(NamedArray(jax_array, shape)) @@ -316,7 +316,7 @@ def weibull_min(key, shape: AxisSpec, scale: NamedOrNumeric, concentration: Name def pareto(key, shape: AxisSpec, b: NamedOrNumeric, dtype=float): shape = ensure_tuple(shape) b = broadcast_to(b, shape) - jax_shape = _to_jax_shape(shape) + jax_shape = to_jax_shape(shape) jax_array = jrandom.pareto(key, b.array, jax_shape, dtype=dtype) return haliax.auto_sharded(NamedArray(jax_array, shape)) @@ -325,15 +325,11 @@ def pareto(key, shape: AxisSpec, b: NamedOrNumeric, dtype=float): def loggamma(key, shape: AxisSpec, a: NamedOrNumeric, dtype=float): shape = ensure_tuple(shape) a = broadcast_to(a, shape) - jax_shape = _to_jax_shape(shape) + jax_shape = to_jax_shape(shape) jax_array = jrandom.loggamma(key, a.array, jax_shape, dtype=dtype) return haliax.auto_sharded(NamedArray(jax_array, shape)) -def _to_jax_shape(shape): - return tuple(axis.size if isinstance(axis, Axis) else axis for axis in shape) - - __all__ = [ "generate_sharded", "uniform", commit 00f6e571ecec192a19a18c505d39cccbdfacd463 Date: 2025-03-28T16:13:49-07:00 stray print diff --git a/src/haliax/_src/scan.py b/src/haliax/_src/scan.py index f1d4dfa..7f8b0da 100644 --- a/src/haliax/_src/scan.py +++ b/src/haliax/_src/scan.py @@ -168,7 +168,6 @@ class ScanCheckpointPolicy: if self.disable: return callable elif self.simple: - print("simple") return eqx.filter_checkpoint(callable, prevent_cse=self.prevent_cse) else: policy = self._to_jax_policy(carry_name, input_name) commit df3aac7e964490ab9b16a3570a42b4edc737a40c Date: 2025-04-18T12:11:13-07:00 Add Offloading of checkpointed internals (#130) * remove stray print * add checkpoint offloading for block internals * doc comment * oops diff --git a/docs/scan.md b/docs/scan.md index 86b5494..4fe9d4f 100644 --- a/docs/scan.md +++ b/docs/scan.md @@ -289,6 +289,12 @@ which is double that required by the default policy, but it reduces the amount o Both `save_carries` and `save_inputs` can either be a boolean or the string "offload". If "offload", then the checkpointed values will be offloaded to the host during the forward pass, and reloaded during the backward pass. +In addition, you can offload block internals by passing a list of strings to `offload_block_internals`: + +``` +policy = ScanCheckpointPolicy(save_carries=True, save_block_internals=["y"], offload_block_internals=["z"]) +``` + ### Summary of String and Boolean Aliases diff --git a/src/haliax/_src/scan.py b/src/haliax/_src/scan.py index f1d4dfa..f7631d6 100644 --- a/src/haliax/_src/scan.py +++ b/src/haliax/_src/scan.py @@ -106,6 +106,13 @@ class ScanCheckpointPolicy: See Also: https://docs.jax.dev/en/latest/gradient-checkpointing.html#custom-policies-for-offload """ + + offload_block_internals: list[str] = dataclasses.field(default_factory=list) + """ + List of named block internals to offload to the host. This is useful for reducing memory usage on the device + while still avoiding rematerialization. + """ + prevent_cse: bool = False """ Whether to prevent common subexpression elimination in the checkpointed function. @@ -168,7 +175,6 @@ class ScanCheckpointPolicy: if self.disable: return callable elif self.simple: - print("simple") return eqx.filter_checkpoint(callable, prevent_cse=self.prevent_cse) else: policy = self._to_jax_policy(carry_name, input_name) @@ -202,6 +208,9 @@ class ScanCheckpointPolicy: if isinstance(self.save_block_internals, Sequence): our_names_to_save.extend(self.save_block_internals) + if self.offload_block_internals: + our_names_to_offload.extend(self.offload_block_internals) + if not our_names_to_save and not our_names_to_offload and not self.save_block_internals: return None diff --git a/tests/test_scan.py b/tests/test_scan.py index c1e7383..eb1865d 100644 --- a/tests/test_scan.py +++ b/tests/test_scan.py @@ -171,40 +171,56 @@ E = hax.Axis("E", 10) @pytest.mark.parametrize( - "name,policy,expected_scan_shapes", + "name,policy,expected_scan_shapes,check_offloading", [ - ("disabled", ScanCheckpointPolicy(disable=True), [(E.size,), (Block.size, E.size), (Block.size, E.size)]), - ("carry_true", True, [(E.size,), (Block.size, E.size)]), + ( + "disabled", + ScanCheckpointPolicy(disable=True), + [(E.size,), (Block.size, E.size), (Block.size, E.size)], + None, + ), + ("carry_true", True, [(E.size,), (Block.size, E.size)], None), ( "carry", ScanCheckpointPolicy(save_carries=True, save_block_internals=False), [(E.size,), (Block.size, E.size)], + None, ), ( "everything", ScanCheckpointPolicy(save_carries=True, save_inputs=True, save_block_internals=True), [(E.size,), (Block.size, E.size), (Block.size, E.size)], + None, ), ( "internals", ScanCheckpointPolicy(save_carries=False, save_block_internals=True), [(E.size,), (Block.size, E.size), (Block.size, E.size)], + None, ), ( "cos", ScanCheckpointPolicy(save_carries=False, save_block_internals=["cos"]), [(E.size,), (Block.size, E.size)], + None, ), ( "sin", ScanCheckpointPolicy(save_carries=True, save_block_internals=["sin"]), [(E.size,), (Block.size, E.size), (Block.size, E.size)], + None, + ), + ("simple", ScanCheckpointPolicy(simple=True), [(E.size,), (Block.size, E.size)], None), + ("nested", ScanCheckpointPolicy(simple=True, nested=2), [(E.size,), (2, E.size)], None), + ( + "sin_offload", + ScanCheckpointPolicy(save_carries=True, offload_block_internals=["sin"]), + [(E.size,), (Block.size, E.size), (Block.size, E.size)], + ["sin"], ), - ("simple", ScanCheckpointPolicy(simple=True), [(E.size,), (Block.size, E.size)]), - ("nested", ScanCheckpointPolicy(simple=True, nested=2), [(E.size,), (2, E.size)]), ], ) -def test_checkpoint_carries(name, policy, expected_scan_shapes): +def test_checkpoint_carries(name, policy, expected_scan_shapes, check_offloading): class Module(eqx.Module): named: hax.NamedArray @@ -243,3 +259,29 @@ def test_checkpoint_carries(name, policy, expected_scan_shapes): print(residual) assert out_shapes == expected_scan_shapes, f"{name}: Expected {expected_scan_shapes}, got {out_shapes}" + + # Add check for offloading if specified + if check_offloading is not None: + for name in check_offloading: + print(f"Checking offloading for {name}") + target = None + found_saved = False + for expr in jaxpr.jaxpr.eqns: + if expr.primitive.name == "scan": + inner_jaxpr = expr.params["jaxpr"] + for eqn in inner_jaxpr.eqns: + if eqn.primitive.name == "name": + this_name = eqn.params["name"] + if this_name == name: + # TODO in theory we can save more than one thing with the same name + # not gonna worry about that for now + target = eqn.outvars[0] + elif eqn.primitive.name == "device_put": + if eqn.invars[0] == target: + found_saved = True + break + # found scan + break + + assert target is not None, f"Could not find named value for {name}" + assert found_saved, f"Could not find offloaded value for {name}" commit e50adabf694c7541a6f351b9dfc2a5c999da5566 Date: 2025-04-25T15:36:29-07:00 add a check to make lora happy diff --git a/src/haliax/nn/linear.py b/src/haliax/nn/linear.py index 7c8c1ee..9b91b50 100644 --- a/src/haliax/nn/linear.py +++ b/src/haliax/nn/linear.py @@ -83,7 +83,7 @@ class Linear(ModuleWithStateDictSerialization): new_Out = hax.flatten_axes(self.Out, "__OUT__") new_In = hax.flatten_axes(self.In, "__IN__") - if weight.array is not None: + if weight is not None and weight.array is not None: out_first = self._out_first weight = weight.flatten_axes(self.Out, new_Out).flatten_axes(self.In, new_In) commit b50acde578ad0fc919d0dfee6a6f9519473cba90 Date: 2025-05-01T21:06:40-07:00 MoE support using gmm kernels (#131) * add moelinear * format * tiny fixes * fix moe tpp diff --git a/src/haliax/nn/__init__.py b/src/haliax/nn/__init__.py index 23029e2..536c5df 100644 --- a/src/haliax/nn/__init__.py +++ b/src/haliax/nn/__init__.py @@ -33,7 +33,7 @@ from .activations import ( from .conv import Conv, ConvTranspose from .dropout import Dropout, dropout from .embedding import Embedding -from .linear import Linear +from .linear import Linear, MoELinear from .loss import binary_cross_entropy_loss, cross_entropy_loss, cross_entropy_loss_and_log_normalizers, reduce_loss from .mlp import MLP from .normalization import LayerNorm, RmsNorm, log_softmax, logsumexp, softmax, standardize @@ -83,6 +83,7 @@ __all__ = [ "dropout", "LayerNorm", "Linear", + "MoELinear", "Embedding", "RmsNorm", "Stacked", diff --git a/src/haliax/nn/linear.py b/src/haliax/nn/linear.py index 9b91b50..37922bf 100644 --- a/src/haliax/nn/linear.py +++ b/src/haliax/nn/linear.py @@ -1,16 +1,22 @@ import dataclasses import math +from functools import partial from typing import Optional import equinox as eqx +import jax +import jax.numpy as jnp +from jax.experimental.pallas.ops.tpu.megablox import gmm +from jax.experimental.shard_map import shard_map from jax.random import PRNGKey import haliax as hax from .._src.state_dict import Mod, ModuleWithStateDictSerialization -from ..axis import AxisSpec +from ..axis import Axis, AxisSpec from ..core import NamedArray from ..jax_utils import named_call +from ..partitioning import ResourceAxis from ..quantization import DotGeneralOp @@ -124,3 +130,132 @@ class Linear(ModuleWithStateDictSerialization): return self.weight.axes[-1] != self.Out else: return self.weight.axes[-len(self.Out) :] != self.Out + + +class MoELinear(eqx.Module): + """A named Linear layer for MoE. This module allows you to specify multiple named axes for both input + and output, which is occasionally useful.""" + + weight: NamedArray + bias: Optional[NamedArray] + + Experts: AxisSpec = eqx.static_field() + In: Axis = eqx.static_field() + Out: Axis = eqx.static_field() + dot_general: DotGeneralOp = eqx.field(default_factory=DotGeneralOp.default) + + @staticmethod + def init( + Experts: Axis, + In: Axis, + Out: Axis, + *, + key: PRNGKey, + use_bias: bool = True, + out_first: bool = False, + init_scale: float = 1.0, + ) -> "MoELinear": + """ + Args: + Experts: Axis: The expert axis + In: Axis: The input axis + Out: Axis: The output axis + key: PRNGKeyArray: The PRNG key to use for initialization + use_bias: bool: Whether to use a bias term + out_first: bool: Whether to put output axes first in the weight matrix. out_first is how PyTorch does it. + dot_general: Callable: The dot_general function to use. Defaults to jax.lax.dot_general. For fp8 or int8 + init_scale: float: The scale to use for initialization. We scale init by 1/sqrt(Input.size)*init_scale + """ + joint_spec = hax.concat_axis_specs(Out, In) if out_first else hax.concat_axis_specs(In, Out) + joint_spec = hax.concat_axis_specs(Experts, joint_spec) + input_size = hax.axis_size(In) + weight = hax.random.truncated_normal(key, joint_spec, -3, 3) * (init_scale / math.sqrt(input_size)) + bias = hax.zeros(Out) if use_bias else None + + return MoELinear(weight, bias, Experts, In, Out) + + @named_call + def __call__(self, inputs, group_sizes, *, key: Optional[PRNGKey] = None): + """ + Args: + inputs (NamedArray): Input array (Batch, In) + group_sizes (NamedArray): MoE expert sizes (Experts) + key: Not used, but there for compat with other modules + """ + del key + + inputs = inputs.rearrange((..., self.In)) + out_axes = hax.replace_axis(inputs.axes, self.In, self.Out) + + q = _gmm( + inputs, + self.weight, + group_sizes, + out_axes, + ar=hax.partitioning.physical_axis_name(self.In) == ResourceAxis.MODEL, + ) # gmm((B, D), (E, D, d)) -> (B, d) + q = hax.auto_sharded(q) + + if self.bias is not None: + q = q + self.bias + q = hax.auto_sharded(q) + + return q + + @property + def out_first(self): + """ + Returns: bool: Whether the output axes are first in the weight matrix + """ + # We do it this way because of scan layers + if isinstance(self.Out, hax.Axis): + return self.weight.axes[-1] != self.Out + else: + return self.weight.axes[-len(self.Out) :] != self.Out + + +def _gmm(lhs, rhs, group_sizes, out_axes, sharded=False, ar=False): + if sharded: + gmm_fn = gmm_sharded + else: + gmm_fn = shard_map( + partial(gmm_sharded, ar=ar), + mesh=hax.partitioning._get_mesh(), + in_specs=( + hax.partitioning.pspec_for_axis(lhs.axes), + hax.partitioning.pspec_for_axis(rhs.axes), + hax.partitioning.pspec_for_axis(group_sizes.axes), + ), + out_specs=hax.partitioning.pspec_for_axis(out_axes), + check_rep=False, + ) + + out = gmm_fn(lhs.array, rhs.array, group_sizes.array) + + return hax.NamedArray(out, axes=out_axes) + + +def gmm_sharded(lhs_: jnp.ndarray, rhs_: jnp.ndarray, group_sizes_: jnp.ndarray, ar: bool = False) -> jnp.ndarray: + hs_shape = lhs_.shape + if hs_shape[0] % 512: + pad_length = 512 - hs_shape[0] % 512 + lhs_ = jax.lax.pad(lhs_, 0.0, [(0, pad_length, 0), (0, 0, 0)]) + + tile_size = (512, 1024, 1024) # (m, k, n) + m, k, n = lhs_.shape[0], lhs_.shape[1], rhs_.shape[2] + out = gmm( + lhs_, + rhs_, + group_sizes_, + preferred_element_type=lhs_.dtype, + tiling=(min(m, tile_size[0]), min(k, tile_size[1]), min(n, tile_size[2])), + interpret=True, + ) + + if ar: + out = jax.lax.psum(out, ResourceAxis.MODEL) + + if hs_shape[0] % 512: + out = out[: hs_shape[0]] + + return out commit af29b9e5ed08056250300df7bc1e908e9a1ba8de Date: 2025-05-01T23:39:19-07:00 disable gmm interpret mode (#132) diff --git a/src/haliax/nn/linear.py b/src/haliax/nn/linear.py index 37922bf..8f308e8 100644 --- a/src/haliax/nn/linear.py +++ b/src/haliax/nn/linear.py @@ -249,7 +249,7 @@ def gmm_sharded(lhs_: jnp.ndarray, rhs_: jnp.ndarray, group_sizes_: jnp.ndarray, group_sizes_, preferred_element_type=lhs_.dtype, tiling=(min(m, tile_size[0]), min(k, tile_size[1]), min(n, tile_size[2])), - interpret=True, + # interpret=True, ) if ar: commit 58e65e587f704413d196aba07adf4ab1aee20949 Date: 2025-06-16T10:24:08-07:00 Merge remote-tracking branch 'origin/main' into main2 commit cfbf1d8c701306cef1aac9f5dbf4cb223bf078bf Date: 2025-06-17T21:31:23-07:00 state_dict: if template is None stay with none diff --git a/src/haliax/_src/state_dict.py b/src/haliax/_src/state_dict.py index 576a256..11ec001 100644 --- a/src/haliax/_src/state_dict.py +++ b/src/haliax/_src/state_dict.py @@ -215,6 +215,8 @@ def from_state_dict(tree: T, state_dict: StateDict, prefix: Optional[str] = None raise ValueError("Cannot extract a leaf value from a state dict without a prefix") # TODO: add "strict" flag so we can return None in cases where it's just missing return jnp.array(state_dict[prefix]) + elif tree is None: + return None else: if prefix is None: return tree diff --git a/tests/test_state_dict.py b/tests/test_state_dict.py index ed3e888..2dda82a 100644 --- a/tests/test_state_dict.py +++ b/tests/test_state_dict.py @@ -175,3 +175,27 @@ def test_stacked_layer_norm(): new_norms = unflatten_modules_from_export(norms_flat, norms2) assert norms == new_norms + + +def test_linear_doesnt_read_bias_if_it_didnt_have_bias(): + H = hax.Axis("H", 10) + W = hax.Axis("W", 20) + D = hax.Axis("D", 30) + B = hax.Axis("B", 40) + + linear = hax.nn.Linear.init((H, W), (D, B), key=jax.random.PRNGKey(0), use_bias=False, out_first=True) + + flat_linear = linear.flatten_for_export() + + flat_state_dict = to_state_dict(flat_linear) + + assert "bias" not in flat_state_dict + flat_state_dict["bias"] = jnp.zeros((D.size * B.size,)) # add a dummy bias + + # now unflatten it + linear2 = Linear.init((H, W), (D, B), key=jax.random.PRNGKey(1), use_bias=False, out_first=True) + flinear2 = linear2.flatten_for_export() + flinear2 = from_state_dict(flinear2, flat_state_dict) + new_linear = flinear2.unflatten_from_export(linear2) + + assert linear == new_linear commit 6d816d19dc3155f9dabbc9d7df62b3030c003378 Date: 2025-06-20T14:55:42-07:00 Add scatter/gather support (#133) diff --git a/src/haliax/core.py b/src/haliax/core.py index e8acf19..442ded3 100644 --- a/src/haliax/core.py +++ b/src/haliax/core.py @@ -931,6 +931,7 @@ def _compute_new_axes_and_slices_for_index( ordered_slices: list = [py_slice(None, None, None)] * len(array.axes) # type: ignore kept_axes = [True] * len(array.axes) array_slice_indices = [] + index_axis_names = set() for axis, slice_ in slices.items(): axis_index = array._lookup_indices(axis) @@ -946,6 +947,8 @@ def _compute_new_axes_and_slices_for_index( ordered_slices[axis_index] = slice_ array_slice_indices.append(axis_index) kept_axes[axis_index] = False + for ax in slice_.axes: + index_axis_names.add(ax.name) elif isinstance(slice_, list): # we'll let JAX complain if this is wrong ordered_slices[axis_index] = slice_ @@ -955,10 +958,17 @@ def _compute_new_axes_and_slices_for_index( ordered_slices[axis_index] = slice_ kept_axes[axis_index] = False elif slice_.ndim == 1: - # we allow this if it's a 1-d array, in which case we treat it as sugar for NamedArray(slice_, sliced-axis) - ordered_slices[axis_index] = haliax.named(slice_, axis_name(axis)) + target_axis = None + for i2, ax2 in enumerate(array.axes): + if i2 != axis_index and kept_axes[i2] and ax2.size == slice_.shape[0]: + target_axis = ax2 + break + if target_axis is None: + target_axis = axis + ordered_slices[axis_index] = haliax.named(slice_, axis_name(target_axis)) kept_axes[axis_index] = False array_slice_indices.append(axis_index) + index_axis_names.add(axis_name(target_axis)) else: raise ValueError( f"Only 0-d or 1-d unnamed arrays can be used for indexing. Got {slice_} for axis {axis}" @@ -966,6 +976,14 @@ def _compute_new_axes_and_slices_for_index( else: raise ValueError(f"Only NamedArrays can be used for advanced indexing. Got {slice_} for axis {axis}") + # If any index array uses axes that are already present in the array and not removed, + # we need to explicitly advance-index those axes so numpy broadcasting works. + for i, ax in enumerate(array.axes): + if kept_axes[i] and ax.name in index_axis_names: + ordered_slices[i] = haliax.arange(ax) + array_slice_indices.append(i) + kept_axes[i] = False + # advanced indexing if len(array_slice_indices) > 0: # this requires broadcasting diff --git a/tests/test_scatter_gather.py b/tests/test_scatter_gather.py new file mode 100644 index 0000000..18793b7 --- /dev/null +++ b/tests/test_scatter_gather.py @@ -0,0 +1,165 @@ +import jax +import jax.numpy as jnp + +import haliax as hax +from haliax import Axis, dslice + + +# ----------------------------------------------------------------------------- +# Helper for reference via take_along_axis +# ----------------------------------------------------------------------------- + + +def _ref_gather(src, axis, idx): + ax_num = src.axes.index(axis) + # broadcast idx to match src without the gathered axis + other_axes = tuple(ax for ax in src.axes if ax != axis) + broadcast_axes = other_axes + for ax in idx.axes: + if ax not in broadcast_axes: + broadcast_axes += (ax,) + idx_b = hax.broadcast_to(idx, broadcast_axes, enforce_no_extra_axes=False) + if idx_b.array.ndim == src.array.ndim - 1: + idx_arr = idx_b.array[..., None] + else: + idx_arr = idx_b.array + out = jnp.take_along_axis(src.array, idx_arr, axis=ax_num) + if idx_b.array.ndim == src.array.ndim - 1: + out = out.squeeze(ax_num) + return out + + +# ---------------------------- 1. single batched selector ---------------------- + + +def test_single_batched_selector(): + B, S, V = Axis("batch", 4), Axis("seq", 3), Axis("vocab", 7) + x = hax.arange((B, S, V)) + idx = hax.arange((B, S), dtype=jnp.int32) % V.size + out = x["vocab", idx] + assert out.axes == (B, S) + assert jnp.array_equal(out.array, _ref_gather(x, V, idx)) + + +# ---------------------------- 2. selector adds new axis ----------------------- + + +def test_selector_adds_new_axis(): + B, S, V, T = Axis("batch", 2), Axis("seq", 3), Axis("vocab", 5), Axis("step", 4) + logits = hax.arange((B, S, V)) + idx = hax.arange((B, T), dtype=jnp.int32) % V.size + out = logits["vocab", idx] + assert set(out.axes) == {B, S, T} + ref = jnp.transpose(_ref_gather(logits, V, idx), (0, 2, 1)) + assert jnp.array_equal(out.array, ref) + + +# ------------------------ 3. two contiguous selector arrays ------------------- + + +def test_two_contiguous_selectors(): + B, X, Y = Axis("batch", 3), Axis("x", 5), Axis("y", 7) + a = hax.arange((B, X, Y)) + ix = hax.arange((B,), dtype=jnp.int32) % X.size + iy = hax.arange((B,), dtype=jnp.int32) % Y.size + out = a["x", ix, "y", iy] + assert out.axes == (B,) + ref = a.array[jnp.arange(3), ix.array, iy.array] + assert jnp.array_equal(out.array, ref) + + +# ------------------ 4. non-contiguous selectors → axes to front -------------- + + +def test_noncontig_selectors(): + B, X, Z, Y = Axis("batch", 2), Axis("x", 4), Axis("z", 6), Axis("y", 5) + a = hax.arange((B, X, Z, Y)) + ix = hax.arange((B,), dtype=jnp.int32) % X.size + iy = hax.arange((B,), dtype=jnp.int32) % Y.size + out = a["x", ix, "y", iy] + assert out.axes == (B, Z) + ref = a.array[jnp.arange(2), ix.array, :, iy.array] + assert jnp.array_equal(out.array, ref) + + +# ----------------- 5. integer elimination + selector -------------------------- + + +def test_mixed_int_and_selector(): + B, C, V = Axis("batch", 3), Axis("channel", 2), Axis("vocab", 6) + x = hax.arange((B, C, V)) + idx = hax.arange((B,), dtype=jnp.int32) % V.size + out = x["channel", 1, "vocab", idx] + assert out.axes == (B,) + ref = x.array[:, 1, :][jnp.arange(3), idx.array] + assert jnp.array_equal(out.array, ref) + + +def test_dslice_with_selector(): + B, S, V = Axis("batch", 2), Axis("seq", 5), Axis("vocab", 10) + x = hax.arange((B, S, V)) + idx = (hax.arange((B, S), dtype=jnp.int32) + 2) % 4 + shard = V.resize(4) + x_shard = x["vocab", dslice(0, shard)] + out = x_shard["vocab", idx] + assert out.axes == (B, S) + ref = x.array[:, :, :4][jnp.arange(B.size)[:, None], jnp.arange(S.size)[None, :], idx.array] + assert jnp.array_equal(out.array, ref) + + +def test_scalar_eliminates_axis(): + B, S, V = Axis("batch", 2), Axis("seq", 3), Axis("vocab", 4) + x = hax.arange((B, S, V)) + out = x["seq", 1] + assert out.axes == (B, V) + assert jnp.array_equal(out.array, x.array[:, 1, :]) + + +# ----------------- 9. plain ndarray selector sugar ---------------------------- + + +def test_plain_ndarray_selector(): + B, V = Axis("batch", 3), Axis("vocab", 5) + x = hax.arange((B, V)) + idx = jnp.array([0, 2, 4], dtype=jnp.int32) + out = x["vocab", idx] + assert out.axes == (B,) + assert jnp.array_equal(out.array, x.array[jnp.arange(3), idx]) + + +# ----------------- 10. two selectors needing broadcast ------------------------ + + +def test_multiselector_broadcast(): + B, S, V = Axis("batch", 2), Axis("seq", 3), Axis("vocab", 6) + a = hax.arange((B, S, V)) + idx1 = hax.arange((B, S), dtype=jnp.int32) % V.size + out = a["vocab", idx1] + assert out.axes == (B, S) + assert jnp.array_equal(out.array, _ref_gather(a, V, idx1)) + + +# ----------------- 11. scatter-ADD via .at[…].add ----------------------------- + + +def test_scatter_add(): + B, S, V = Axis("batch", 2), Axis("seq", 3), Axis("vocab", 5) + x = hax.zeros((B, S, V)) + idx = hax.arange((B, S), dtype=jnp.int32) % V.size + ones = hax.ones((B, S)) + y = x.at[{V: idx}].add(ones) + ref = jnp.zeros((2, 3, 5)).at[jnp.arange(2)[:, None], jnp.arange(3)[None, :], idx.array].add(1.0) + assert jnp.array_equal(y.array, ref) + + +# ----------------- 12. scatter-SET via .at[…].set ----------------------------- + + +def test_scatter_set(): + B, V = Axis("batch", 2), Axis("vocab", 6) + x = hax.zeros((B, V)) + idx = hax.named(jnp.array([1, 4]), B) + val = hax.ones(B) * 9 + y = x.at[{V: idx}].set(val) + ref = jnp.zeros((2, 6)).at[jnp.arange(2), idx.array].set(9) + assert jnp.array_equal(y.array, ref) commit 39502bb6823d65c925371021af17da33628dcdc3 Date: 2025-06-20T23:15:01-07:00 Scatter slice update (#135) * add scatter slice update * slice scatter update diff --git a/src/haliax/core.py b/src/haliax/core.py index 442ded3..e03ae61 100644 --- a/src/haliax/core.py +++ b/src/haliax/core.py @@ -1,7 +1,6 @@ import contextlib import functools as ft import typing -import warnings from dataclasses import dataclass from math import prod from types import EllipsisType @@ -324,7 +323,9 @@ class NamedArray: def slice(self, *args, **kwargs) -> "NamedArray": return haliax.slice(self, *args, **kwargs) - def updated_slice(self, start: Mapping[AxisSelector, int], update: "NamedArray") -> "NamedArray": + def updated_slice( + self, start: Mapping[AxisSelector, Union[int, "NamedArray"]], update: "NamedArray" + ) -> "NamedArray": return haliax.updated_slice(self, start=start, update=update) def take(self, axis: AxisSelector, index: Union[int, "NamedArray"]) -> "NamedArray": @@ -854,7 +855,7 @@ def _slice_new( def updated_slice( - array: NamedArray, start: Mapping[AxisSelector, Union[int, jnp.ndarray]], update: NamedArray + array: NamedArray, start: Mapping[AxisSelector, Union[int, jnp.ndarray, NamedArray]], update: NamedArray ) -> NamedArray: """ Updates a slice of an array with another array. @@ -868,18 +869,42 @@ def updated_slice( NamedArray: The updated array. """ + # figure out which axis‐names to map over + map_axes: list[str] = [] + for axis_sel, s in start.items(): + if isinstance(s, NamedArray): + for ax in s.axes: + if ax.name not in map_axes: + map_axes.append(ax.name) + + # need to vmap + if len(map_axes) > 0: + # scalar version: all starts are ints / tracers + f = updated_slice + for axis_name in map_axes: + # make sure that axis_name is in `array`. otherwise it doesn't make sense to vmap over it + if array._lookup_indices(axis_name) is None: + raise ValueError(f"axis {axis_name} not found in original array's axes: {array.shape}") + f = haliax.vmap(f, axis=axis_name) + return f(array, start, update) + array_slice_indices = [0] * len(array.axes) for axis, s in start.items(): - axis_index = array._lookup_indices(axis_name(axis)) + axis_index = array._lookup_indices(haliax.axis_name(axis)) if axis_index is None: raise ValueError(f"axis {axis} not found in {array}") + if isinstance(s, NamedArray): # this can happen in the vmap case + if s.ndim != 0: + raise ValueError(f"NamedArray {s} must be a scalar for axis {axis} in updated_slice") + s = s.scalar() + array_slice_indices[axis_index] = s total_length = array.axes[axis_index].size - update_axis = update._lookup_indices(axis_name(axis)) + update_axis = update._lookup_indices(haliax.axis_name(axis)) - if update_axis is None: - raise ValueError(f"axis {axis} not found in {update}") # if s is a tracer we can't check the size + if update_axis is None: + continue if isinstance(s, int) and update.axes[update_axis].size + s > total_length: raise ValueError( f"update axis {axis} is too large to start at {s}. Array size is {total_length}, update size is" @@ -888,17 +913,25 @@ def updated_slice( # broadcasting here is a bit delicate because the sizes aren't necessarily the same # we need to broadcast the update array to the same axis names as the array we're updating, adding them as necessary - broadcasted_axes = [] - for axis in array.axes: - update_axis = update._lookup_indices(axis.name) - if update_axis is None: - broadcasted_axes.append(axis) - else: - broadcasted_axes.append(update.axes[update_axis]) - - update = haliax.broadcast_to(update, broadcasted_axes, enforce_no_extra_axes=True) + if update.ndim > 0: + # if there are any axes in update that are not in array, it is an error: + axes_in_update = haliax.axis.without_axes(update.axes, array.axes) + if axes_in_update: + raise ValueError( + f"Update array with shape {update.shape} has axes {axes_in_update} that are not in the original array" + f" with shape {array.shape}. This is not allowed in updated_slice." + ) + broadcasted_axes = [] + for ax in array.axes: + upd_ax = update._lookup_indices(ax.name) + broadcasted_axes.append(ax if upd_ax is None else update.axes[upd_ax]) + update = haliax.broadcast_to(update, broadcasted_axes, enforce_no_extra_axes=True) + upd_arr = update.array + else: + # scalar case: just add one axis so it doesn't get too mad + upd_arr = update.array.reshape((1,)) - updated = jax.lax.dynamic_update_slice(array.array, update.array, array_slice_indices) + updated = jax.lax.dynamic_update_slice(array.array, upd_arr, array_slice_indices) return NamedArray(updated, array.axes) diff --git a/tests/core_test.py b/tests/core_test.py index 58f52ea..4cc683a 100644 --- a/tests/core_test.py +++ b/tests/core_test.py @@ -1,11 +1,8 @@ -import equinox as eqx import jax import jax.numpy as jnp -import pytest from jax.random import PRNGKey -import haliax as hax -from haliax import Axis, NamedArray +from haliax import Axis, NamedArray, updated_slice def test_unary_np_functions(): @@ -603,3 +600,90 @@ def test_slice_nd_array_present_dims(): assert jnp.all(jnp.equal(named1[{"H": index1}].array, named1.array[index1.array, :, :])) # this is not ok, since the H would not be eliminated + + +import numpy as np +import pytest + +import haliax as hax + + +def test_scalar_updated_slice(): + # Base case: scalar start on a 1D array + Seq = hax.Axis("seq", 5) + arr = hax.arange((Seq,), dtype=int) + # replace positions 2 and 3 with [100, 101] + upd = hax.named([100, 101], "seq") + + result = updated_slice(arr, {"seq": 2}, upd) + # expect [0,1,100,101,4] + assert np.array_equal(result.array, np.array([0, 1, 100, 101, 4])) + + +def test_ragged_single_token(): + # Ragged case: one token per batch at different positions + Batch = hax.Axis("batch", 3) + Seq = hax.Axis("seq", 5) + cache = hax.zeros((Batch, Seq), dtype=int) + + # lengths[b] is next free slot for batch b + lengths = hax.named([0, 1, 2], axis=Batch) + new_k = hax.named([7, 8, 9], axis=Batch) + + result = updated_slice(cache, {"seq": lengths}, new_k) + + # build expected NumPy array + exp = np.zeros((3, 5), int) + exp[0, 0] = 7 + exp[1, 1] = 8 + exp[2, 2] = 9 + + assert np.array_equal(result.array, exp) + + +def test_ragged_multi_token(): + # Ragged case: a block of 2 tokens per batch at different positions + Batch = hax.Axis("batch", 2) + Seq = hax.Axis("seq", 5) + New = hax.Axis("seq", 2) + + cache = hax.zeros((Batch, Seq), dtype=int) + lengths = hax.named([1, 3], axis=Batch) + # for batch=0 insert [1,2] at pos=1, for batch=1 insert [3,4] at pos=3 + kv = hax.named([[1, 2], [3, 4]], axis=(Batch, New)) + + result = updated_slice(cache, {"seq": lengths}, kv) + + exp = np.zeros((2, 5), int) + exp[0, 1] = 1 + exp[0, 2] = 2 + exp[1, 3] = 3 + exp[1, 4] = 4 + + assert np.array_equal(result.array, exp) + + +def test_ragged_multi_token_bad_axis_name(): + # Ragged case: a block of 2 tokens per batch at different positions + Batch = hax.Axis("batch", 2) + Seq = hax.Axis("seq", 5) + New = hax.Axis("new", 2) + + cache = hax.zeros((Batch, Seq), dtype=int) + lengths = hax.named([1, 3], axis=Batch) + # for batch=0 insert [1,2] at pos=1, for batch=1 insert [3,4] at pos=3 + kv = hax.named([[1, 2], [3, 4]], axis=(Batch, New)) + + with pytest.raises(ValueError, match="that are not in the original array with shape "): + updated_slice(cache, {"seq": lengths}, kv) + + +def test_update_overflow_error(): + # Overflow: scalar start + update too large for axis → ValueError + Seq = hax.Axis("seq", 4) + arr = hax.zeros((Seq,), dtype=int) + # update of length 3 starting at pos=2 would run off the end (2+3 > 4) + upd = hax.arange((hax.Axis("seq", 3),), dtype=int) + + with pytest.raises(ValueError): + updated_slice(arr, {"seq": 2}, upd) commit 58005be8267dcde4b7d4e8f1b55370f654907568 Date: 2025-06-21T23:35:25-07:00 Add multi-axis support to vmap (#134) * feat: support multi-axis vmap * pre-commit diff --git a/src/haliax/hof.py b/src/haliax/hof.py index 87eb90f..472aba5 100644 --- a/src/haliax/hof.py +++ b/src/haliax/hof.py @@ -19,16 +19,16 @@ from ._src.scan import ( map, scan, ) -from .axis import Axis, AxisSelector, selects_axis +from .axis import Axis, AxisSelection, AxisSelector, selects_axis from .core import NamedArray from .jax_utils import Static, broadcast_prefix, is_jax_array_like from .partitioning import physical_axis_name -from .util import is_named_array +from .util import ensure_tuple, is_named_array def vmap( fn, - axis: AxisSelector, + axis: AxisSelection, *, default: PyTree[UnnamedAxisSpec] = _zero_if_array_else_none, args: PyTree[UnnamedAxisSpec] = (), @@ -43,7 +43,9 @@ def vmap( Args: fn (Callable): function to vmap over - axis (Axis): axis to vmap over + axis (Axis or Sequence[Axis]): axis or axes to vmap over. If a sequence is + provided, the function will be vmapped over each axis in turn, + from innermost to outermost. default: how to handle (unnamed) arrays by default. Should be either an integer or None, or a callable that takes a PyTree leaf and returns an integer or None, or a PyTree prefix of the same. If an integer, the array will be mapped over that axis. If None, the array will not be mapped over. args: optional per-argument overrides for how to handle arrays. Should be a PyTree prefix of the same type as default. @@ -53,6 +55,15 @@ def vmap( if kwargs is None: kwargs = {} + axes = ensure_tuple(axis) # type: ignore + if len(axes) > 1: + mapped = fn + for ax in reversed(axes): + mapped = vmap(mapped, ax, default=default, args=args, kwargs=kwargs) + return mapped + else: + axis = axes[0] + signature = inspect.signature(fn) # this mirrors equinox's filter_vmap, but it's not really documented there so: diff --git a/tests/test_hof.py b/tests/test_hof.py index ad80303..840bce5 100644 --- a/tests/test_hof.py +++ b/tests/test_hof.py @@ -321,3 +321,22 @@ def test_vmap_error_for_incorrectly_specified_args(): Width = Axis("Width", 3) hax.vmap(lambda a: Module(a), Batch)(Width) + + +def test_vmap_multiple_axes(): + Batch1 = Axis("Batch1", 4) + Batch2 = Axis("Batch2", 3) + Width = Axis("Width", 2) + Depth = Axis("Depth", 5) + + named = hax.random.uniform(PRNGKey(0), (Batch1, Batch2, Width, Depth)) + + def vmap_fun(x): + return x.sum(Width) + + selected = hax.vmap(vmap_fun, (Batch1, Batch2))(named) + + expected = jnp.sum(named.array, axis=2) + + assert jnp.allclose(selected.array, expected) + assert selected.axes == (Batch1, Batch2, Depth) commit 4e87303b93bb7a9fc17def01b19ab447c71465bb Date: 2025-06-24T00:51:37-07:00 docs: document scatter gather (#136) diff --git a/docs/indexing.md b/docs/indexing.md index e4f839d..bde3839 100644 --- a/docs/indexing.md +++ b/docs/indexing.md @@ -287,3 +287,42 @@ operation more effectively.) It's worth emphasizing that these functions are typically compiled to scatter-add and friends (as appropriate). This is the preferred way to do scatter/gather operations in JAX, as well as in Haliax. + +## Scatter/Gather + +Haliax supports scatter/gather semantics in its indexing operations. When an axis +is indexed by another NamedArray (or a 1-D JAX array), the values of that axis +are gathered according to the index array and the axes of the indexer are +inserted into the result. + +```python +import haliax as hax +import jax.numpy as jnp + +B, S, V = Axis("batch", 4), Axis("seq", 3), Axis("vocab", 7) +x = hax.arange((B, S, V)) +idx = hax.arange((B, S), dtype=jnp.int32) % V.size + +out = x["vocab", idx] +``` + +Here `out` has axes `(B, S)` and its values match `jax.numpy.take_along_axis` +on the underlying ndarray. + +For scatter-style updates where each batch writes to a different position, use +[`updated_slice`][haliax.updated_slice]: + +```python +Batch = hax.Axis("batch", 2) +Seq = hax.Axis("seq", 5) +New = hax.Axis("seq", 2) + +cache = hax.zeros((Batch, Seq), dtype=int) +lengths = hax.named([1, 3], axis=Batch) +kv = hax.named([[1, 2], [3, 4]], axis=(Batch, New)) + +result = updated_slice(cache, {"seq": lengths}, kv) +``` + +This inserts `[1, 2]` starting at position `1` in batch `0` and `[3, 4]` starting +at position `3` in batch `1`. commit 1baeac7f18a6d253f1a508baaeb6f8e0c8fb2fc7 Date: 2025-06-24T22:13:24-05:00 relu squared for sparse activations -- allows for inference speedup (#140) * relu squared for sparse activations -- allows for inference speedup * remove graidnet test diff --git a/src/haliax/nn/__init__.py b/src/haliax/nn/__init__.py index 536c5df..4ea2738 100644 --- a/src/haliax/nn/__init__.py +++ b/src/haliax/nn/__init__.py @@ -23,6 +23,7 @@ from .activations import ( quick_gelu, relu, relu6, + relu_squared, selu, sigmoid, silu, @@ -94,6 +95,7 @@ __all__ = [ "quick_gelu", "glu", "relu6", + "relu_squared", "sigmoid", "soft_sign", "softplus", diff --git a/src/haliax/nn/activations.py b/src/haliax/nn/activations.py index 2cb2ec1..ae9a80d 100644 --- a/src/haliax/nn/activations.py +++ b/src/haliax/nn/activations.py @@ -87,3 +87,13 @@ def glu(x: NamedArray, axis: Axis) -> NamedArray: def quick_gelu(x): return x * sigmoid(1.702 * x) + + + +def relu_squared(x: A) -> A: + """ReLU squared activation function. jnp.square(jnp.maximum(0, x))""" + + def _fn(a): + return jnp.square(jnn.relu(a)) + + return typing.cast(A, wrap_elemwise_unary(_fn, x)) diff --git a/tests/test_nn.py b/tests/test_nn.py index 08809b7..634736d 100644 --- a/tests/test_nn.py +++ b/tests/test_nn.py @@ -147,3 +147,55 @@ def test_linear_has_no_function_leaves_by_default(): hax_linear = hax.nn.Linear.init((H, C, W), E, key=jrandom.PRNGKey(0)) assert all(not isinstance(v, Callable) for v in jax.tree_util.tree_leaves(hax_linear)) # type: ignore + + +@pytest.mark.parametrize( + "input_data, axes", + [ + (jnp.array([-2.0, -1.0, 0.0, 1.0, 2.0]), (hax.Axis("X", 5),)), + (jnp.array([[1.0, -1.0], [0.0, 2.0]]), (hax.Axis("Y", 2), hax.Axis("Z", 2))), + (jnp.array([jnp.nan, 1.0, -1.0]), (hax.Axis("A", 3),)), + (jnp.array([jnp.inf, -jnp.inf, 0.0]), (hax.Axis("B", 3),)), + ], +) +@pytest.mark.parametrize("dtype", [jnp.float16, jnp.float32, jnp.bfloat16]) +@pytest.mark.parametrize("use_jit", [False, True]) +def test_relu_squared_robust(input_data, axes, dtype, use_jit): + input_data = input_data.astype(dtype) + x = hax.named(input_data, axes) + + # Manually compute the expected output using the base JAX functions + expected_raw = jnp.square(jax.nn.relu(input_data)) + expected = hax.named(expected_raw, axes) + + f = hax.nn.relu_squared + if use_jit: + f = hax.named_jit(f) + + # Apply the relu_squared function + actual = f(x) + + # Check that the output is a NamedArray with the correct axes and dtype + assert isinstance(actual, hax.NamedArray) + assert actual.axes == expected.axes + assert actual.dtype == expected.dtype + + # Check that the values are correct, handling NaNs correctly + assert jnp.allclose(actual.array, expected.array, equal_nan=True) + + +@pytest.mark.parametrize("use_jit", [False, True]) +def test_relu_squared_scalar(use_jit): + f = hax.nn.relu_squared + if use_jit: + f = jax.jit(f) + + x = 5.0 + expected = 25.0 + actual = f(x) + assert jnp.allclose(actual, expected) + + x_neg = -5.0 + expected_neg = 0.0 + actual_neg = f(x_neg) + assert jnp.allclose(actual_neg, expected_neg) \ No newline at end of file commit 16c26feb40445e8eff6e6e04117623fbf8b0d5cc Date: 2025-06-24T00:50:52-07:00 tweaks/bugfixes diff --git a/src/haliax/hof.py b/src/haliax/hof.py index 472aba5..7babdd0 100644 --- a/src/haliax/hof.py +++ b/src/haliax/hof.py @@ -61,8 +61,10 @@ def vmap( for ax in reversed(axes): mapped = vmap(mapped, ax, default=default, args=args, kwargs=kwargs) return mapped - else: + elif len(axis) == 1: # type: ignore axis = axes[0] + else: + return fn signature = inspect.signature(fn) diff --git a/src/haliax/nn/attention.py b/src/haliax/nn/attention.py index c105b7c..bb448ce 100644 --- a/src/haliax/nn/attention.py +++ b/src/haliax/nn/attention.py @@ -111,7 +111,7 @@ def dot_product_attention( KPos = ensure_tuple(key.resolve_axis(KPos)) # any axis in KPos that's in query is a problem for axis in KPos: - if axis in query.axes: + if query.has_axis(axis): raise ValueError( f"Axis {axis} in KPos is also in query. Attended-to axes must be distinct from query axis" ) commit fa5c109ec79567398d808bbf7d4e89f6b1f28638 Date: 2025-06-24T16:11:16-07:00 oops diff --git a/src/haliax/hof.py b/src/haliax/hof.py index 7babdd0..ddd624e 100644 --- a/src/haliax/hof.py +++ b/src/haliax/hof.py @@ -61,7 +61,7 @@ def vmap( for ax in reversed(axes): mapped = vmap(mapped, ax, default=default, args=args, kwargs=kwargs) return mapped - elif len(axis) == 1: # type: ignore + elif len(axes) == 1: # type: ignore axis = axes[0] else: return fn commit 87995637d13d38a46a18d89f64525804014a520a Date: 2025-06-24T23:52:31-07:00 rename _lookup_indices to axis_indices diff --git a/src/haliax/__init__.py b/src/haliax/__init__.py index ca1d0ec..6c45a8f 100644 --- a/src/haliax/__init__.py +++ b/src/haliax/__init__.py @@ -212,7 +212,7 @@ def repeat( a: NamedArray, repeats: int | jnp.ndarray, axis: AxisSelector, total_repeat_length: Optional[int] = None ) -> NamedArray: """Version of [jax.numpy.repeat][] that returns a NamedArray""" - index = a._lookup_indices(axis) + index = a.axis_indices(axis) if index is None: raise ValueError(f"Axis {axis} not found in array {a}") @@ -235,7 +235,7 @@ def tile(a: NamedArray, reps: dict[AxisSelector, int]) -> NamedArray: new_dims = [] dim_reps = [1] * len(a.axes) for ax, i in reps.items(): - index = a._lookup_indices(ax) + index = a.axis_indices(ax) if index is None: new_dims.append(Axis(axis_name(ax), i)) else: @@ -265,7 +265,7 @@ def concatenate(axis: AxisSelector, arrays: Sequence[NamedArray]) -> NamedArray: if len(arrays) == 0: return zeros(axis) - axis_index = arrays[0]._lookup_indices(aname) + axis_index = arrays[0].axis_indices(aname) if axis_index is None: raise ValueError(f"Axis {aname} not found in 0th array {arrays[0]}") diff --git a/src/haliax/core.py b/src/haliax/core.py index e03ae61..51c34a6 100644 --- a/src/haliax/core.py +++ b/src/haliax/core.py @@ -1,6 +1,7 @@ import contextlib import functools as ft import typing +import warnings from dataclasses import dataclass from math import prod from types import EllipsisType @@ -142,7 +143,7 @@ class NamedArray: def has_axis(self, axis: AxisSelection) -> bool: """Returns true if the given axis is present in this NamedArray.""" - return self._lookup_indices(axis) is not None + return self.axis_indices(axis) is not None @overload def axis_size(self, axis: AxisSelector) -> int: # type: ignore @@ -156,7 +157,7 @@ class NamedArray: """ Returns the size of the given axis, or a tuple of sizes if given multiple axes. """ - indices = self._lookup_indices(axis) + indices = self.axis_indices(axis) if isinstance(indices, int): return self.axes[indices].size elif indices is None: @@ -184,7 +185,7 @@ class NamedArray: Raises a ValueError if any of the axes are not found. """ - indices = self._lookup_indices(axes) + indices = self.axis_indices(axes) if isinstance(indices, int): return self.axes[indices] elif indices is None: @@ -235,6 +236,27 @@ class NamedArray: For a single axis, returns an int corresponding to the index of the axis. For multiple axes, returns a tuple of ints corresponding to the indices of the axes. + If the axis is not present, returns None for that position + """ + warnings.warn( + "_lookup_indices() is deprecated, use axis_indices() instead", + DeprecationWarning, + ) + return self.axis_indices(axis) + + @overload + def axis_indices(self, axis: AxisSelector) -> Optional[int]: # type: ignore + ... + + @overload + def axis_indices(self, axis: Sequence[AxisSelector]) -> Tuple[Optional[int], ...]: + ... + + def axis_indices(self, axis: AxisSelection) -> Union[Optional[int], Tuple[Optional[int], ...]]: + """ + For a single axis, returns an int corresponding to the index of the axis. + For multiple axes, returns a tuple of ints corresponding to the indices of the axes. + If the axis is not present, returns None for that position """ if isinstance(axis, Axis): @@ -262,7 +284,7 @@ class NamedArray: except ValueError: return None else: - return tuple(self._lookup_indices(a) for a in axis) + return tuple(self.axis_indices(a) for a in axis) # Axis rearrangement @typing.overload @@ -675,7 +697,7 @@ def take(array: NamedArray, axis: AxisSelector, index: Union[int, NamedArray]) - if index is a NamedArray, then those axes are added to the output array """ - axis_index = array._lookup_indices(axis) + axis_index = array.axis_indices(axis) if axis_index is None: raise ValueError(f"axis {axis} not found in {array}") @@ -696,14 +718,14 @@ def take(array: NamedArray, axis: AxisSelector, index: Union[int, NamedArray]) - if intersecting_axes: # if the eliminated axis is also in the index, we rename it to a dummy axis that we can broadcast over it - need_to_use_dummy_axis = index._lookup_indices(axis.name) is not None + need_to_use_dummy_axis = index.axis_indices(axis.name) is not None if need_to_use_dummy_axis: index = index.rename({axis.name: "__DUMMY_" + axis.name}) array = haliax.broadcast_to(array, index.axes, ensure_order=False, enforce_no_extra_axes=False) new_axes = eliminate_axes(array.axes, axis) index = haliax.broadcast_to(index, new_axes, ensure_order=True, enforce_no_extra_axes=True) - axis_index = array._lookup_indices(axis) # if it moved + axis_index = array.axis_indices(axis) # if it moved index_array = jnp.expand_dims(index.array, axis=axis_index) new_array = jnp.take_along_axis(array.array, index_array, axis=axis_index) new_array = jnp.squeeze(new_array, axis=axis_index) @@ -792,7 +814,7 @@ def _slice_old( Note: This method is basically a wrapper around jax.lax.dynamic_slice_in_dim. """ - axis_index = array._lookup_indices(axis) + axis_index = array.axis_indices(axis) if axis_index is None: raise ValueError(f"axis {axis} not found in {array}") @@ -824,7 +846,7 @@ def _slice_new( new_lengths = [axis.size for axis in array.axes] for axis, s in start.items(): - axis_index = array._lookup_indices(axis_name(axis)) + axis_index = array.axis_indices(axis_name(axis)) if axis_index is None: raise ValueError(f"axis {axis} not found in {array}") @@ -883,14 +905,14 @@ def updated_slice( f = updated_slice for axis_name in map_axes: # make sure that axis_name is in `array`. otherwise it doesn't make sense to vmap over it - if array._lookup_indices(axis_name) is None: + if array.axis_indices(axis_name) is None: raise ValueError(f"axis {axis_name} not found in original array's axes: {array.shape}") f = haliax.vmap(f, axis=axis_name) return f(array, start, update) array_slice_indices = [0] * len(array.axes) for axis, s in start.items(): - axis_index = array._lookup_indices(haliax.axis_name(axis)) + axis_index = array.axis_indices(haliax.axis_name(axis)) if axis_index is None: raise ValueError(f"axis {axis} not found in {array}") if isinstance(s, NamedArray): # this can happen in the vmap case @@ -900,7 +922,7 @@ def updated_slice( array_slice_indices[axis_index] = s total_length = array.axes[axis_index].size - update_axis = update._lookup_indices(haliax.axis_name(axis)) + update_axis = update.axis_indices(haliax.axis_name(axis)) # if s is a tracer we can't check the size if update_axis is None: @@ -923,7 +945,7 @@ def updated_slice( ) broadcasted_axes = [] for ax in array.axes: - upd_ax = update._lookup_indices(ax.name) + upd_ax = update.axis_indices(ax.name) broadcasted_axes.append(ax if upd_ax is None else update.axes[upd_ax]) update = haliax.broadcast_to(update, broadcasted_axes, enforce_no_extra_axes=True) upd_arr = update.array @@ -967,7 +989,7 @@ def _compute_new_axes_and_slices_for_index( index_axis_names = set() for axis, slice_ in slices.items(): - axis_index = array._lookup_indices(axis) + axis_index = array.axis_indices(axis) if axis_index is None: raise ValueError(f"axis {axis} not found in {array}") if isinstance(slice_, py_slice) or isinstance(slice_, dslice) or is_pallas_dslice(slice_): @@ -1111,7 +1133,7 @@ def split(a: NamedArray, axis: AxisSelector, new_axes: Sequence[Axis]) -> Sequen new_axes (Sequence[Axis]): the axes to split into. Must have the same total length as the axis being split. """ # check the lengths of the new axes - index = a._lookup_indices(axis) + index = a.axis_indices(axis) if index is None: raise ValueError(f"Axis {axis} not found in {a.axes}") @@ -1136,7 +1158,7 @@ def unbind(array: NamedArray, axis: AxisSelector) -> List[NamedArray]: Unbind an array along an axis, returning a list of NamedArrays, one for each position on that axis. Analogous to torch.unbind or np.rollaxis """ - axis_index = array._lookup_indices(axis) + axis_index = array.axis_indices(axis) if axis_index is None: raise ValueError(f"axis {axis} not found in {array}") new_axes = array.axes[:axis_index] + array.axes[axis_index + 1 :] @@ -1153,7 +1175,7 @@ def roll(array: NamedArray, shift: Union[int, Tuple[int, ...]], axis: AxisSelect """ Roll an array along an axis or axes. Analogous to np.roll """ - axis_indices = array._lookup_indices(axis) + axis_indices = array.axis_indices(axis) if axis_indices is None: raise ValueError(f"axis {axis} not found in {array}") return NamedArray(jnp.roll(array.array, shift, axis_indices), array.axes) @@ -1331,7 +1353,7 @@ def unflatten_axis(array: NamedArray, axis: AxisSelector, new_axes: AxisSpec) -> """ Split an axis into a sequence of axes. The old axis must have the same size as the product of the new axes. """ - old_index = array._lookup_indices(axis) + old_index = array.axis_indices(axis) if old_index is None: raise ValueError(f"Axis {axis} not found in {array}") diff --git a/src/haliax/hof.py b/src/haliax/hof.py index ddd624e..00144f0 100644 --- a/src/haliax/hof.py +++ b/src/haliax/hof.py @@ -85,7 +85,7 @@ def vmap( def _index_of_batch_axis(array, default): if isinstance(array, NamedArray): - return array._lookup_indices(axis) + return array.axis_indices(axis) elif callable(default): return default(array) else: diff --git a/src/haliax/nn/normalization.py b/src/haliax/nn/normalization.py index 8622c66..9f684b8 100644 --- a/src/haliax/nn/normalization.py +++ b/src/haliax/nn/normalization.py @@ -163,7 +163,7 @@ def standardize( """Analogous to [jax.nn.standardize][], but with support for NamedArrays.""" x, mean, variance, where = haliax.broadcast_arrays(x, mean, variance, where) # type: ignore raw_x, mean, variance, where = unwrap_namedarrays(x, mean, variance, where) - axis_indices = x._lookup_indices(axis) + axis_indices = x.axis_indices(axis) plain = jnn.standardize(raw_x, axis_indices, mean=mean, variance=variance, epsilon=epsilon, where=where) return NamedArray(plain, x.axes) diff --git a/src/haliax/ops.py b/src/haliax/ops.py index fb23f8d..d6508b4 100644 --- a/src/haliax/ops.py +++ b/src/haliax/ops.py @@ -11,8 +11,8 @@ from .jax_utils import is_scalarish def trace(array: NamedArray, axis1: AxisSelector, axis2: AxisSelector, offset=0, dtype=None) -> NamedArray: """Compute the trace of an array along two named axes.""" - a1_index = array._lookup_indices(axis1) - a2_index = array._lookup_indices(axis2) + a1_index = array.axis_indices(axis1) + a2_index = array.axis_indices(axis2) if a1_index is None: raise ValueError(f"Axis {axis1} not found in array. Available axes: {array.axes}") @@ -139,7 +139,7 @@ def pad_left(array: NamedArray, axis: Axis, new_axis: Axis, value=0) -> NamedArr if amount_to_pad_to < 0: raise ValueError(f"Cannot pad {axis} to {new_axis}") - idx = array._lookup_indices(axis) + idx = array.axis_indices(axis) padding = [(0, 0)] * array.ndim if idx is None: diff --git a/src/haliax/random.py b/src/haliax/random.py index ad461f3..6b840b0 100644 --- a/src/haliax/random.py +++ b/src/haliax/random.py @@ -218,7 +218,7 @@ def choice( :return: Array with shape `shape` + (`a.axes` - `axis`) """ - index = a._lookup_indices(axis) + index = a.axis_indices(axis) assert index is not None, f"axis {axis} not in a" shape = ensure_tuple(shape) @@ -261,7 +261,7 @@ def categorical(key, logits: NamedArray, axis: AxisSelector, shape: Optional[Axi logits = logits.broadcast_axis(shape) - index = logits._lookup_indices(axis) + index = logits.axis_indices(axis) assert index is not None, f"axis {axis} not in logits" jax_shape = to_jax_shape(shape) @@ -280,7 +280,7 @@ def gumbel(key, shape: AxisSpec, dtype=float): @named_call def permutation(key, x: NamedArray, axis: AxisSelector, independent: bool = False): - axis_index = x._lookup_indices(axis) + axis_index = x.axis_indices(axis) jax_array = jrandom.permutation(key, x.array, axis_index, independent=independent) return haliax.auto_sharded(NamedArray(jax_array, x.axes)) diff --git a/src/haliax/specialized_fns.py b/src/haliax/specialized_fns.py index 709d1ab..ea5914b 100644 --- a/src/haliax/specialized_fns.py +++ b/src/haliax/specialized_fns.py @@ -22,7 +22,7 @@ def top_k( NamedArray: array with the top k elements along the given axis NamedArray: array with the top k elements' indices along the given axis """ - pos = arr._lookup_indices(axis) + pos = arr.axis_indices(axis) if pos is None: raise ValueError(f"Axis {axis} not found in {arr}") new_array = jnp.moveaxis(arr.array, pos, -1) # move axis to the last position diff --git a/src/haliax/wrap.py b/src/haliax/wrap.py index 56943ed..f151d46 100644 --- a/src/haliax/wrap.py +++ b/src/haliax/wrap.py @@ -52,7 +52,7 @@ def wrap_reduction_call( axis = ensure_tuple(axis) if single_axis_only and len(axis) > 1: raise ValueError(f"{fn.__name__} only supports a single axis") - indices = a._lookup_indices(axis) + indices = a.axis_indices(axis) if indices is None or any(x is None for x in indices): raise ValueError(f"axis {axis} is not in {a.axes}") new_axes = [ax for ax in a.axes if not selects_axis(axis, ax)] @@ -74,7 +74,7 @@ def wrap_axiswise_call(fn, a, axis: Optional[AxisSelection], *, single_axis_only if axis is None: return fn(a.array, axis=None, **kwargs) else: - indices = ensure_tuple(a._lookup_indices(axis)) + indices = ensure_tuple(a.axis_indices(axis)) if any(x is None for x in indices): raise ValueError(f"axis {axis} is not in {a.axes}") if len(indices) == 1: commit 0e890c157adedb1caa49ee62db1f427d98f051b0 Date: 2025-06-24T23:56:21-07:00 use the newer jax ragged_dot for moe diff --git a/src/haliax/nn/linear.py b/src/haliax/nn/linear.py index 8f308e8..736293c 100644 --- a/src/haliax/nn/linear.py +++ b/src/haliax/nn/linear.py @@ -18,6 +18,7 @@ from ..core import NamedArray from ..jax_utils import named_call from ..partitioning import ResourceAxis from ..quantization import DotGeneralOp +from ..util import ensure_tuple class Linear(ModuleWithStateDictSerialization): @@ -142,7 +143,10 @@ class MoELinear(eqx.Module): Experts: AxisSpec = eqx.static_field() In: Axis = eqx.static_field() Out: Axis = eqx.static_field() - dot_general: DotGeneralOp = eqx.field(default_factory=DotGeneralOp.default) + # TODO: support quanitization for ragged_dot? + # dot_general: DotGeneralOp = eqx.field(default_factory=DotGeneralOp.default) + + use_gmm: bool = eqx.field(static=True) @staticmethod def init( @@ -154,6 +158,7 @@ class MoELinear(eqx.Module): use_bias: bool = True, out_first: bool = False, init_scale: float = 1.0, + use_gmm: bool = False, ) -> "MoELinear": """ Args: @@ -172,7 +177,7 @@ class MoELinear(eqx.Module): weight = hax.random.truncated_normal(key, joint_spec, -3, 3) * (init_scale / math.sqrt(input_size)) bias = hax.zeros(Out) if use_bias else None - return MoELinear(weight, bias, Experts, In, Out) + return MoELinear(weight, bias, Experts, In, Out, use_gmm=use_gmm) @named_call def __call__(self, inputs, group_sizes, *, key: Optional[PRNGKey] = None): @@ -184,21 +189,42 @@ class MoELinear(eqx.Module): """ del key - inputs = inputs.rearrange((..., self.In)) - out_axes = hax.replace_axis(inputs.axes, self.In, self.Out) + dim_numbers = jax.lax.RaggedDotDimensionNumbers( + dot_dimension_numbers=( + # contracting + (ensure_tuple(inputs.axis_indices(self.In)), ensure_tuple(self.weight.axis_indices(self.In))), + # batch + ((), ()), + ), + # Everything other than contracting dim is ragged + lhs_ragged_dimensions=(inputs.axis_indices(hax.axis.without_axes(inputs.axes, self.In))), + rhs_group_dimensions=(self.weight.axis_indices(self.Experts),), + ) - q = _gmm( - inputs, - self.weight, - group_sizes, - out_axes, - ar=hax.partitioning.physical_axis_name(self.In) == ResourceAxis.MODEL, - ) # gmm((B, D), (E, D, d)) -> (B, d) - q = hax.auto_sharded(q) + if self.use_gmm: + inputs = inputs.rearrange((..., self.In)) + out_axes = hax.replace_axis(inputs.axes, self.In, self.Out) + q = _gmm( + inputs, + self.weight, + group_sizes, + out_axes, + ar=hax.partitioning.physical_axis_name(self.In) == ResourceAxis.MODEL, + ) # gmm((B, D), (E, D, d)) -> (B, d) + else: + q_raw = jax.lax.ragged_dot_general( + lhs=inputs.array, + rhs=self.weight.array, + group_sizes=group_sizes.rearrange((..., self.Experts)).array, + ragged_dot_dimension_numbers=dim_numbers, + ) + out_axes = hax.replace_axis(inputs.axes, self.In, self.Out) + q = hax.named(q_raw, out_axes) if self.bias is not None: q = q + self.bias - q = hax.auto_sharded(q) + + q = hax.auto_sharded(q) return q @@ -249,7 +275,7 @@ def gmm_sharded(lhs_: jnp.ndarray, rhs_: jnp.ndarray, group_sizes_: jnp.ndarray, group_sizes_, preferred_element_type=lhs_.dtype, tiling=(min(m, tile_size[0]), min(k, tile_size[1]), min(n, tile_size[2])), - # interpret=True, + interpret=jax.default_backend() == "cpu", ) if ar: commit 101dd37d225391c6352cf5943814cb043b4fc12c Date: 2025-06-26T22:41:14-07:00 sigh diff --git a/.github/workflows/run_tests.yaml b/.github/workflows/run_tests.yaml index 8a03bea..e376f96 100644 --- a/.github/workflows/run_tests.yaml +++ b/.github/workflows/run_tests.yaml @@ -17,7 +17,7 @@ jobs: run: | python -m pip install --upgrade pip pip install flake8 pytest - pip install jax==0.4.35 jaxlib==0.4.35 .[dev] + pip install -e .[dev] - name: Test with pytest run: | XLA_FLAGS=--xla_force_host_platform_device_count=8 PYTHONPATH=tests:src:. pytest tests commit 4f74b1789d9825164fc73ca4ca4894e2bc24509d Date: 2025-06-26T22:43:47-07:00 pre-commit diff --git a/src/haliax/nn/activations.py b/src/haliax/nn/activations.py index ae9a80d..8f16f0a 100644 --- a/src/haliax/nn/activations.py +++ b/src/haliax/nn/activations.py @@ -89,7 +89,6 @@ def quick_gelu(x): return x * sigmoid(1.702 * x) - def relu_squared(x: A) -> A: """ReLU squared activation function. jnp.square(jnp.maximum(0, x))""" diff --git a/tests/test_nn.py b/tests/test_nn.py index 634736d..a53381c 100644 --- a/tests/test_nn.py +++ b/tests/test_nn.py @@ -198,4 +198,4 @@ def test_relu_squared_scalar(use_jit): x_neg = -5.0 expected_neg = 0.0 actual_neg = f(x_neg) - assert jnp.allclose(actual_neg, expected_neg) \ No newline at end of file + assert jnp.allclose(actual_neg, expected_neg) commit 542918a14b1eb840628b48e87fe20760e8d01b53 Date: 2025-06-28T22:38:37-07:00 Improve NamedArray typing (#142) * Return Annotated NamedArray * Add Named type wrapper (#143) * Run pre-commit * Run pre-commit hooks * Implement dtype-aware NamedArray typing (#145) * Enhance dtype typing * Update docs/typing.md diff --git a/docs/typing.md b/docs/typing.md new file mode 100644 index 0000000..528e9da --- /dev/null +++ b/docs/typing.md @@ -0,0 +1,61 @@ +# NamedArray Type Annotations + +Haliax supports a lightweight syntax for specifying the axes of a `NamedArray` +in type annotations. Internally, `Named[...]` expands to +`Annotated[NamedArray, axes]`, so it works well with static type checkers like +``mypy``. The syntax mirrors normal indexing with axis names. Some examples: + +```python +from haliax import Named + +arr: Named["batch", "embed"] +arr: Named["batch embed ..."] # starts with these axes +arr: Named["... embed"] # ends with this axis +arr: Named["batch ... embed"] # contains these axes in order +arr: Named[{"batch", "embed"}] # has exactly these axes, order ignored +arr: Named[{"batch", "embed", ...}] # has at least these axes +``` + +At runtime you can verify that a `NamedArray` conforms to a particular +annotation using `matches_axes`: + +```python +if not arr.matches_axes(Named["batch embed ..."]): + raise ValueError("unexpected axes") +``` + +## DType-aware annotations + +Sometimes it is useful to express both the axes **and** the dtype in the type +annotation. The :mod:`haliax.typing` module defines symbolic types for all of +JAX's common dtypes that can be indexed just like ``Named``. In documentation +examples we'll use ``import haliax.typing as ht``: + +```python +import haliax.typing as ht + +def foo(x: ht.f32["batch"]): + ... + +def bar(x: ht.i32["batch"]): + ... +``` + +For convenience the module also provides aggregate categories ``Float``, +``Complex``, ``Int`` and ``UInt`` that match any floating point, complex, +signed integer or unsigned integer dtype respectively: + +```python +def baz(x: ht.Float["batch"]): + ... +``` + +At runtime ``matches_axes`` also checks the dtype when one is present: + +```python +from haliax import Axis, zeros +import haliax.typing as ht + +arr = zeros({"batch": 4}) +assert arr.matches_axes(ht.f32["batch"]) # dtype and axes both match +``` diff --git a/mkdocs.yml b/mkdocs.yml index e0f61fe..e429b6b 100644 --- a/mkdocs.yml +++ b/mkdocs.yml @@ -90,6 +90,7 @@ nav: - Indexing and Slicing: 'indexing.md' - Rearrange: 'rearrange.md' - Matrix Multiplication: 'matmul.md' + - Type Annotations: 'typing.md' - Higher Order Functions: - Scan and Fold: 'scan.md' - Vectorization: 'vmap.md' diff --git a/src/haliax/__init__.py b/src/haliax/__init__.py index 6c45a8f..d0caeb3 100644 --- a/src/haliax/__init__.py +++ b/src/haliax/__init__.py @@ -40,7 +40,10 @@ from .axis import ( selects_axis, ) from .core import ( + Named, NamedArray, + NamedArrayAxes, + NamedArrayAxesSpec, NamedOrNumeric, are_shape_checks_enabled, broadcast_arrays, @@ -926,6 +929,9 @@ __all__ = [ "make_axes", "axis_name", "axis_size", + "NamedArrayAxesSpec", + "NamedArrayAxes", + "Named", "NamedArray", "broadcast_to", "broadcast_axis", diff --git a/src/haliax/core.py b/src/haliax/core.py index 51c34a6..44537fb 100644 --- a/src/haliax/core.py +++ b/src/haliax/core.py @@ -58,9 +58,139 @@ def are_shape_checks_enabled(): return _ENABLE_SHAPE_CHECKS +@dataclass(frozen=True) +class NamedArrayAxes: + """Representation of a :class:`NamedArray`'s axes for type annotations.""" + + before: Tuple[str, ...] + """Names that must appear before any optional ellipsis.""" + + after: Tuple[str, ...] = () + """Names that must appear after any optional ellipsis.""" + + ordered: bool = True + """Whether the axes must appear in this order.""" + + subset: bool = False + """If ``True``, other axes may appear where the ellipsis is located.""" + + dtype: typing.Any | None = None + """Optional dtype that the array should have.""" + + def __repr__(self) -> str: + dtype_prefix = "" + if self.dtype is not None: + dtype_obj = self.dtype + if hasattr(dtype_obj, "category"): + dtype_name = dtype_obj.name + else: + dtype_name = getattr(dtype_obj, "name", str(dtype_obj)) + dtype_prefix = f"{dtype_name} " + + if self.ordered: + parts = list(self.before) + if self.subset: + parts.append("...") + parts.extend(self.after) + spec = " ".join(parts) + return f"NamedArray[{dtype_prefix}{spec}]" + else: + part = ", ".join(self.before) + if self.subset: + if part: + part += ", ..." + else: + part = "..." + return f"NamedArray[{dtype_prefix}{{{part}}}]" + + +# a specification for NamedArray axes used in type annotations +NamedArrayAxesSpec = Union[ + NamedArrayAxes, + str, + Sequence[str | EllipsisType], + set[str | EllipsisType], +] + + +def _parse_namedarray_axes( + item: NamedArrayAxesSpec | typing.Annotated["NamedArray", NamedArrayAxes] +) -> NamedArrayAxes: + origin = typing.get_origin(item) + if origin is typing.Annotated: + args = typing.get_args(item) + if len(args) >= 2: + item = args[1] + if isinstance(item, NamedArrayAxes): + return item + if isinstance(item, str): + parts = item.split() + if parts.count("...") > 1: + raise TypeError("Only one ellipsis allowed in NamedArray typing spec") + if "..." in parts: + idx = parts.index("...") + before_parts = tuple(parts[:idx]) + after_parts = tuple(parts[idx + 1 :]) + return NamedArrayAxes(before_parts, after_parts, ordered=True, subset=True) + else: + return NamedArrayAxes(tuple(parts), (), ordered=True, subset=False) + if isinstance(item, set) or isinstance(item, frozenset): + subset = False + names_list: List[str] = [] + for part in item: + if part is Ellipsis: + if subset: + raise TypeError("Only one ellipsis allowed in NamedArray typing spec") + subset = True + else: + if not isinstance(part, str): + raise TypeError(f"Invalid axis spec: {part}") + names_list.append(part) + return NamedArrayAxes(tuple(names_list), (), ordered=False, subset=subset) + if isinstance(item, (tuple, list)): + subset = False + before_list: List[str] = [] + after_list: List[str] = [] + cur_list = before_list + for part in item: + if part is Ellipsis: + if subset: + raise TypeError("Only one ellipsis allowed in NamedArray typing spec") + subset = True + cur_list = after_list + else: + if not isinstance(part, str): + raise TypeError(f"Invalid axis spec: {part}") + cur_list.append(part) + if subset: + return NamedArrayAxes(tuple(before_list), tuple(after_list), ordered=True, subset=True) + else: + return NamedArrayAxes(tuple(before_list), (), ordered=True, subset=False) + raise TypeError(f"Invalid NamedArray typing spec: {item}") + + +class Named: + """Type annotation helper for :class:`NamedArray`. + + ``Named["batch embed"]`` expands to ``Annotated[NamedArray, axes]`` so that + type checkers treat it as a ``NamedArray`` at static time while the axis + metadata is available at runtime via :func:`typing.get_args`. + """ + + def __class_getitem__(cls, item: NamedArrayAxesSpec) -> typing.Any: + axes = _parse_namedarray_axes(item) + return typing.Annotated[NamedArray, axes] + + +class NamedArrayMeta(type): + def __getitem__(cls, item: NamedArrayAxesSpec) -> typing.Any: + axes = _parse_namedarray_axes(item) + return typing.Annotated[NamedArray, axes] + + @jax.tree_util.register_pytree_node_class @dataclass(frozen=True) -class NamedArray: +class NamedArray(metaclass=NamedArrayMeta): array: jnp.ndarray axes: Tuple[Axis, ...] @@ -145,6 +275,45 @@ class NamedArray: """Returns true if the given axis is present in this NamedArray.""" return self.axis_indices(axis) is not None + def matches_axes(self, spec: NamedArrayAxesSpec) -> bool: + """Check whether this NamedArray conforms to the given `NamedArray` type. + + Parameters + ---------- + spec : NamedArrayAxesSpec + The specification to check against. It can be produced via the + ``NamedArray[...]`` syntax or passed directly as a string or + sequence of axis names. + """ + + ann = _parse_namedarray_axes(spec) + if ann.dtype is not None: + dtype_spec = ann.dtype + if hasattr(dtype_spec, "category"): + if not jnp.issubdtype(self.dtype, dtype_spec.category): + return False + elif self.dtype != dtype_spec: + return False + + names = tuple(ax.name for ax in self.axes) + if ann.ordered: + if not ann.subset: + return names == ann.before + if len(names) < len(ann.before) + len(ann.after): + return False + if names[: len(ann.before)] != ann.before: + return False + if ann.after and names[-len(ann.after) :] != ann.after: + return False + return True + else: + name_set = set(names) + spec_set = set(ann.before) + if ann.subset: + return spec_set.issubset(name_set) + else: + return name_set == spec_set + @overload def axis_size(self, axis: AxisSelector) -> int: # type: ignore ... @@ -1885,6 +2054,9 @@ def _convert_index_expr_to_dict(idx) -> dict[AxisSelector, NamedIndex]: __all__ = [ + "NamedArrayAxesSpec", + "NamedArrayAxes", + "Named", "NamedArray", "named", "slice", diff --git a/src/haliax/typing.py b/src/haliax/typing.py new file mode 100644 index 0000000..6cfc6e0 --- /dev/null +++ b/src/haliax/typing.py @@ -0,0 +1,88 @@ +from __future__ import annotations + +import typing as tp +from dataclasses import dataclass, replace + +import jax.numpy as jnp + +from .core import NamedArray, NamedArrayAxes, _parse_namedarray_axes + + +@dataclass(frozen=True) +class DTypeCategory: + """Represents a dtype category such as ``float`` or ``int``.""" + + name: str + category: tp.Any + + def __repr__(self) -> str: # pragma: no cover - trivial + return self.name + + +def _wrap_namedarray_with_dtype(dtype): + class DTypeType: + def __class_getitem__(cls, axes_spec): + axes = _parse_namedarray_axes(axes_spec) + axes_with_dtype = replace(axes, dtype=dtype) + return tp.Annotated[NamedArray, axes_with_dtype] + + return DTypeType + + +def _wrap_namedarray_with_category(category: DTypeCategory): + class DTypeType: + def __class_getitem__(cls, axes_spec): + axes = _parse_namedarray_axes(axes_spec) + axes_with_dtype = replace(axes, dtype=category) + return tp.Annotated[NamedArray, axes_with_dtype] + + return DTypeType + + +f32 = _wrap_namedarray_with_dtype(jnp.float32) +f64 = _wrap_namedarray_with_dtype(jnp.float64) +f16 = _wrap_namedarray_with_dtype(jnp.float16) +bf16 = _wrap_namedarray_with_dtype(jnp.bfloat16) + +i8 = _wrap_namedarray_with_dtype(jnp.int8) +i16 = _wrap_namedarray_with_dtype(jnp.int16) +i32 = _wrap_namedarray_with_dtype(jnp.int32) +i64 = _wrap_namedarray_with_dtype(jnp.int64) + +u8 = _wrap_namedarray_with_dtype(jnp.uint8) +u16 = _wrap_namedarray_with_dtype(jnp.uint16) +u32 = _wrap_namedarray_with_dtype(jnp.uint32) +u64 = _wrap_namedarray_with_dtype(jnp.uint64) + +bool_ = _wrap_namedarray_with_dtype(jnp.bool_) +complex64 = _wrap_namedarray_with_dtype(jnp.complex64) +complex128 = _wrap_namedarray_with_dtype(jnp.complex128) + + +Float = _wrap_namedarray_with_category(DTypeCategory("float", jnp.floating)) +Complex = _wrap_namedarray_with_category(DTypeCategory("complex", jnp.complexfloating)) +Int = _wrap_namedarray_with_category(DTypeCategory("int", jnp.signedinteger)) +UInt = _wrap_namedarray_with_category(DTypeCategory("uint", jnp.unsignedinteger)) + + +__all__ = [ + "f32", + "f64", + "f16", + "bf16", + "i8", + "i16", + "i32", + "i64", + "u8", + "u16", + "u32", + "u64", + "bool_", + "complex64", + "complex128", + "Float", + "Complex", + "Int", + "UInt", +] diff --git a/tests/test_dtype_typing.py b/tests/test_dtype_typing.py new file mode 100644 index 0000000..805ae27 --- /dev/null +++ b/tests/test_dtype_typing.py @@ -0,0 +1,41 @@ +from __future__ import annotations + +import typing + +import jax.numpy as jnp + +from haliax import Axis, NamedArray +from haliax.typing import Float, Int, f32, i32 + + +def test_dtype_and_axes_annotation(): + def foo(x: f32["batch embed"]): # type: ignore # noqa: F722 + pass + + ann = typing.get_args(typing.get_type_hints(foo, include_extras=True)["x"]) + assert ann[0] is NamedArray + spec = ann[1] + assert spec.dtype == jnp.float32 + assert spec.before == ("batch", "embed") + + +def test_other_dtype_annotation(): + def bar(x: i32["batch"]): # type: ignore # noqa: F722 + pass + + spec = typing.get_args(typing.get_type_hints(bar, include_extras=True)["x"])[1] + assert spec.dtype == jnp.int32 + assert spec.before == ("batch",) + + +def test_dtype_category_annotation_and_check(): + def baz(x: Float["b"]): # type: ignore # noqa: F722 + pass + + spec = typing.get_args(typing.get_type_hints(baz, include_extras=True)["x"])[1] + assert str(spec.dtype) == "float" + + B = Axis("b", 1) + arr = NamedArray(jnp.ones((B.size,), dtype=jnp.float32), (B,)) + assert arr.matches_axes(Float["b"]) # type: ignore + assert not arr.matches_axes(Int["b"]) # type: ignore diff --git a/tests/test_namedarray_typing.py b/tests/test_namedarray_typing.py new file mode 100644 index 0000000..6259796 --- /dev/null +++ b/tests/test_namedarray_typing.py @@ -0,0 +1,64 @@ +from __future__ import annotations + +import typing + +import jax.numpy as jnp + +from haliax import Axis, Named, NamedArray +from haliax.typing import Float, Int, f32, i32 + + +def test_namedarray_type_syntax(): + axes1 = typing.get_args(NamedArray["batch", "embed"])[1] + axes2 = typing.get_args(Named["batch embed"])[1] # type: ignore + assert axes1 == axes2 + + axes3 = typing.get_args(NamedArray["batch embed ..."])[1] + assert axes3.before == ("batch", "embed") and axes3.subset and axes3.after == () + + axes4 = typing.get_args(NamedArray[{"batch", "embed"}])[1] + assert set(axes4.before) == {"batch", "embed"} and not axes4.ordered + + axes5 = typing.get_args(NamedArray[{"batch", "embed", ...}])[1] + assert set(axes5.before) == {"batch", "embed"} and not axes5.ordered and axes5.subset + + axes6 = typing.get_args(NamedArray["... embed"])[1] + assert axes6.before == () and axes6.after == ("embed",) and axes6.subset + + axes7 = typing.get_args(NamedArray["batch ... embed"])[1] + assert axes7.before == ("batch",) and axes7.after == ("embed",) and axes7.subset + + +def test_named_param_annotation(): + def foo(x: Named["batch", "embed"]): # type: ignore + pass + + axes = typing.get_args(typing.get_type_hints(foo, include_extras=True)["x"])[1] + assert axes.before == ("batch", "embed") + + +def test_namedarray_runtime_check(): + Batch = Axis("batch", 2) + Embed = Axis("embed", 3) + arr = NamedArray(jnp.zeros((Batch.size, Embed.size)), (Batch, Embed)) + assert arr.matches_axes(NamedArray["batch", "embed"]) + assert arr.matches_axes(Named["batch embed"]) # type: ignore + assert arr.matches_axes(NamedArray["batch embed ..."]) + assert arr.matches_axes(NamedArray[{"batch", "embed"}]) + assert arr.matches_axes(NamedArray[{"batch", "embed", ...}]) + assert not arr.matches_axes(NamedArray["embed batch"]) + assert not arr.matches_axes(NamedArray[{"batch", "foo", ...}]) + + +def test_namedarray_runtime_check_with_dtype(): + Batch = Axis("batch", 2) + arr = NamedArray(jnp.zeros((Batch.size,), dtype=jnp.float32), (Batch,)) + assert arr.matches_axes(f32["batch"]) # type: ignore + assert not arr.matches_axes(i32["batch"]) # type: ignore + + +def test_namedarray_runtime_check_with_category(): + B = Axis("batch", 1) + arr = NamedArray(jnp.zeros((B.size,), dtype=jnp.float32), (B,)) + assert arr.matches_axes(Float["batch"]) # type: ignore + assert not arr.matches_axes(Int["batch"]) # type: ignore commit fad5600b46993c262037a3ae5772831fb122e76e Date: 2025-06-29T21:45:53-07:00 Dict shapes (#147) diff --git a/docs/api.md b/docs/api.md index 1dd3fc6..1fac737 100644 --- a/docs/api.md +++ b/docs/api.md @@ -35,7 +35,6 @@ Occasionally, an axis size can be inferred in some circumstances but not others. ::: haliax.axis.eliminate_axes ::: haliax.axis.without_axes ::: haliax.axis.selects_axis -::: haliax.axis.overlapping_axes ::: haliax.axis.is_axis_compatible diff --git a/pyproject.toml b/pyproject.toml index 9e893be..c9e9f18 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -71,3 +71,19 @@ src_paths = ["src", "tests"] "Homepage" = "https://github.com/stanford-crfm/haliax" "Bug Tracker" = "https://github.com/stanford-crfm/haliax/issues/" "Documentation" = "https://haliax.readthedocs.io/en/latest/" + + +[tool.coverage.report] +exclude_also = [ + "def __repr__", + "if self.debug:", + "if settings.DEBUG", + "raise AssertionError", + "raise NotImplementedError", + "if 0:", + "if __name__ == .__main__.:", + "if TYPE_CHECKING:", + "class .*\\bProtocol\\):", + "@(abc\\.)?abstractmethod", + "[.][.][.]" + ] diff --git a/src/haliax/__init__.py b/src/haliax/__init__.py index d0caeb3..e26ac12 100644 --- a/src/haliax/__init__.py +++ b/src/haliax/__init__.py @@ -29,6 +29,7 @@ from .axis import ( AxisSpec, axis_name, axis_size, + axis_spec_to_tuple, concat_axes, dblock, ds, @@ -38,6 +39,7 @@ from .axis import ( replace_axis, resolve_axis, selects_axis, + to_jax_shape, ) from .core import ( Named, @@ -105,8 +107,8 @@ def full(shape: AxisSpec, fill_value: T, dtype: Optional[DTypeLike] = None) -> N if isinstance(shape, Axis): return NamedArray(jnp.full(shape=shape.size, fill_value=fill_value, dtype=dtype), (shape,)) else: - x_shape = tuple(x.size for x in shape) - return NamedArray(jnp.full(shape=x_shape, fill_value=fill_value, dtype=dtype), tuple(shape)) + x_shape = to_jax_shape(shape) + return NamedArray(jnp.full(shape=x_shape, fill_value=fill_value, dtype=dtype), shape) def zeros_like(a: NamedArray, dtype=None) -> NamedArray: @@ -155,7 +157,7 @@ def arange(axis: AxisSpec, *, start=0, step=1, dtype: Optional[DTypeLike] = None arr = jax.lax.iota(dtype=dtype or jnp.result_type(start), size=size) * step + start arr = arr.reshape(to_jax_shape(axis)) - return NamedArray(arr, ensure_tuple(axis)) + return NamedArray(arr, axis_spec_to_tuple(axis)) # TODO: add overrides for arraylike start/stop to linspace, logspace, geomspace diff --git a/src/haliax/_src/dot.py b/src/haliax/_src/dot.py index 48a0061..966452e 100644 --- a/src/haliax/_src/dot.py +++ b/src/haliax/_src/dot.py @@ -12,6 +12,7 @@ from haliax.axis import ( AxisSelection, PartialAxisSpec, axis_name, + axis_spec_to_shape_dict, eliminate_axes, rearrange_for_partial_order, union_axes, @@ -140,8 +141,8 @@ def dot( if axis is None: jax_str = f"contract {', '.join(axis_name(ax) for ax in all_axes)} -> <scalar>" else: - axis = ensure_tuple(axis) - jax_str = f"contract {', '.join(axis_name(ax) for ax in axis)} -> {', '.join(a.name for a in output_axes)}" + axis = axis_spec_to_shape_dict(axis) + jax_str = f"contract {', '.join(axis)} -> {', '.join(a.name for a in output_axes)}" with jax.named_scope(jax_str): output = _jittable_dg_einsum( diff --git a/src/haliax/axis.py b/src/haliax/axis.py index af930fa..3560525 100644 --- a/src/haliax/axis.py +++ b/src/haliax/axis.py @@ -2,7 +2,7 @@ import typing from dataclasses import dataclass from math import prod from types import EllipsisType -from typing import Dict, List, Mapping, Optional, Sequence, Tuple, Union, overload +from typing import List, Mapping, Optional, Sequence, Union, overload import equinox as eqx @@ -28,7 +28,7 @@ class Axis: return f"{self.name}({self.size})" -def make_axes(**kwargs: int) -> Tuple[Axis, ...]: +def make_axes(**kwargs: int) -> tuple[Axis, ...]: """ Convenience function for creating a tuple of Axis objects. @@ -43,16 +43,17 @@ def make_axes(**kwargs: int) -> Tuple[Axis, ...]: AxisSelector = Union[Axis, str] """AxisSelector is a type that can be used to select a single axis from an array. str or Axis""" -AxisSelection = Union[AxisSelector, Sequence[AxisSelector]] +ShapeDict = Mapping[str, int] +"""ShapeDict is a type that can be used to specify the axes of an array, usually for creation or adding a new axis""" +PartialShapeDict = Mapping[str, Optional[int]] +"""Similar to a AxisSelection, in dict form.""" + +AxisSelection = Union[AxisSelector, Sequence[AxisSelector], PartialShapeDict] """AxisSelection is a type that can be used to select multiple axes from an array. str, Axis, or sequence of mixed str and Axis""" -AxisSpec = Union[Axis, Sequence[Axis]] +AxisSpec = Union[Axis, Sequence[Axis], ShapeDict] """AxisSpec is a type that can be used to specify the axes of an array, usually for creation or adding a new axis whose size can't be determined another way. Axis or sequence of Axis""" -ShapeDict = Mapping[str, int] -"""ShapeDict is a type that can be used to specify the axes of an array, usually for creation or adding a new axis""" -PartialShapeDict = Mapping[str, Optional[int]] -"""Similar to an AxisSelection, in dict form.""" PartialAxisSpec = Sequence[EllipsisType | AxisSelector] @@ -61,30 +62,28 @@ Some functions may require that the Ellipsis is present at most once, while othe multiple times. """ +_DUMMY = object() + def selects_axis(selector: AxisSelection, selected: AxisSelection) -> bool: """Returns true if the selector has every axis in selected and, if dims are given, that they match""" - if isinstance(selector, Axis) or isinstance(selector, str): - selected = ensure_tuple(selected) - try: - index = index_where(lambda ax: is_axis_compatible(ax, selector), selected) # type: ignore - return index >= 0 - except ValueError: + selector_dict = axis_spec_to_shape_dict(selector) + + selected_dict = axis_spec_to_shape_dict(selected) + + if len(selector_dict) < len(selected_dict): + return False + + for ax, size in selected_dict.items(): + selector_size = selector_dict.get(ax, _DUMMY) + if selector_size is _DUMMY: return False - selector_dict = axis_spec_to_shape_dict(selector) + if selector_size is None or size is None: + continue - selected_tuple = ensure_tuple(selected) # type: ignore - for ax in selected_tuple: - if isinstance(ax, Axis): - selector_size = selector_dict.get(ax.name, _Sentinel) - if selector_size is not None and selector_size != ax.size: - return False - elif isinstance(ax, str): - if ax not in selector_dict: - return False - else: - raise ValueError(f"Invalid axis spec: {ax}") + if selector_size != size: + return False return True @@ -107,18 +106,28 @@ def is_axis_compatible(ax1: AxisSelector, ax2: AxisSelector): @overload -def axis_spec_to_shape_dict(axis_spec: AxisSpec) -> Dict[str, int]: # type: ignore +def axis_spec_to_shape_dict(axis_spec: AxisSpec) -> dict[str, int]: # type: ignore ... @overload -def axis_spec_to_shape_dict(axis_spec: AxisSelection) -> Dict[str, Optional[int]]: # type: ignore +def axis_spec_to_shape_dict(axis_spec: AxisSelection) -> dict[str, Optional[int]]: # type: ignore ... -def axis_spec_to_shape_dict(axis_spec: AxisSelection) -> Dict[str, Optional[int]]: # type: ignore +def axis_spec_to_shape_dict(axis_spec: AxisSelection) -> dict[str, Optional[int]]: # type: ignore + if isinstance(axis_spec, Axis): + return {axis_name(axis_spec): axis_spec.size} + + if isinstance(axis_spec, str): + return {axis_spec: None} + + if isinstance(axis_spec, Mapping): + return dict(**axis_spec) + spec = ensure_tuple(axis_spec) # type: ignore - shape_dict: Dict[str, Optional[int]] = {} + + shape_dict: dict[str, Optional[int]] = {} for ax in spec: if isinstance(ax, Axis): shape_dict[ax.name] = ax.size @@ -130,8 +139,47 @@ def axis_spec_to_shape_dict(axis_spec: AxisSelection) -> Dict[str, Optional[int] return shape_dict -def _dict_to_spec(axis_spec: Mapping[str, Optional[int]]) -> AxisSelection: - return tuple(Axis(name, size) if size is not None else name for name, size in axis_spec.items()) +@typing.overload +def axis_spec_to_tuple(axis_spec: ShapeDict) -> tuple[Axis, ...]: + ... + + +@typing.overload +def axis_spec_to_tuple(axis_spec: AxisSpec) -> tuple[Axis, ...]: + ... + + +@typing.overload +def axis_spec_to_tuple(axis_spec: PartialShapeDict) -> tuple[AxisSelector, ...]: + ... + + +@typing.overload +def axis_spec_to_tuple(axis_spec: AxisSelection) -> tuple[AxisSelector, ...]: + ... + + +def axis_spec_to_tuple(axis_spec: AxisSelection) -> tuple[AxisSelector, ...]: + if isinstance(axis_spec, Mapping): + return tuple(Axis(name, size) if size is not None else name for name, size in axis_spec.items()) + + if isinstance(axis_spec, Axis | str): + return (axis_spec,) + + if isinstance(axis_spec, Sequence): + return tuple(axis_spec) + + raise ValueError(f"Invalid axis spec: {axis_spec}") + + +@overload +def concat_axes(a1: ShapeDict, a2: AxisSpec) -> ShapeDict: + pass + + +@overload +def concat_axes(a1: Sequence[Axis], a2: AxisSpec) -> tuple[Axis, ...]: + pass @overload @@ -144,16 +192,33 @@ def concat_axes(a1: AxisSelection, a2: AxisSelection) -> AxisSelection: pass -def concat_axes(a1: AxisSelection, a2: AxisSelection) -> AxisSelection: - """Concatenates two AxisSpec. Raises ValueError if any axis is present in both specs""" +def concat_axes(a1, a2): + """Concatenates two AxisSpecs. Raises ValueError if any axis is present in both specs""" if isinstance(a1, Axis) and isinstance(a2, Axis): if axis_name(a1) == axis_name(a2): raise ValueError(f"Axis {a1} specified twice") return (a1, a2) + elif isinstance(a1, Mapping): + out = dict(a1) + a2 = axis_spec_to_shape_dict(a2) + for ax, sz in a2.items(): + if ax in a1: + raise ValueError(f"Axis {ax} specified twice") + out[ax] = sz + + return out + elif isinstance(a2, Mapping): + out = axis_spec_to_shape_dict(a1) + for ax, sz in a2.items(): + if ax in out: + raise ValueError(f"Axis {ax} specified twice") + out[ax] = sz + + return axis_spec_to_tuple(out) else: - a1 = ensure_tuple(a1) - a2 = ensure_tuple(a2) + a1 = axis_spec_to_tuple(a1) + a2 = axis_spec_to_tuple(a2) a1_names = [axis_name(ax) for ax in a1] a2_names = [axis_name(ax) for ax in a2] @@ -164,6 +229,16 @@ def concat_axes(a1: AxisSelection, a2: AxisSelection) -> AxisSelection: return a1 + a2 +@typing.overload +def union_axes(a1: ShapeDict, a2: AxisSpec) -> ShapeDict: + ... + + +@typing.overload +def union_axes(a1: AxisSpec, a2: ShapeDict) -> ShapeDict: + ... + + @typing.overload def union_axes(a1: AxisSpec, a2: AxisSpec) -> AxisSpec: ... @@ -181,8 +256,8 @@ def union_axes(a1: AxisSelection, a2: AxisSelection) -> AxisSelection: Raises if any axis is present in both specs with different sizes """ - a1 = ensure_tuple(a1) - a2 = ensure_tuple(a2) + + should_return_dict = isinstance(a1, Mapping) or isinstance(a2, Mapping) a1_dict = axis_spec_to_shape_dict(a1) a2_dict = axis_spec_to_shape_dict(a2) @@ -194,11 +269,19 @@ def union_axes(a1: AxisSelection, a2: AxisSelection) -> AxisSelection: else: a1_dict[ax] = sz - return _dict_to_spec(a1_dict) + if should_return_dict: + return a1_dict + else: + return axis_spec_to_tuple(a1_dict) @overload -def eliminate_axes(axis_spec: AxisSpec, axes: AxisSelection) -> Tuple[Axis, ...]: # type: ignore +def eliminate_axes(axis_spec: Axis | Sequence[Axis], axes: AxisSelection) -> tuple[Axis, ...]: # type: ignore + ... + + +@overload +def eliminate_axes(axis_spec: ShapeDict, axes: AxisSelection) -> ShapeDict: # type: ignore ... @@ -207,41 +290,90 @@ def eliminate_axes(axis_spec: AxisSelection, axes: AxisSelection) -> AxisSelecti ... +@overload +def eliminate_axes(axis_spec: PartialShapeDict, axes: AxisSelection) -> PartialShapeDict: # type: ignore + ... + + def eliminate_axes(axis_spec: AxisSelection, to_remove: AxisSelection) -> AxisSelection: # type: ignore - """Returns a new axis spec that is the same as the original, but without any axes in axes. Raises if any axis in to_remove is - not present in axis_spec""" - to_remove = ensure_tuple(to_remove) + """Returns a new axis spec that is the same as the original, but without any axes in axes. + Raises if any axis in to_remove is not present in axis_spec""" + + should_return_dict = isinstance(axis_spec, Mapping) + axis_spec_dict = axis_spec_to_shape_dict(axis_spec) + to_remove = axis_spec_to_shape_dict(to_remove) for ax in to_remove: name = axis_name(ax) if name not in axis_spec_dict: raise ValueError(f"Axis {name} not present in axis spec {axis_spec}") + _check_size_consistency(axis_spec, to_remove, name, axis_spec_dict[name], to_remove[name]) del axis_spec_dict[name] - return _dict_to_spec(axis_spec_dict) + if should_return_dict: + return axis_spec_dict + else: + return axis_spec_to_tuple(axis_spec_dict) @typing.overload -def without_axes(axis_spec: AxisSpec, to_remove: AxisSelection) -> AxisSpec: # type: ignore +def without_axes(axis_spec: ShapeDict, to_remove: AxisSelection, allow_mismatched_sizes=False) -> ShapeDict: # type: ignore ... @typing.overload -def without_axes(axis_spec: AxisSelection, to_remove: AxisSelection) -> AxisSelection: # type: ignore - """As eliminate_axes, but does not raise if any axis in to_remove is not present in axis_spec""" +def without_axes(axis_spec: Sequence[Axis], to_remove: AxisSelection, allow_mismatched_sizes=False) -> tuple[Axis, ...]: # type: ignore + ... -def without_axes(axis_spec: AxisSelection, to_remove: AxisSelection) -> AxisSelection: # type: ignore +@typing.overload +def without_axes(axis_spec: AxisSpec, to_remove: AxisSelection, allow_mismatched_sizes=False) -> AxisSpec: # type: ignore + ... + + +@typing.overload +def without_axes(axis_spec: AxisSelection, to_remove: AxisSelection, allow_mismatched_sizes=False) -> AxisSelection: # type: ignore """As eliminate_axes, but does not raise if any axis in to_remove is not present in axis_spec""" - to_remove = ensure_tuple(to_remove) + +@typing.overload +def without_axes(axis_spec: Sequence[AxisSelector], to_remove: AxisSelection, allow_mismatched_sizes=False) -> tuple[AxisSpec, ...]: # type: ignore + ... + + +@typing.overload +def without_axes(axis_spec: PartialShapeDict, to_remove: AxisSelection, allow_mismatched_sizes=False) -> PartialShapeDict: # type: ignore + ... + + +def without_axes(axis_spec: AxisSelection, to_remove: AxisSelection, allow_mismatched_sizes=False) -> AxisSelection: # type: ignore + """ + As eliminate_axes, but does not raise if any axis in to_remove is not present in axis_spec. + + However, this does raise if any axis in to_remove is present in axis_spec with a different size. + """ + + to_remove_dict = axis_spec_to_shape_dict(to_remove) + was_dict = isinstance(axis_spec, Mapping) + axis_spec_dict = axis_spec_to_shape_dict(axis_spec) - for ax in to_remove: - name = axis_name(ax) - if name in axis_spec_dict: - del axis_spec_dict[name] - return _dict_to_spec(axis_spec_dict) + for ax, size in to_remove_dict.items(): + if ax in axis_spec_dict: + if not allow_mismatched_sizes and ( + size is not None and axis_spec_dict[ax] is not None and size != axis_spec_dict[ax] + ): + raise ValueError(f"Axis {ax} present in both specs with different sizes: {axis_spec} - {to_remove}") + del axis_spec_dict[ax] + + if was_dict: + return axis_spec_dict + return axis_spec_to_tuple(axis_spec_dict) + + +@typing.overload +def unsize_axes(axis_spec: PartialShapeDict, to_unsize: AxisSelection) -> PartialShapeDict: + ... @typing.overload @@ -249,6 +381,11 @@ def unsize_axes(axis_spec: AxisSelection, to_unsize: AxisSelection) -> AxisSelec ... +@typing.overload +def unsize_axes(axis_spec: PartialShapeDict) -> PartialShapeDict: + ... + + @typing.overload def unsize_axes(axis_spec: AxisSelection) -> AxisSelection: ... @@ -263,9 +400,16 @@ def unsize_axes(axis_spec: AxisSelection, to_unsize: Optional[AxisSelection] = N """ if to_unsize is None: - return tuple(axis_name(ax) for ax in ensure_tuple(axis_spec)) # type: ignore + if isinstance(axis_spec, Mapping): + return {name: None for name in axis_spec} + elif isinstance(axis_spec, Axis | str): + return axis_name(axis_spec) + else: + return tuple(axis_name(ax) for ax in ensure_tuple(axis_spec)) # type: ignore + + was_dict = isinstance(axis_spec, Mapping) - to_unsize = ensure_tuple(to_unsize) + to_unsize = axis_spec_to_shape_dict(to_unsize) axis_spec_dict: dict[str, Optional[int]] = axis_spec_to_shape_dict(axis_spec) # type: ignore for ax in to_unsize: name = axis_name(ax) @@ -273,7 +417,10 @@ def unsize_axes(axis_spec: AxisSelection, to_unsize: Optional[AxisSelection] = N raise ValueError(f"Axis {name} not present in axis spec {axis_spec}") axis_spec_dict[name] = None - return _dict_to_spec(axis_spec_dict) + if was_dict: + return axis_spec_dict + + return axis_spec_to_tuple(axis_spec_dict) @overload @@ -289,73 +436,77 @@ def replace_axis(axis_spec: AxisSelection, old: AxisSelector, new: AxisSelection def replace_axis(axis_spec: AxisSelection, old: AxisSelector, new: AxisSelection) -> AxisSelection: """Returns a new axis spec that is the same as the original, but with any axes in old replaced with new. Raises if old is not present in axis_spec""" - axis_spec = ensure_tuple(axis_spec) - index_of_old = index_where(lambda ax: is_axis_compatible(ax, old), axis_spec) - if index_of_old < 0: - raise ValueError(f"Axis {old} not present in axis spec {axis_spec}") + was_dict = isinstance(axis_spec, Mapping) + axis_spec_dict = axis_spec_to_shape_dict(axis_spec) + new_dict = axis_spec_to_shape_dict(new) + + found = False + out = {} + for ax, size in axis_spec_dict.items(): + if is_axis_compatible(ax, old): + found = True + for new_ax, new_size in new_dict.items(): + if new_ax in axis_spec_dict and new_ax != ax: + raise ValueError( + f"Axis {new_ax} already present in axis spec {axis_spec}. Replacing {ax} with {new_ax} would" + " cause a conflict" + ) + out[new_ax] = new_size + else: + out[ax] = size + + if not found: + raise ValueError(f"Axis {old} not found in axis spec {axis_spec}") + + if was_dict: + return out + + return axis_spec_to_tuple(out) - return axis_spec[:index_of_old] + ensure_tuple(new) + axis_spec[index_of_old + 1 :] # type: ignore + +@overload +def intersect_axes(ax1: ShapeDict, ax2: AxisSelection) -> ShapeDict: + ... @overload -def intersect_axes(ax1: AxisSpec, ax2: AxisSelection) -> Tuple[Axis, ...]: +def intersect_axes(ax1: tuple[AxisSelector, ...], ax2: AxisSpec) -> tuple[Axis, ...]: ... @overload -def intersect_axes(ax1: AxisSelection, ax2: AxisSpec) -> Tuple[Axis, ...]: +def intersect_axes(ax1: tuple[AxisSelector, ...], ax2: AxisSelection) -> tuple[AxisSelector, ...]: # type: ignore ... @overload -def intersect_axes(ax1: AxisSelection, ax2: AxisSelection) -> Tuple[AxisSelector, ...]: +def intersect_axes(ax1: AxisSpec, ax2: AxisSelection) -> AxisSpec: # type: ignore ... -def intersect_axes(ax1: AxisSelection, ax2: AxisSelection) -> Tuple[AxisSelector, ...]: +def intersect_axes(ax1: AxisSelection, ax2: AxisSelection) -> AxisSelection: """Returns a tuple of axes that are present in both ax1 and ax2. The returned order is the same as ax1. """ ax2_dict = axis_spec_to_shape_dict(ax2) out: List[AxisSelector] = [] - ax1 = ensure_tuple(ax1) - - for ax in ax1: - if isinstance(ax, Axis): - if ax.name in ax2_dict: - sz = ax2_dict[ax.name] - if sz is not None and sz != ax.size: - raise ValueError(f"Axis {ax.name} has different sizes in {ax1} and {ax2}") + was_dict = isinstance(ax1, Mapping) + ax1_dict = axis_spec_to_shape_dict(ax1) + + for ax, size in ax1_dict.items(): + if ax in ax2_dict: + sz2 = ax2_dict[ax] + _check_size_consistency(ax1, ax2, ax, size, sz2) + if sz2 is not None: + out.append(Axis(ax, sz2)) + else: out.append(ax) - elif isinstance(ax, str): - if ax in ax2_dict: - ax_sz = ax2_dict[ax] - if ax_sz is not None: - out.append(Axis(ax, ax_sz)) - else: - out.append(ax) - else: - raise ValueError(f"Invalid axis spec: {ax}") - return tuple(out) - - -def overlapping_axes(ax1: AxisSelection, ax2: AxisSelection) -> Tuple[str, ...]: - """ - Like intersect_axes, but returns the names instead of the axes themselves. - Unlike intersect_axes, it does not throw an error if the sizes of a common axis are - different. - - The returned order is the same as in ax1. - """ - ax1 = ensure_tuple(ax1) - ax2 = ensure_tuple(ax2) - ax1_names = map(axis_name, ax1) - ax2_names = set(map(axis_name, ax2)) - - out = tuple(name for name in ax1_names if name in ax2_names) - return out + if was_dict: + return axis_spec_to_shape_dict(out) + else: + return tuple(out) @overload @@ -364,11 +515,11 @@ def axis_name(ax: AxisSelector) -> str: # type: ignore @overload -def axis_name(ax: Sequence[AxisSelector]) -> Tuple[str, ...]: # type: ignore +def axis_name(ax: Sequence[AxisSelector]) -> tuple[str, ...]: # type: ignore ... -def axis_name(ax: AxisSelection) -> Union[str, Tuple[str, ...]]: +def axis_name(ax: AxisSelection) -> Union[str, tuple[str, ...]]: """ Returns the name of the axis. If ax is a string, returns ax. If ax is an Axis, returns ax.name """ @@ -392,8 +543,10 @@ def axis_size(ax: AxisSpec) -> int: if isinstance(ax, Axis): return ax.size + elif isinstance(ax, Mapping): + return prod(ax.values()) else: - return prod(axis.size for axis in ensure_tuple(ax)) # type: ignore + return prod(axis.size for axis in ax) @typing.overload @@ -414,32 +567,34 @@ def resolve_axis(axis_spec: AxisSpec, axis_selection: AxisSelection) -> AxisSpec If an axis is present with a different size, raises ValueError. """ - ax: Axis + as_dict = axis_spec_to_shape_dict(axis_spec) + if isinstance(axis_selection, str | Axis): name = axis_name(axis_selection) - for ax in ensure_tuple(axis_spec): - if axis_name(ax) == name: - if isinstance(axis_selection, Axis) and axis_size(ax) != axis_size(axis_selection): - raise ValueError(f"Axis {name} has different sizes in {axis_spec} and {axis_selection}") - return ax - raise ValueError(f"Axis {name} not found in {axis_spec}") + if name not in as_dict: + raise ValueError(f"Axis {name} not found in {axis_spec}") + + if isinstance(axis_selection, Axis): + _check_size_consistency(axis_spec, axis_selection, name, as_dict[name], axis_size(axis_selection)) + + return Axis(name, as_dict[name]) else: - as_map = axis_spec_to_shape_dict(axis_spec) - out: list[Axis] = [] - - for ax in ensure_tuple(axis_selection): # type: ignore - name = axis_name(ax) - if name not in as_map: - raise ValueError(f"Axis {name} not found in {axis_spec}") - if isinstance(ax, Axis): - if as_map[name] != ax.size: # type: ignore - raise ValueError(f"Axis {name} has different sizes in {axis_spec} and {axis_selection}") - else: - out.append(ax) - else: - out.append(Axis(name, as_map[name])) + out = {} + selection_was_dict = isinstance(axis_selection, Mapping) + select_dict = axis_spec_to_shape_dict(axis_selection) - return tuple(out) + ax: str + for ax, size in select_dict.items(): + if ax not in as_dict: + raise ValueError(f"Axis {ax} not found in {axis_spec}") + _check_size_consistency(axis_spec, axis_selection, ax, as_dict[ax], size) + + out[ax] = as_dict[ax] + + if selection_was_dict: + return out + else: + return axis_spec_to_tuple(out) class dslice(eqx.Module): @@ -577,28 +732,18 @@ def replace_missing_with_ellipsis(ax1: AxisSelection, ax2: AxisSelection) -> Par """ ax2_dict = axis_spec_to_shape_dict(ax2) out: List[AxisSelector | EllipsisType] = [] - ax1 = ensure_tuple(ax1) - - for ax in ax1: - if isinstance(ax, Axis): - if ax.name in ax2_dict: - sz = ax2_dict[ax.name] - if sz is not None and sz != ax.size: - raise ValueError(f"Axis {ax.name} has different sizes in {ax1} and {ax2}") - out.append(ax) - else: - out.append(Ellipsis) - elif isinstance(ax, str): - if ax in ax2_dict: - ax_sz = ax2_dict[ax] - if ax_sz is not None: - out.append(Axis(ax, ax_sz)) - else: - out.append(ax) + ax1_dict = axis_spec_to_shape_dict(ax1) + + for ax, size in ax1_dict.items(): + if ax in ax2_dict: + sz2 = ax2_dict[ax] + _check_size_consistency(ax1, ax2, ax, size, sz2) + if sz2 is not None: + out.append(Axis(ax, sz2)) else: - out.append(Ellipsis) + out.append(ax) else: - raise ValueError(f"Invalid axis spec: {ax}") + out.append(Ellipsis) return tuple(out) @@ -622,7 +767,6 @@ __all__ = [ "eliminate_axes", "intersect_axes", "is_axis_compatible", - "overlapping_axes", "replace_axis", "resolve_axis", "selects_axis", @@ -631,3 +775,18 @@ __all__ = [ "unsize_axes", "rearrange_for_partial_order", ] + + +def _check_size_consistency( + spec1: AxisSelection, spec2: AxisSelection, name: str, size1: int | None, size2: int | None +): + if size1 is not None and size2 is not None and size1 != size2: + raise ValueError(f"Axis {name} has different sizes in {spec1} and {spec2}: {size1} != {size2}") + + +def to_jax_shape(shape: AxisSpec): + if isinstance(shape, Axis): + return shape.size + elif isinstance(shape, Sequence): + return tuple(s.size for s in shape) + return tuple(shape[a] for a in shape) diff --git a/src/haliax/core.py b/src/haliax/core.py index 44537fb..3c50b92 100644 --- a/src/haliax/core.py +++ b/src/haliax/core.py @@ -17,7 +17,19 @@ from haliax.jax_utils import is_jax_array_like, is_pallas_dslice from haliax.util import ensure_tuple from ._src.util import index_where, py_slice, slice_t -from .axis import Axis, AxisSelection, AxisSelector, AxisSpec, axis_name, dslice, eliminate_axes, selects_axis +from .axis import ( + Axis, + AxisSelection, + AxisSelector, + AxisSpec, + PartialShapeDict, + ShapeDict, + axis_name, + axis_spec_to_tuple, + dslice, + eliminate_axes, + selects_axis, +) from .types import GatherScatterModeStr, IntScalar, PrecisionLike, Scalar @@ -192,11 +204,14 @@ class NamedArrayMeta(type): @dataclass(frozen=True) class NamedArray(metaclass=NamedArrayMeta): array: jnp.ndarray - axes: Tuple[Axis, ...] + axes: tuple[Axis, ...] + + def __init__(self, array: jnp.ndarray, axes: AxisSpec): + object.__setattr__(self, "array", array) + if isinstance(axes, Mapping): + axes = tuple(Axis(name, size) for name, size in axes.items()) + object.__setattr__(self, "axes", ensure_tuple(axes)) - def __post_init__(self): - if not isinstance(self.axes, tuple): - object.__setattr__(self, "axes", tuple(self.axes)) # ensure axes are all Axis objects # TODO: anonymous positional axes? for axis in self.axes: @@ -218,7 +233,7 @@ class NamedArray(metaclass=NamedArrayMeta): if s != tuple(a.size for a in self.axes): raise ValueError(f"Shape of underlying array {s} does not match shape of axes {self.axes}") - def item(self): + def item(self): # pragma: no cover """Returns the value of this NamedArray as a python scalar.""" return self.array.item() @@ -340,17 +355,25 @@ class NamedArray(metaclass=NamedArrayMeta): return tuple(result) @overload - def resolve_axis(self, axis: AxisSelector) -> Axis: # type: ignore + def resolve_axis(self, axis: AxisSelector) -> Axis: + ... + + @overload + def resolve_axis(self, axis: tuple[AxisSelector, ...]) -> tuple[Axis, ...]: ... @overload - def resolve_axis(self, axis: Sequence[AxisSelector]) -> Tuple[Axis, ...]: # type: ignore + def resolve_axis(self, axis: PartialShapeDict) -> ShapeDict: ... - def resolve_axis(self, axes: AxisSelection) -> AxisSpec: # type: ignore + @overload + def resolve_axis(self, axes: AxisSelection) -> AxisSpec: + ... + + def resolve_axis(self, axes: AxisSelection) -> AxisSpec: # type: ignore[misc] """ Returns the axes corresponding to the given axis selection. - That is, it return the [haliax.Axis][] values themselves, not just their names. + That is, it returns the [haliax.Axis][] values themselves, not just their names. Raises a ValueError if any of the axes are not found. """ @@ -359,14 +382,21 @@ class NamedArray(metaclass=NamedArrayMeta): return self.axes[indices] elif indices is None: raise ValueError(f"Axis {axes} not found") + elif isinstance(axes, Mapping): + result = {} + for key, i in zip(axes.keys(), indices): + if i is None: + raise ValueError(f"Axis {key} not found") + result[key] = self.axes[i].size + return result else: - result = [] + result_list = [] assert isinstance(axes, Sequence) for i, ax in zip(indices, axes): if i is None: raise ValueError(f"Axis {ax} not found in {self.shape}") - result.append(self.axes[i]) - return tuple(result) + result_list.append(self.axes[i]) + return tuple(result_list) def __str__(self): # we consider the following cases: @@ -397,7 +427,7 @@ class NamedArray(metaclass=NamedArrayMeta): ... @overload - def _lookup_indices(self, axis: Sequence[AxisSelector]) -> Tuple[Optional[int], ...]: + def _lookup_indices(self, axis: AxisSelection) -> Tuple[Optional[int], ...]: ... def _lookup_indices(self, axis: AxisSelection) -> Union[Optional[int], Tuple[Optional[int], ...]]: @@ -421,6 +451,10 @@ class NamedArray(metaclass=NamedArrayMeta): def axis_indices(self, axis: Sequence[AxisSelector]) -> Tuple[Optional[int], ...]: ... + @overload + def axis_indices(self, axis: AxisSelection) -> Tuple[Optional[int], ...]: + ... + def axis_indices(self, axis: AxisSelection) -> Union[Optional[int], Tuple[Optional[int], ...]]: """ For a single axis, returns an int corresponding to the index of the axis. @@ -447,11 +481,6 @@ class NamedArray(metaclass=NamedArrayMeta): return index_where(lambda a: a.name == axis, self.axes) except ValueError: return None - elif isinstance(axis, str): - try: - return index_where(lambda a: a.name == axis, self.axes) - except ValueError: - return None else: return tuple(self.axis_indices(a) for a in axis) @@ -466,36 +495,35 @@ class NamedArray(metaclass=NamedArrayMeta): """See [haliax.rearrange][] for details.""" pass - def rearrange(self, *args, **kwargs) -> "NamedArray": + def rearrange(self, *args, **kwargs) -> "NamedArray": # pragma: no cover """See [haliax.rearrange][] for details.""" return haliax.rearrange(self, *args, **kwargs) - def broadcast_to(self, axes: AxisSpec) -> "NamedArray": - axes = ensure_tuple(axes) + def broadcast_to(self, axes: AxisSpec) -> "NamedArray": # pragma: no cover return haliax.broadcast_to(self, axes=axes) - def broadcast_axis(self, axis: AxisSpec) -> "NamedArray": + def broadcast_axis(self, axis: AxisSpec) -> "NamedArray": # pragma: no cover return haliax.broadcast_axis(self, axis=axis) - def split(self, axis: AxisSelector, new_axes: Sequence[Axis]) -> Sequence["NamedArray"]: + def split(self, axis: AxisSelector, new_axes: Sequence[Axis]) -> Sequence["NamedArray"]: # pragma: no cover return haliax.split(self, axis=axis, new_axes=new_axes) - def flatten_axes(self, old_axes: AxisSelection, new_axis: AxisSelector) -> "NamedArray": + def flatten_axes(self, old_axes: AxisSelection, new_axis: AxisSelector) -> "NamedArray": # pragma: no cover return haliax.flatten_axes(self, old_axes=old_axes, new_axis=new_axis) - def unflatten_axis(self, axis: AxisSelector, new_axes: AxisSpec) -> "NamedArray": + def unflatten_axis(self, axis: AxisSelector, new_axes: AxisSpec) -> "NamedArray": # pragma: no cover return haliax.unflatten_axis(self, axis=axis, new_axes=new_axes) - def ravel(self, new_axis_name: AxisSelector) -> "NamedArray": + def ravel(self, new_axis_name: AxisSelector) -> "NamedArray": # pragma: no cover return haliax.ravel(self, new_axis_name=new_axis_name) - def flatten(self, new_axis_name: AxisSelector) -> "NamedArray": + def flatten(self, new_axis_name: AxisSelector) -> "NamedArray": # pragma: no cover return haliax.flatten(self, new_axis_name=new_axis_name) - def unbind(self, axis: AxisSelector) -> Sequence["NamedArray"]: + def unbind(self, axis: AxisSelector) -> Sequence["NamedArray"]: # pragma: no cover return haliax.unbind(self, axis=axis) - def rename(self, renames: Mapping[AxisSelector, AxisSelector]) -> "NamedArray": + def rename(self, renames: Mapping[AxisSelector, AxisSelector]) -> "NamedArray": # pragma: no cover return haliax.rename(self, renames=renames) # slicing @@ -511,21 +539,25 @@ class NamedArray(metaclass=NamedArrayMeta): ) -> "NamedArray": ... - def slice(self, *args, **kwargs) -> "NamedArray": + def slice(self, *args, **kwargs) -> "NamedArray": # pragma: no cover return haliax.slice(self, *args, **kwargs) def updated_slice( self, start: Mapping[AxisSelector, Union[int, "NamedArray"]], update: "NamedArray" - ) -> "NamedArray": + ) -> "NamedArray": # pragma: no cover return haliax.updated_slice(self, start=start, update=update) - def take(self, axis: AxisSelector, index: Union[int, "NamedArray"]) -> "NamedArray": + def take(self, axis: AxisSelector, index: Union[int, "NamedArray"]) -> "NamedArray": # pragma: no cover return haliax.take(self, axis=axis, index=index) @property - def at(self) -> "_NamedIndexUpdateHelper": + def at(self) -> "_NamedIndexUpdateHelper": # pragma: no cover """ Named analog of [jax's at method](https://jax.readthedocs.io/en/latest/_autosummary/jax.numpy.ndarray.at.html). + The at[...].set(...) pattern is a functional way to update elements of an array. + + This is just the named version, using the same indexing syntax we use for slicing and + the JAX syntax for at etc. Docs from the JAX docs: @@ -589,40 +621,44 @@ class NamedArray(metaclass=NamedArrayMeta): return index(self, idx_dict) # np.ndarray methods: - def all(self, axis: Optional[AxisSelection] = None, *, where: Optional["NamedArray"] = None) -> "NamedArray": + def all( + self, axis: Optional[AxisSelection] = None, *, where: Optional["NamedArray"] = None + ) -> "NamedArray": # pragma: no cover return haliax.all(self, axis=axis, where=where) - def any(self, axis: Optional[AxisSelection] = None, *, where: Optional["NamedArray"] = None) -> "NamedArray": + def any( + self, axis: Optional[AxisSelection] = None, *, where: Optional["NamedArray"] = None + ) -> "NamedArray": # pragma: no cover return haliax.any(self, axis=axis, where=where) - def argmax(self, axis: Optional[AxisSelector] = None) -> "NamedArray": + def argmax(self, axis: Optional[AxisSelector] = None) -> "NamedArray": # pragma: no cover return haliax.argmax(self, axis=axis) - def argmin(self, axis: Optional[AxisSelector]) -> "NamedArray": + def argmin(self, axis: Optional[AxisSelector]) -> "NamedArray": # pragma: no cover return haliax.argmin(self, axis=axis) - def argsort(self, axis: AxisSelector) -> "NamedArray": + def argsort(self, axis: AxisSelector) -> "NamedArray": # pragma: no cover return haliax.argsort(self, axis=axis) - def astype(self, dtype) -> "NamedArray": + def astype(self, dtype) -> "NamedArray": # pragma: no cover return NamedArray(self.array.astype(dtype), self.axes) - def clip(self, a_min=None, a_max=None) -> Any: + def clip(self, a_min=None, a_max=None) -> Any: # pragma: no cover return haliax.clip(self, a_min=a_min, a_max=a_max) - def conj(self) -> "NamedArray": + def conj(self) -> "NamedArray": # pragma: no cover return NamedArray(self.array.conj(), self.axes) - def conjugate(self) -> "NamedArray": + def conjugate(self) -> "NamedArray": # pragma: no cover return NamedArray(self.array.conjugate(), self.axes) - def copy(self) -> "NamedArray": + def copy(self) -> "NamedArray": # pragma: no cover return NamedArray(self.array.copy(), self.axes) - def cumprod(self, axis: AxisSelector, *, dtype=None) -> "NamedArray": + def cumprod(self, axis: AxisSelector, *, dtype=None) -> "NamedArray": # pragma: no cover return haliax.cumprod(self, axis=axis, dtype=dtype) - def cumsum(self, axis: AxisSelector, *, dtype=None) -> "NamedArray": + def cumsum(self, axis: AxisSelector, *, dtype=None) -> "NamedArray": # pragma: no cover return haliax.cumsum(self, axis=axis, dtype=dtype) # Deprecated overload @@ -652,51 +688,53 @@ class NamedArray(metaclass=NamedArrayMeta): return haliax.dot(axis, self, *args, **kwargs) @property - def imag(self) -> "NamedArray": + def imag(self) -> "NamedArray": # pragma: no cover return NamedArray(self.array.imag, self.axes) - def max(self, axis: Optional[AxisSelection] = None, *, where=None) -> "NamedArray": + def max(self, axis: Optional[AxisSelection] = None, *, where=None) -> "NamedArray": # pragma: no cover return haliax.max(self, axis=axis, where=where) def mean( self, axis: Optional[AxisSelection] = None, *, dtype=None, where: Optional["NamedArray"] = None - ) -> "NamedArray": + ) -> "NamedArray": # pragma: no cover return haliax.mean(self, axis=axis, dtype=dtype, where=where) - def min(self, axis: Optional[AxisSelection] = None, *, where: Optional["NamedArray"] = None) -> "NamedArray": + def min( + self, axis: Optional[AxisSelection] = None, *, where: Optional["NamedArray"] = None + ) -> "NamedArray": # pragma: no cover return haliax.min(self, axis=axis, where=where) def prod( self, axis: Optional[AxisSelection] = None, *, dtype=None, where: Optional["NamedArray"] = None - ) -> "NamedArray": + ) -> "NamedArray": # pragma: no cover return haliax.prod(self, axis=axis, dtype=dtype, where=where) def product( self, axis: Optional[AxisSelection] = None, *, dtype=None, where: Optional["NamedArray"] = None - ) -> "NamedArray": + ) -> "NamedArray": # pragma: no cover return haliax.product(self, axis=axis, dtype=dtype, where=where) - def ptp(self, axis: Optional[AxisSelection] = None) -> "NamedArray": + def ptp(self, axis: Optional[AxisSelection] = None) -> "NamedArray": # pragma: no cover return haliax.ptp(self, axis=axis) @property - def real(self) -> "NamedArray": + def real(self) -> "NamedArray": # pragma: no cover return NamedArray(self.array.real, self.axes) - def round(self, decimals=0) -> "NamedArray": + def round(self, decimals=0) -> "NamedArray": # pragma: no cover return haliax.round(self, decimals=decimals) - def sort(self, axis: AxisSelector) -> Any: + def sort(self, axis: AxisSelector) -> Any: # pragma: no cover return haliax.sort(self, axis=axis) def std( self, axis: Optional[AxisSelection] = None, *, dtype=None, ddof=0, where: Optional["NamedArray"] = None - ) -> "NamedArray": + ) -> "NamedArray": # pragma: no cover return haliax.std(self, axis=axis, dtype=dtype, ddof=ddof, where=where) def sum( self, axis: Optional[AxisSelection] = None, *, dtype=None, where: Optional["NamedArray"] = None - ) -> "NamedArray": + ) -> "NamedArray": # pragma: no cover return haliax.sum( self, axis=axis, @@ -704,159 +742,161 @@ class NamedArray(metaclass=NamedArrayMeta): where=where, ) - def tobytes(self, order="C") -> Any: + def tobytes(self, order="C") -> Any: # pragma: no cover return self.array.tobytes(order=order) - def tolist(self) -> Any: + def tolist(self) -> Any: # pragma: no cover return self.array.tolist() - def trace(self, axis1: AxisSelector, axis2: AxisSelector, offset=0, dtype=None) -> "NamedArray": + def trace( + self, axis1: AxisSelector, axis2: AxisSelector, offset=0, dtype=None + ) -> "NamedArray": # pragma: no cover return haliax.trace(self, offset=offset, axis1=axis1, axis2=axis2, dtype=dtype) def var( self, axis: Optional[AxisSelection] = None, dtype=None, ddof=0, *, where: Optional["NamedArray"] = None - ) -> "NamedArray": + ) -> "NamedArray": # pragma: no cover return haliax.var(self, axis=axis, dtype=dtype, ddof=ddof, where=where) # operators # Comparisons - def __lt__(self, other) -> "NamedArray": + def __lt__(self, other) -> "NamedArray": # pragma: no cover return haliax.less(self, other) - def __le__(self, other) -> "NamedArray": + def __le__(self, other) -> "NamedArray": # pragma: no cover return haliax.less_equal(self, other) - def __eq__(self, other): + def __eq__(self, other): # pragma: no cover # special case because Jax sometimes call == on # types when they're in PyTrees - if self.array is None: + if self.array is None: # pragma: no cover return other.array is None - if hasattr(other, "array") and other.array is None: + if hasattr(other, "array") and other.array is None: # pragma: no cover return False return haliax.equal(self, other) - def __ne__(self, other): + def __ne__(self, other): # pragma: no cover return haliax.not_equal(self, other) - def __gt__(self, other) -> "NamedArray": + def __gt__(self, other) -> "NamedArray": # pragma: no cover return haliax.greater(self, other) - def __ge__(self, other) -> "NamedArray": + def __ge__(self, other) -> "NamedArray": # pragma: no cover return haliax.greater_equal(self, other) # Unary arithmetic - def __neg__(self) -> "NamedArray": + def __neg__(self) -> "NamedArray": # pragma: no cover return haliax.negative(self) - def __pos__(self) -> "NamedArray": + def __pos__(self) -> "NamedArray": # pragma: no cover return haliax.positive(self) - def __abs__(self) -> "NamedArray": + def __abs__(self) -> "NamedArray": # pragma: no cover return haliax.absolute(self) - def __invert__(self) -> "NamedArray": + def __invert__(self) -> "NamedArray": # pragma: no cover return haliax.invert(self) # Binary arithmetic - def __add__(self, other) -> "NamedArray": + def __add__(self, other) -> "NamedArray": # pragma: no cover return haliax.add(self, other) - def __sub__(self, other) -> "NamedArray": + def __sub__(self, other) -> "NamedArray": # pragma: no cover return haliax.subtract(self, other) - def __mul__(self, other) -> "NamedArray": + def __mul__(self, other) -> "NamedArray": # pragma: no cover return haliax.multiply(self, other) - def __matmul__(self, other) -> "NamedArray": + def __matmul__(self, other) -> "NamedArray": # pragma: no cover raise ValueError("matmul is too ambiguous with NamedArrays. Use dot instead.") - def __truediv__(self, other) -> "NamedArray": + def __truediv__(self, other) -> "NamedArray": # pragma: no cover return haliax.true_divide(self, other) - def __floordiv__(self, other) -> "NamedArray": + def __floordiv__(self, other) -> "NamedArray": # pragma: no cover return haliax.floor_divide(self, other) - def __mod__(self, other) -> "NamedArray": + def __mod__(self, other) -> "NamedArray": # pragma: no cover return haliax.mod(self, other) - def __divmod__(self, other) -> "NamedArray": + def __divmod__(self, other) -> "NamedArray": # pragma: no cover return haliax.divmod(self, other) - def __pow__(self, other) -> "NamedArray": + def __pow__(self, other) -> "NamedArray": # pragma: no cover return haliax.power(self, other) - def __lshift__(self, other) -> "NamedArray": + def __lshift__(self, other) -> "NamedArray": # pragma: no cover return haliax.left_shift(self, other) - def __rshift__(self, other) -> "NamedArray": + def __rshift__(self, other) -> "NamedArray": # pragma: no cover return haliax.right_shift(self, other) - def __and__(self, other) -> "NamedArray": + def __and__(self, other) -> "NamedArray": # pragma: no cover return haliax.bitwise_and(self, other) - def __xor__(self, other) -> "NamedArray": + def __xor__(self, other) -> "NamedArray": # pragma: no cover return haliax.bitwise_xor(self, other) - def __or__(self, other) -> "NamedArray": + def __or__(self, other) -> "NamedArray": # pragma: no cover return haliax.bitwise_or(self, other) - def __radd__(self, other) -> "NamedArray": + def __radd__(self, other) -> "NamedArray": # pragma: no cover return haliax.add(other, self) - def __rsub__(self, other) -> "NamedArray": + def __rsub__(self, other) -> "NamedArray": # pragma: no cover return haliax.subtract(other, self) - def __rmul__(self, other) -> "NamedArray": + def __rmul__(self, other) -> "NamedArray": # pragma: no cover return haliax.multiply(other, self) - def __rmatmul__(self, other): + def __rmatmul__(self, other): # pragma: no cover raise ValueError("Matrix multiplication is too ambiguous with NamedArrays. Use dot instead.") - def __rtruediv__(self, other) -> "NamedArray": + def __rtruediv__(self, other) -> "NamedArray": # pragma: no cover return haliax.true_divide(other, self) - def __rfloordiv__(self, other) -> "NamedArray": + def __rfloordiv__(self, other) -> "NamedArray": # pragma: no cover return haliax.floor_divide(other, self) - def __rmod__(self, other) -> "NamedArray": + def __rmod__(self, other) -> "NamedArray": # pragma: no cover return haliax.mod(other, self) - def __rdivmod__(self, other) -> "NamedArray": + def __rdivmod__(self, other) -> "NamedArray": # pragma: no cover return haliax.divmod(other, self) - def __rpow__(self, other) -> "NamedArray": + def __rpow__(self, other) -> "NamedArray": # pragma: no cover return haliax.power(other, self) - def __rlshift__(self, other) -> "NamedArray": + def __rlshift__(self, other) -> "NamedArray": # pragma: no cover return haliax.left_shift(other, self) - def __rrshift__(self, other) -> "NamedArray": + def __rrshift__(self, other) -> "NamedArray": # pragma: no cover return haliax.right_shift(other, self) - def __rand__(self, other) -> "NamedArray": + def __rand__(self, other) -> "NamedArray": # pragma: no cover return haliax.bitwise_and(other, self) - def __rxor__(self, other) -> "NamedArray": + def __rxor__(self, other) -> "NamedArray": # pragma: no cover return haliax.bitwise_xor(other, self) - def __ror__(self, other) -> "NamedArray": + def __ror__(self, other) -> "NamedArray": # pragma: no cover return haliax.bitwise_or(other, self) - def __bool__(self) -> bool: + def __bool__(self) -> bool: # pragma: no cover return bool(self.array) - def __complex__(self) -> complex: + def __complex__(self) -> complex: # pragma: no cover return complex(self.array) - def __int__(self) -> int: + def __int__(self) -> int: # pragma: no cover return int(self.array) - def __float__(self) -> float: + def __float__(self) -> float: # pragma: no cover return float(self.array) @@ -1106,7 +1146,7 @@ def updated_slice( # we need to broadcast the update array to the same axis names as the array we're updating, adding them as necessary if update.ndim > 0: # if there are any axes in update that are not in array, it is an error: - axes_in_update = haliax.axis.without_axes(update.axes, array.axes) + axes_in_update = haliax.axis.without_axes(update.axes, array.axes, allow_mismatched_sizes=True) if axes_in_update: raise ValueError( f"Update array with shape {update.shape} has axes {axes_in_update} that are not in the original array" @@ -1441,10 +1481,10 @@ def _simple_flatten(axis: AxisSpec, new_axis: AxisSelector) -> Axis: def _full_flatten( array: NamedArray | AxisSpec, old_axes: AxisSelection, new_axis: AxisSelector ) -> NamedArray | AxisSpec: - if isinstance(array, str | Axis | Sequence): + if isinstance(array, str | Axis | Sequence | Mapping): return _flatten_axis_spec(array, old_axes, new_axis) - old_axes = ensure_tuple(old_axes) + old_axes = axis_spec_to_tuple(old_axes) old_axes = array.resolve_axis(old_axes) total_axis_size = haliax.axis_size(old_axes) @@ -1483,8 +1523,8 @@ def _full_flatten( def _flatten_axis_spec(axes: AxisSpec, old_axes: AxisSelection, new_axis: AxisSelector) -> AxisSpec: - axes = ensure_tuple(axes) - old_axes = ensure_tuple(old_axes) + axes = axis_spec_to_tuple(axes) + old_axes = axis_spec_to_tuple(old_axes) old_axes = haliax.axis.resolve_axis(axes, old_axes) total_axis_size = haliax.axis_size(old_axes) @@ -1528,7 +1568,7 @@ def unflatten_axis(array: NamedArray, axis: AxisSelector, new_axes: AxisSpec) -> axis_size = array.axes[old_index].size - new_axes = ensure_tuple(new_axes) + new_axes = axis_spec_to_tuple(new_axes) if len(new_axes) == 0: if axis_size == 1: @@ -1636,7 +1676,7 @@ def broadcast_to( If enforce_no_extra_axes is True and the array has axes that are not in axes, then a ValueError is raised. """ - axes = ensure_tuple(axes) + axes = axis_spec_to_tuple(axes) if not isinstance(a, NamedArray): a = named(jnp.asarray(a), ()) @@ -1791,7 +1831,7 @@ def broadcast_axis(a: NamedArray, axis: AxisSpec) -> NamedArray: def check_shape(jnp_shape: Sequence[int], hax_axes: AxisSelection) -> Tuple[Axis, ...]: """Check that the shape of a jax array matches the axes of a NamedArray""" - axes: Tuple[AxisSelector, ...] = ensure_tuple(hax_axes) + axes = axis_spec_to_tuple(hax_axes) if len(jnp_shape) != len(axes): raise ValueError(f"Shape mismatch: jnp_shape={jnp_shape} hax_axes={hax_axes}") result_axes: List[Axis] = [] @@ -1908,6 +1948,22 @@ class _NamedIndexUpdateRef: ) return NamedArray(new_array, self._array.axes) + def mul( + self, + update: NamedOrNumeric, + *, + indices_are_sorted: bool = False, + unique_indices: bool = False, + mode: Optional[GatherScatterModeStr] = None, + ) -> NamedArray: + slices, sliced_axes = _raw_indices_for_at(self._array, self._slices) + + update = haliax.broadcast_to(update, sliced_axes, enforce_no_extra_axes=True) + new_array = self._array.array.at[tuple(slices)].mul( + update.array, indices_are_sorted=indices_are_sorted, unique_indices=unique_indices, mode=mode + ) + return NamedArray(new_array, self._array.axes) + def multiply( self, update: NamedOrNumeric, diff --git a/src/haliax/hof.py b/src/haliax/hof.py index 00144f0..f386f3c 100644 --- a/src/haliax/hof.py +++ b/src/haliax/hof.py @@ -19,7 +19,7 @@ from ._src.scan import ( map, scan, ) -from .axis import Axis, AxisSelection, AxisSelector, selects_axis +from .axis import Axis, AxisSelection, AxisSelector, axis_spec_to_shape_dict, axis_spec_to_tuple, selects_axis from .core import NamedArray from .jax_utils import Static, broadcast_prefix, is_jax_array_like from .partitioning import physical_axis_name @@ -55,14 +55,17 @@ def vmap( if kwargs is None: kwargs = {} - axes = ensure_tuple(axis) # type: ignore + axes = axis_spec_to_shape_dict(axis) if len(axes) > 1: mapped = fn for ax in reversed(axes): + size = axes.get(ax, None) + if size is not None: + ax = Axis(ax, size) # type: ignore mapped = vmap(mapped, ax, default=default, args=args, kwargs=kwargs) return mapped elif len(axes) == 1: # type: ignore - axis = axes[0] + axis = axis_spec_to_tuple(axis)[0] else: return fn diff --git a/src/haliax/nn/activations.py b/src/haliax/nn/activations.py index 8f16f0a..f130411 100644 --- a/src/haliax/nn/activations.py +++ b/src/haliax/nn/activations.py @@ -82,7 +82,7 @@ def gelu(a: A, approximate: bool = True) -> A: def glu(x: NamedArray, axis: Axis) -> NamedArray: axis_index = x.axes.index(axis) - return jnn.glu(x.array, axis_index) + return NamedArray(jnn.glu(x.array, axis_index), x.axes) def quick_gelu(x): diff --git a/src/haliax/nn/attention.py b/src/haliax/nn/attention.py index bb448ce..560bee3 100644 --- a/src/haliax/nn/attention.py +++ b/src/haliax/nn/attention.py @@ -8,7 +8,7 @@ from jaxtyping import PRNGKeyArray import haliax import haliax.random as hrandom -from haliax.axis import Axis, AxisSelection, AxisSelector, AxisSpec, axis_name +from haliax.axis import Axis, AxisSelection, AxisSelector, AxisSpec, axis_name, axis_spec_to_shape_dict from haliax.core import NamedArray from haliax.types import PrecisionLike from haliax.util import ensure_tuple @@ -108,7 +108,8 @@ def dot_product_attention( f"query must be a NamedArray, got {type(query)}. Probably you are still using the old signature" "of dot_product_attention. It no longer takes a QPos argument." ) - KPos = ensure_tuple(key.resolve_axis(KPos)) + KPos = axis_spec_to_shape_dict(KPos) + KPos = key.resolve_axis(KPos) # any axis in KPos that's in query is a problem for axis in KPos: if query.has_axis(axis): @@ -123,56 +124,6 @@ def dot_product_attention( return haliax.dot(weights, value, axis=KPos) -def self_attention( - Pos: AxisSelection, - Key: AxisSelector, - query: NamedArray, - key: NamedArray, - value: NamedArray, - is_causal: bool, # make people be explicit about this - mask: Optional[NamedArray] = None, - bias: Optional[NamedArray] = None, - attention_dtype: Optional[jnp.dtype] = None, - precision: PrecisionLike = None, -) -> NamedArray: - """ - Convenience function for self attention. This is just a wrapper around dot_product_attention that makes sure - the query and key axes are distinct. This is a common mistake and it's better to catch it early. - - Note that mask and bias's Pos axis/axes should be key axes, not query axes. You can't use - query axes in a mask/bias with this method. Use dot_product_attention directly if you need to do that. - As an exception, if is_causal is True, then we create a causal mask for you. - - Args: - Pos: Axis of sequence length - Key: Axis of head dimension - query: NamedArray of shape {..., Pos, KeySize} - key: NamedArray of shape {..., Pos, KeySize} - value: NamedArray of shape {..., Pos, KeySize} - is_causal: whether to use a causal mask - mask: Optional[NamedArray] broadcast compatible with (KeySize, Pos, Pos). Should be boolean - bias: Optional[NamedArray] broadcast compatible with (KeySize, Pos, Pos). Should be float - attention_dtype: Optional dtype to use for attention - precision: PrecisionLike for dot product. See precision argument to jax.lax.dot_general - """ - Pos = ensure_tuple(key.resolve_axis(Pos)) - - # rename key/value length axes if necessary - QPos, renames = _get_query_pos_renames(Pos) - - query = query.rename(renames) - - if is_causal: - # require that QPos is a single axis - if len(Pos) != 1: - raise ValueError("QPos must be a single axis for causal self attention") - mask = causal_mask(QPos[0], Pos[0]) - - out = dot_product_attention(Pos, Key, query, key, value, mask, bias, attention_dtype, precision) - # now rename back - return out.rename({v: k for k, v in renames.items()}) - - def _get_query_pos_renames(Pos): new_Pos: list[Axis] = [] renames: dict[str, str] = {} diff --git a/src/haliax/nn/conv.py b/src/haliax/nn/conv.py index a1ea779..6dec83e 100644 --- a/src/haliax/nn/conv.py +++ b/src/haliax/nn/conv.py @@ -9,7 +9,16 @@ from jaxtyping import PRNGKeyArray import haliax.partitioning -from ..axis import Axis, AxisSelection, axis_name, replace_axis, selects_axis, without_axes +from ..axis import ( + Axis, + AxisSelection, + axis_name, + axis_spec_to_shape_dict, + replace_axis, + selects_axis, + unsize_axes, + without_axes, +) from ..core import NamedArray, named from ..jax_utils import named_call from ..random import uniform @@ -127,7 +136,7 @@ class Conv(_ConvBase): use_bias: Whether to add a bias after the convolution. key: Random key """ - Spatial = ensure_tuple(Spatial) + Spatial = axis_spec_to_shape_dict(Spatial) if len(Spatial) == 0: raise ValueError("Spatial must have at least one element") @@ -191,7 +200,7 @@ class Conv(_ConvBase): # identify batch dims, which get special treatment # jax's conv_general_dilated only supports exactly one batch dimension (not 0), so we vmap over any others. # We could choose instead to flatten them, but then we'd definitely lose sharding. - batch_dims = without_axes(inputs.axes, self.weight.axes) + batch_dims = without_axes(inputs.axes, unsize_axes(self.weight.axes)) flat_inputs, unflatten = haliax.core.flatten_all_axes_but( inputs, "__batch__", batch_dims, reorder_to_front=True ) @@ -275,7 +284,7 @@ class ConvTranspose(_ConvBase): """ k_w, k_b = jax.random.split(key, 2) - Spatial = ensure_tuple(Spatial) + Spatial = axis_spec_to_shape_dict(Spatial) kernel_size = _expand_and_check_shape(len(Spatial), kernel_size, "kernel_size") stride = _expand_and_check_shape(len(Spatial), stride, "stride") @@ -325,7 +334,7 @@ class ConvTranspose(_ConvBase): """ del key - batch_dims = without_axes(inputs.axes, self.weight.axes) + batch_dims = without_axes(inputs.axes, unsize_axes(self.weight.axes)) flat_inputs, unflatten = haliax.core.flatten_all_axes_but( inputs, "__batch__", batch_dims, reorder_to_front=True ) diff --git a/src/haliax/nn/embedding.py b/src/haliax/nn/embedding.py index 079007b..04ba8ec 100644 --- a/src/haliax/nn/embedding.py +++ b/src/haliax/nn/embedding.py @@ -8,7 +8,7 @@ from jaxtyping import PRNGKeyArray import haliax as hax -from ..axis import Axis, AxisSpec +from ..axis import Axis, AxisSpec, concat_axes from ..core import NamedArray from ..jax_utils import named_call from ..tree_util import resize_axis @@ -42,7 +42,7 @@ class Embedding(eqx.Module): warnings.warn("initializer_range is deprecated. Use init_std instead.", DeprecationWarning) init_scale = initializer_range - all_axes = (Vocab,) + ensure_tuple(Embed) + all_axes = concat_axes(Vocab, Embed) output_size = hax.axis_size(Embed) weight = hax.random.truncated_normal(key, all_axes, -3, 3) * (init_scale / output_size) return Embedding(weight=weight, Vocab=Vocab, Embed=Embed) diff --git a/src/haliax/nn/pool.py b/src/haliax/nn/pool.py index 8c3c048..178ff17 100644 --- a/src/haliax/nn/pool.py +++ b/src/haliax/nn/pool.py @@ -52,15 +52,14 @@ def pool( Returns: The output of the reduction for each window slice. """ - Window = ensure_tuple(Window) + Window = axis_spec_to_shape_dict(Window) reduce_fn = _patch_up_reduce_fn(reduce_fn) - window_map = axis_spec_to_shape_dict(Window) dims = [] for ax in inputs.axes: - if ax.name in window_map: - dims.append(window_map[ax.name]) + if ax.name in Window: + dims.append(Window[ax.name]) else: dims.append(1) @@ -71,7 +70,7 @@ def pool( if len(Window) != len(stride): raise ValueError(f"len(Window) ({len(Window)}) != len(stride) ({len(stride)})") stride = ensure_tuple(stride) - stride_map = {w.name: s for w, s in zip(Window, stride)} + stride_map = {w: s for w, s in zip(Window, stride)} stride_out = [] for ax in inputs.axes: if ax.name in stride_map: @@ -83,7 +82,7 @@ def pool( del stride_out else: stride = (1,) * len(dims) - stride_map = {w.name: 1 for w in Window} + stride_map = {w: 1 for w in Window} if isinstance(padding, int): padding = ((padding, padding),) * len(Window) @@ -95,12 +94,12 @@ def pool( if not all([len(x) == 2 for x in padding]): raise ValueError(f"each entry in padding must be length 2, got {padding}") - padding_map = {w.name: p for w, p in zip(Window, padding)} + padding_map = {w: p for w, p in zip(Window, padding)} if use_ceil: - window_inputs = {w.name: ax.size for w, ax in zip(Window, inputs.axes)} + window_inputs = {w: ax.size for w, ax in zip(Window, inputs.axes)} padding_map = _use_ceil_padding( window_inputs=window_inputs, - window_kernel=window_map, + window_kernel=(Window), window_padding=padding_map, window_stride=stride_map, ) @@ -214,8 +213,8 @@ def mean_pool( """ tots = pool(Window, inputs, 0, jax.lax.add, stride, padding, use_ceil=use_ceil) if count_include_pad: - Window = ensure_tuple(Window) - window_size = reduce(lambda x, y: x * y, [w.size for w in Window]) + Window = axis_spec_to_shape_dict(Window) + window_size = reduce(lambda x, y: x * y, [s for s in Window.values()]) return tots / window_size else: inputs_axes_without_batches = inputs.resolve_axis(unsize_axes(Window)) diff --git a/src/haliax/partitioning.py b/src/haliax/partitioning.py index 0d2aa8a..bce942c 100644 --- a/src/haliax/partitioning.py +++ b/src/haliax/partitioning.py @@ -16,7 +16,7 @@ from jaxtyping import PyTree import haliax.tree_util as htu from haliax._src.compile_utils import compile_cache -from .axis import Axis, AxisSelection, AxisSelector +from .axis import Axis, AxisSelection, AxisSelector, axis_spec_to_shape_dict from .core import NamedArray from .jax_utils import Static, is_in_jit, is_jax_array_like, is_on_mac_metal from .tree_util import hashable_combine, hashable_partition @@ -590,7 +590,7 @@ def sharding_for_axis( def pspec_for_axis(axis: AxisSelection, mapping: Optional[ResourceMapping] = None) -> PartitionSpec: """Get the PartitionSpec for a single axis""" - axis = ensure_tuple(axis) + axis = axis_spec_to_shape_dict(axis) return PartitionSpec(*(physical_axis_name(a, mapping) for a in axis)) diff --git a/src/haliax/random.py b/src/haliax/random.py index 6b840b0..a2561da 100644 --- a/src/haliax/random.py +++ b/src/haliax/random.py @@ -4,23 +4,29 @@ import inspect import warnings from typing import Optional -import jax import jax.random as jrandom import haliax from haliax.core import NamedArray, NamedOrNumeric, broadcast_to -from haliax.util import ensure_tuple -from .axis import Axis, AxisSelector, AxisSpec, selects_axis -from .jax_utils import named_call, to_jax_shape -from .partitioning import physical_axis_name, physical_axis_size, pspec_for_axis +from .axis import ( + Axis, + AxisSelector, + AxisSpec, + axis_spec_to_shape_dict, + axis_spec_to_tuple, + concat_axes, + selects_axis, + to_jax_shape, +) +from .jax_utils import named_call @named_call def uniform( key, shape: AxisSpec, dtype=float, minval: NamedOrNumeric = 0.0, maxval: NamedOrNumeric = 1.0 ) -> NamedArray: - shape = ensure_tuple(shape) + shape = axis_spec_to_shape_dict(shape) minval = broadcast_to(minval, shape).array maxval = broadcast_to(maxval, shape).array jax_shape = to_jax_shape(shape) @@ -30,7 +36,7 @@ def uniform( @named_call def normal(key, shape: AxisSpec, dtype=float): - shape = ensure_tuple(shape) + shape = axis_spec_to_shape_dict(shape) jax_shape = to_jax_shape(shape) jax_array = jrandom.normal(key=key, shape=jax_shape, dtype=dtype) return haliax.auto_sharded(NamedArray(jax_array, shape)) @@ -38,7 +44,7 @@ def normal(key, shape: AxisSpec, dtype=float): @named_call def bernoulli(key, shape: AxisSpec, p: NamedOrNumeric): - shape = ensure_tuple(shape) + shape = axis_spec_to_shape_dict(shape) p = broadcast_to(p, shape).array jax_shape = to_jax_shape(shape) jax_array = jrandom.bernoulli(key=key, p=p, shape=jax_shape) @@ -47,7 +53,7 @@ def bernoulli(key, shape: AxisSpec, p: NamedOrNumeric): @named_call def randint(key, shape: AxisSpec, minval: NamedOrNumeric, maxval: NamedOrNumeric, dtype=int): - shape = ensure_tuple(shape) + shape = axis_spec_to_shape_dict(shape) minval = broadcast_to(minval, shape).array maxval = broadcast_to(maxval, shape).array jax_shape = to_jax_shape(shape) @@ -57,7 +63,7 @@ def randint(key, shape: AxisSpec, minval: NamedOrNumeric, maxval: NamedOrNumeric @named_call def poisson(key, shape: AxisSpec, lam: NamedOrNumeric, dtype=int): - shape = ensure_tuple(shape) + shape = axis_spec_to_shape_dict(shape) lam = broadcast_to(lam, shape).array jax_shape = to_jax_shape(shape) jax_array = jrandom.poisson(key=key, lam=lam, shape=jax_shape, dtype=dtype) @@ -66,7 +72,7 @@ def poisson(key, shape: AxisSpec, lam: NamedOrNumeric, dtype=int): @named_call def exponential(key, shape: AxisSpec, dtype=float): - shape = ensure_tuple(shape) + shape = axis_spec_to_shape_dict(shape) jax_shape = to_jax_shape(shape) jax_array = jrandom.exponential(key=key, shape=jax_shape, dtype=dtype) return haliax.auto_sharded(NamedArray(jax_array, shape)) @@ -74,7 +80,7 @@ def exponential(key, shape: AxisSpec, dtype=float): @named_call def gamma(key, shape: AxisSpec, a: NamedOrNumeric, dtype=float): - shape = ensure_tuple(shape) + shape = axis_spec_to_shape_dict(shape) a = broadcast_to(a, shape).array jax_shape = to_jax_shape(shape) jax_array = jrandom.gamma(key=key, a=a, shape=jax_shape, dtype=dtype) @@ -83,7 +89,7 @@ def gamma(key, shape: AxisSpec, a: NamedOrNumeric, dtype=float): @named_call def beta(key, shape: AxisSpec, a: NamedOrNumeric, b: NamedOrNumeric, dtype=float): - shape = ensure_tuple(shape) + shape = axis_spec_to_shape_dict(shape) a = broadcast_to(a, shape).array b = broadcast_to(b, shape).array jax_shape = to_jax_shape(shape) @@ -93,7 +99,7 @@ def beta(key, shape: AxisSpec, a: NamedOrNumeric, b: NamedOrNumeric, dtype=float @named_call def laplace(key, shape: AxisSpec, dtype=float): - shape = ensure_tuple(shape) + shape = axis_spec_to_shape_dict(shape) jax_shape = to_jax_shape(shape) jax_array = jrandom.laplace(key=key, shape=jax_shape, dtype=dtype) return haliax.auto_sharded(NamedArray(jax_array, shape)) @@ -101,7 +107,7 @@ def laplace(key, shape: AxisSpec, dtype=float): @named_call def cauchy(key, shape: AxisSpec, dtype=float): - shape = ensure_tuple(shape) + shape = axis_spec_to_shape_dict(shape) jax_shape = to_jax_shape(shape) jax_array = jrandom.cauchy(key=key, shape=jax_shape, dtype=dtype) return haliax.auto_sharded(NamedArray(jax_array, shape)) @@ -109,7 +115,7 @@ def cauchy(key, shape: AxisSpec, dtype=float): @named_call def logistic(key, shape: AxisSpec, dtype=float): - shape = ensure_tuple(shape) + shape = axis_spec_to_shape_dict(shape) jax_shape = to_jax_shape(shape) jax_array = jrandom.logistic(key=key, shape=jax_shape, dtype=dtype) return haliax.auto_sharded(NamedArray(jax_array, shape)) @@ -117,7 +123,7 @@ def logistic(key, shape: AxisSpec, dtype=float): @named_call def truncated_normal(key, shape: AxisSpec, lower: NamedOrNumeric, upper: NamedOrNumeric, dtype=float): - shape = ensure_tuple(shape) + shape = axis_spec_to_shape_dict(shape) lower = broadcast_to(lower, shape).array upper = broadcast_to(upper, shape).array jax_shape = to_jax_shape(shape) @@ -125,85 +131,12 @@ def truncated_normal(key, shape: AxisSpec, lower: NamedOrNumeric, upper: NamedOr return haliax.auto_sharded(NamedArray(jax_array, shape)) -_enforce_sharded_generate = False -""" mostly for testing: enforces shard generation for all random functions even if not running distributed""" - - -def generate_sharded(fn, axis: Optional[AxisSelector] = None): - """ - DEPRECATED: use jax.config.update("jax_threefry_partitionable", True) instead - Create a wrapped version of fn (which should be a random generator) that generates the random array in a sharded - manner, using vmap over the provided axis, or inferring the "best" one if not provided. - - This is a bit tricky but, for sharded models, we sometimes want to split the random key so that we only - need to generate the random numbers for the local shard. We do this because the RNG can't actually - auto-shard, meaning that if you want to generate a [1024] vector across 4 devices, each one actually - generates all 1024 numbers, and then only uses 256 of them. This is a waste of time, especially when it's - not a [1024] vector but a [1600, 6400] matrix (for say, gpt-2). So we split the key here, and then let - vmap hopefully only generate the random numbers for the local shard. - - However, we don't want to oversplit or it kind of ruins the whole point since we have to split the key on - every node... So instead we just split along the *largest* physical axis, or the provided axis if it's - provided. - """ - if not _enforce_sharded_generate: - warnings.warn( - 'generate_sharded is deprecated. Use jax.config.update("jax_threefry_partitionable", True) instead', - DeprecationWarning, - ) - - @functools.wraps(fn) - def wrapped_fn(*args, **kwargs): - _axis = axis - bound = inspect.signature(fn).bind(*args, **kwargs) - bound.apply_defaults() - key = bound.arguments["key"] - shape = bound.arguments["shape"] - - shape = ensure_tuple(shape) - - if len(shape) == 0: - # scalar - return fn(*args, **kwargs) - - if _axis is None: - pspec = pspec_for_axis(shape) - if pspec: - _axis, biggest_physical = max( - zip(shape, pspec), key=lambda x: (physical_axis_size(x[0]) or 0) if x[1] else 0 - ) - else: - _axis = biggest_physical = None - - _axis = _axis or shape[0] - else: - biggest_physical = physical_axis_name(_axis) - - if _enforce_sharded_generate or biggest_physical: - with jax.named_scope(f"generate_sharded({_axis})"): - index_of_axis_to_shard = shape.index(_axis) - # remove axis from shape - shape_without_axis = shape[:index_of_axis_to_shard] + shape[index_of_axis_to_shard + 1 :] - - keys = jrandom.split(key, shape[index_of_axis_to_shard].size) - - bound.arguments["shape"] = shape_without_axis - bound.arguments["key"] = keys - - return haliax.vmap(fn, axis=_axis)(*bound.args, **bound.kwargs).rearrange(shape) - else: - with jax.named_scope(f"generate_sharded({_axis}, no_shard)"): - return fn(*args, **kwargs) - - return wrapped_fn - - @named_call def ball(key, shape: AxisSpec, D: Axis, p: float = 2.0, dtype=float): - shape = ensure_tuple(shape) + shape = axis_spec_to_shape_dict(shape) jax_shape = to_jax_shape(shape) jax_array = jrandom.ball(key=key, shape=jax_shape, d=D.size, p=p, dtype=dtype) - return haliax.auto_sharded(NamedArray(jax_array, shape + (D,))) + return haliax.auto_sharded(NamedArray(jax_array, concat_axes(shape, D))) @named_call @@ -221,16 +154,16 @@ def choice( index = a.axis_indices(axis) assert index is not None, f"axis {axis} not in a" - shape = ensure_tuple(shape) + shape = axis_spec_to_shape_dict(shape) if p is not None: - assert p.resolve_axis(ensure_tuple(axis)) == p.axes, f"p must be 1D with axis {axis} or be None" + assert p.resolve_axis(axis_spec_to_tuple(axis)) == p.axes, f"p must be 1D with axis {axis} or be None" jax_shape = to_jax_shape(shape) jax_p = p.array if p is not None else None jax_array = jrandom.choice(key, a.array, jax_shape, replace=replace, p=jax_p, axis=index) - expected_shape = shape + tuple(a.axes[:index] + a.axes[index + 1 :]) + expected_shape = concat_axes(shape, tuple(a.axes[:index] + a.axes[index + 1 :])) return haliax.auto_sharded(NamedArray(jax_array, expected_shape)) @@ -253,7 +186,7 @@ def categorical(key, logits: NamedArray, axis: AxisSelector, shape: Optional[Axi if shape is None: shape = tuple(a for a in logits.axes if a != axis) else: - shape = ensure_tuple(shape) + shape = axis_spec_to_tuple(shape) # TODO: could alias the axis and rename at end if selects_axis(shape, axis): @@ -272,7 +205,7 @@ def categorical(key, logits: NamedArray, axis: AxisSelector, shape: Optional[Axi @named_call def gumbel(key, shape: AxisSpec, dtype=float): - shape = ensure_tuple(shape) + shape = axis_spec_to_shape_dict(shape) jax_shape = to_jax_shape(shape) jax_array = jrandom.gumbel(key, jax_shape, dtype=dtype) return haliax.auto_sharded(NamedArray(jax_array, shape)) @@ -287,7 +220,7 @@ def permutation(key, x: NamedArray, axis: AxisSelector, independent: bool = Fals @named_call def rademacher(key, shape: AxisSpec, dtype=float): - shape = ensure_tuple(shape) + shape = axis_spec_to_shape_dict(shape) jax_shape = to_jax_shape(shape) jax_array = jrandom.rademacher(key, jax_shape, dtype=dtype) return haliax.auto_sharded(NamedArray(jax_array, shape)) @@ -295,7 +228,7 @@ def rademacher(key, shape: AxisSpec, dtype=float): @named_call def t(key, shape: AxisSpec, df: NamedOrNumeric, dtype=float): - shape = ensure_tuple(shape) + shape = axis_spec_to_shape_dict(shape) df = broadcast_to(df, shape) jax_shape = to_jax_shape(shape) jax_array = jrandom.t(key, df.array, jax_shape, dtype=dtype) @@ -304,7 +237,7 @@ def t(key, shape: AxisSpec, df: NamedOrNumeric, dtype=float): @named_call def weibull_min(key, shape: AxisSpec, scale: NamedOrNumeric, concentration: NamedOrNumeric, dtype=float): - shape = ensure_tuple(shape) + shape = axis_spec_to_shape_dict(shape) scale = broadcast_to(scale, shape) concentration = broadcast_to(concentration, shape) jax_shape = to_jax_shape(shape) @@ -314,7 +247,7 @@ def weibull_min(key, shape: AxisSpec, scale: NamedOrNumeric, concentration: Name @named_call def pareto(key, shape: AxisSpec, b: NamedOrNumeric, dtype=float): - shape = ensure_tuple(shape) + shape = axis_spec_to_shape_dict(shape) b = broadcast_to(b, shape) jax_shape = to_jax_shape(shape) jax_array = jrandom.pareto(key, b.array, jax_shape, dtype=dtype) @@ -323,7 +256,7 @@ def pareto(key, shape: AxisSpec, b: NamedOrNumeric, dtype=float): @named_call def loggamma(key, shape: AxisSpec, a: NamedOrNumeric, dtype=float): - shape = ensure_tuple(shape) + shape = axis_spec_to_shape_dict(shape) a = broadcast_to(a, shape) jax_shape = to_jax_shape(shape) jax_array = jrandom.loggamma(key, a.array, jax_shape, dtype=dtype) @@ -331,7 +264,6 @@ def loggamma(key, shape: AxisSpec, a: NamedOrNumeric, dtype=float): __all__ = [ - "generate_sharded", "uniform", "normal", "ball", diff --git a/src/haliax/wrap.py b/src/haliax/wrap.py index f151d46..8a19bde 100644 --- a/src/haliax/wrap.py +++ b/src/haliax/wrap.py @@ -6,9 +6,8 @@ import jax.numpy as jnp from haliax.core import NamedArray, _broadcast_order, broadcast_to from haliax.jax_utils import is_scalarish -from haliax.util import ensure_tuple -from .axis import AxisSelection, AxisSelector, selects_axis +from .axis import AxisSelection, AxisSelector, axis_spec_to_shape_dict, eliminate_axes def wrap_elemwise_unary(f, a, *args, **kwargs): @@ -49,13 +48,14 @@ def wrap_reduction_call( result = fn(a.array, axis=None, **kwargs) return NamedArray(result, ()) else: - axis = ensure_tuple(axis) + axis = axis_spec_to_shape_dict(axis) if single_axis_only and len(axis) > 1: raise ValueError(f"{fn.__name__} only supports a single axis") indices = a.axis_indices(axis) if indices is None or any(x is None for x in indices): raise ValueError(f"axis {axis} is not in {a.axes}") - new_axes = [ax for ax in a.axes if not selects_axis(axis, ax)] + new_axes = eliminate_axes(a.axes, axis) + if single_axis_only: result = fn(a.array, axis=indices[0], **kwargs) else: @@ -74,9 +74,10 @@ def wrap_axiswise_call(fn, a, axis: Optional[AxisSelection], *, single_axis_only if axis is None: return fn(a.array, axis=None, **kwargs) else: - indices = ensure_tuple(a.axis_indices(axis)) + axis = axis_spec_to_shape_dict(axis) + indices = a.axis_indices(axis) if any(x is None for x in indices): - raise ValueError(f"axis {axis} is not in {a.axes}") + raise ValueError(f"Axis {axis} not in {a.axes}") if len(indices) == 1: return NamedArray(fn(a.array, axis=indices[0], **kwargs), a.axes) elif single_axis_only: diff --git a/tests/core_test.py b/tests/core_test.py index 4cc683a..5d7fe2f 100644 --- a/tests/core_test.py +++ b/tests/core_test.py @@ -1,7 +1,10 @@ import jax import jax.numpy as jnp +import numpy as np +import pytest from jax.random import PRNGKey +import haliax as hax from haliax import Axis, NamedArray, updated_slice @@ -485,7 +488,9 @@ def test_index(): named1 = hax.random.uniform(PRNGKey(0), (H, W, D)) - assert jnp.all(jnp.equal(hax.index(named1, {"H": slice(0, 10, 2)}).array, named1.array[0:10:2, :, :])) # type: ignore + assert jnp.all( + jnp.equal(hax.index(named1, {"H": slice(0, 10, 2)}).array, named1.array[0:10:2, :, :]) + ) # type: ignore assert hax.index(named1, {"H": slice(0, 10, 2)}).axes == (Axis("H", 5), W, D) # type: ignore # try indexing syntax @@ -602,10 +607,45 @@ def test_slice_nd_array_present_dims(): # this is not ok, since the H would not be eliminated -import numpy as np -import pytest +def test_broadcast_to(): + H, W, D = hax.make_axes(H=10, W=20, D=30) -import haliax as hax + named1 = hax.random.uniform(PRNGKey(0), (H, W, D)) + + assert jnp.all(jnp.equal(hax.broadcast_to(named1, (H, W, D)).array, named1.array)) + + ZZ = Axis("ZZ", 5) + + assert jnp.all(jnp.equal(hax.broadcast_to(named1, (H, W, D, ZZ)).array, named1.array.reshape(10, 20, 30, 1))) + + +def test_at_set(): + # tests the at/set syntax, similar to test_index but with jax-style modifications + HWD = {"H": 10, "W": 20, "D": 30} + WD = {"W": 20, "D": 30} + + named1 = hax.random.uniform(PRNGKey(0), HWD) + named2 = hax.random.uniform(PRNGKey(1), HWD)["H", 0:10:2] + + wd_only = hax.random.uniform(PRNGKey(2), WD) + + # set a slice + r1 = named1.at["H", slice(0, 10, 2)].set(named2) + + assert jnp.all(jnp.equal(r1.array, named1.array.at[0:10:2, :, :].set(named2.array))) + + r2 = named1.at["H", slice(0, 10, 2)].add(named2) + + assert jnp.all(jnp.equal(r2.array, named1.array.at[0:10:2, :, :].add(named2.array))) + + r3 = named1.at["H", slice(0, 10, 2)].mul(named2) + + assert jnp.all(jnp.equal(r3.array, named1.array.at[0:10:2, :, :].mul(named2.array))) + + # set a single axis + r4 = named1.at["H", :].set(wd_only) + + assert jnp.all(jnp.equal(r4.array, named1.array.at[:, :, :].set(wd_only.array))) def test_scalar_updated_slice(): diff --git a/tests/test_attention.py b/tests/test_attention.py index bdb0c18..9d5479d 100644 --- a/tests/test_attention.py +++ b/tests/test_attention.py @@ -5,11 +5,9 @@ from jax.random import PRNGKey import haliax as hax from haliax.nn.attention import ( alibi_attention_bias, - causal_mask, dot_product_attention, dot_product_attention_weights, forgetful_causal_mask, - self_attention, ) from test_utils import skip_if_no_torch @@ -49,26 +47,6 @@ def test_attention_doesnt_allow_overlapping_axes(): raise AssertionError("Should have raised an error") -def test_self_attention_basically_works(): - Pos = hax.Axis("Pos", 20) - KeyPos = hax.Axis("Pos_key", 20) - NumHeads = hax.Axis("NumHeads", 1) - Hid = hax.Axis("Hid", 8) - - query = hax.ones((NumHeads, Pos, Hid)) - - result = self_attention(Pos, Hid, query, query, query, is_causal=True) - assert result.axes == (NumHeads, Pos, Hid) - - k = query.rename({Pos: KeyPos}) - cmask = causal_mask(Pos, KeyPos) - result2 = dot_product_attention(KeyPos, Hid, query, k, k, mask=cmask) - assert result2.axes == (NumHeads, Pos, Hid) - - # tight tolerances because it should be exactly the same computation - assert jnp.allclose(result.array, result2.array) - - def test_alibi_attention_bias(): KeyPos = hax.Axis("KeyPos", 20) NumHeads = hax.Axis("NumHeads", 1) diff --git a/tests/test_axis.py b/tests/test_axis.py index d7a9def..bb11f6a 100644 --- a/tests/test_axis.py +++ b/tests/test_axis.py @@ -1,6 +1,7 @@ import pytest -from haliax.axis import Axis, eliminate_axes, make_axes, overlapping_axes, rearrange_for_partial_order +import haliax +from haliax.axis import eliminate_axes, make_axes, rearrange_for_partial_order, replace_axis, without_axes def test_eliminate_axes(): @@ -22,6 +23,110 @@ def test_eliminate_axes(): assert eliminate_axes(("H", W), ("H",)) == (W,) assert eliminate_axes(("H", W), ("H", "W")) == () + # test shape dicts + + HWC = {"H": 3, "W": 4, "C": 5} + HW = {"H": 3, "W": 4} + + assert eliminate_axes(HWC, HW) == {"C": 5} + with pytest.raises(ValueError): + eliminate_axes(HW, HWC) + assert eliminate_axes(HW, HW) == {} + assert eliminate_axes(HWC, {"H": 3}) == {"W": 4, "C": 5} + assert eliminate_axes(HWC, {"W": 4}) == {"H": 3, "C": 5} + assert eliminate_axes(HWC, {"C": 5}) == HW + + C2 = make_axes(C=6) + + with pytest.raises(ValueError): + eliminate_axes(HWC, C2) + + with pytest.raises(ValueError): + eliminate_axes(C2, HWC) + + +def test_without_axes(): + H, W, C = make_axes(H=3, W=4, C=5) + + assert without_axes((H, W), (H,)) == (W,) + assert without_axes((H, W), (W,)) == (H,) + assert without_axes((H, W), (H, W)) == () + + assert without_axes((H, W), (C,)) == (H, W) + + assert without_axes((H, W), (H, C)) == (W,) + + # test string references + assert without_axes((H, W), ("H",)) == (W,) + assert without_axes(("H", W), (H,)) == (W,) + assert without_axes(("H", W), ("H",)) == (W,) + assert without_axes(("H", W), ("H", "W")) == () + + # test shape dicts + + HWC = {"H": 3, "W": 4, "C": 5} + HW = {"H": 3, "W": 4} + + assert without_axes(HWC, HW) == {"C": 5} + assert without_axes(HW, HWC) == {} + assert without_axes(HW, HW) == {} + assert without_axes(HWC, {"H": 3}) == {"W": 4, "C": 5} + assert without_axes(HWC, {"W": 4}) == {"H": 3, "C": 5} + assert without_axes(HWC, {"C": 5}) == HW + + # test different sizes cause error + C2 = make_axes(C=6) + + with pytest.raises(ValueError): + without_axes(HWC, C2) + + with pytest.raises(ValueError): + without_axes(C2, HWC) + + +def test_replace_axis(): + H, W, C = make_axes(H=3, W=4, C=5) + H2 = haliax.Axis("H2", 6) + + assert replace_axis((H, W), W, (C,)) == (H, C) + + with pytest.raises(ValueError): + replace_axis((H, W), C, (H,)) + + with pytest.raises(ValueError): + replace_axis((H, W), H2, (C, W)) + + # test string references + with pytest.raises(ValueError): + replace_axis((H, W), "H", (W,)) + + with pytest.raises(ValueError): + assert replace_axis(("H", W), "H", ("C", W)) + + with pytest.raises(ValueError): + assert replace_axis(("H", W), "H", ("W",)) == (W, W) + + assert replace_axis(("H", W), "H", ("C",)) == ("C", W) + assert replace_axis(("H", W), "W", ("C",)) == ("H", "C") + assert replace_axis(("H", W), "W", ("C", "D")) == ("H", "C", "D") + + # test shape dicts + + HWC = {"H": 3, "W": 4, "C": 5} + HW = {"H": 3, "W": 4} + HC = {"H": 3, "C": 5} + + assert replace_axis(HW, "H", HC) == {"H": 3, "C": 5, "W": 4} + + with pytest.raises(ValueError): + replace_axis(HW, "H", HWC) + + with pytest.raises(ValueError): + replace_axis(HW, "C", HC) + + with pytest.raises(ValueError): + replace_axis(HW, "H", HWC) + def assert_partial_order_respected(partial_order, output): positions = {el: i for i, el in enumerate(output)} @@ -133,17 +238,3 @@ def test_duplicate_elements_errors(): with pytest.raises(ValueError): rearrange_for_partial_order(partial_order, candidates) - - -def test_overlapping_axes_with_different_sizes(): - A1 = Axis("A", 10) - A2 = Axis("A", 12) - B = Axis("B", 14) - C = Axis("C", 16) - D = Axis("D", 18) - - ax1 = (A1, B, C) - ax2 = (A2, C, D) - - overlapping_names = overlapping_axes(ax1, ax2) # Should not error - assert overlapping_names == ("A", "C") diff --git a/tests/test_random.py b/tests/test_random.py index 7e3f681..925934d 100644 --- a/tests/test_random.py +++ b/tests/test_random.py @@ -5,13 +5,15 @@ import jax.numpy as jnp from jaxtyping import PRNGKeyArray import haliax as hax -from haliax.random import generate_sharded +from haliax.axis import axis_spec_to_shape_dict Height = hax.Axis("Height", 4) Width = hax.Axis("Width", 8) Digit = hax.Axis("Digit", 10) +HWD = axis_spec_to_shape_dict((Height, Width, Digit)) + def test_empty_shape(): key = jax.random.PRNGKey(0) @@ -66,26 +68,6 @@ def test_uniform_with_bounds_broadcast_and_scalar(): assert hax.all(u <= 0.5) -def test_sharded_uniform_with_bounds_broadcast_and_scalar(): - hax.random._enforce_sharded_generate = True - try: - key = jax.random.PRNGKey(0) - lb = hax.full(Height, -3.0) - ub = 0.5 - u = generate_sharded(hax.random.uniform, axis=Height)(key, shape=(Height, Width), minval=lb, maxval=ub) - - assert u.axes == (Height, Width) - - assert hax.all(u >= -3.0) - assert hax.all(u <= 0.5) - finally: - hax.random._enforce_sharded_generate = False - - # now just assert that this does in fact change the randomness - u2 = hax.random.uniform(key, shape=(Height, Width), minval=lb, maxval=ub) - assert not hax.all(u == u2) - - def test_randint(): check_gen_is_equal(lambda k, s: jax.random.randint(k, s, 0, 10), lambda k, s: hax.random.randint(k, s, 0, 10)) # check broadcasting @@ -252,6 +234,38 @@ def test_choice(): ) +def test_categorical_shape_dict(): + logits = hax.random.uniform(jax.random.PRNGKey(0), HWD) + check_gen_is_equal( + lambda k, s: jax.random.categorical(k, logits.array, shape=s, axis=-1), + lambda k, s: hax.random.categorical(k, logits, Digit, shape=s), + ) + + logits = logits.rearrange((Digit, Height, Width)) + check_gen_is_equal( + lambda k, s: jax.random.categorical(k, logits.array, shape=s, axis=0), + lambda k, s: hax.random.categorical(k, logits, Digit, shape=s), + ) + + # check broadcasting + logits = hax.random.uniform( + jax.random.PRNGKey(0), + {"Height": Height.size, "Digit": Digit.size}, + ) + # https://github.com/google/jax/issues/13124 broadcasting is wrong with jax categorical + raw_logits = jnp.broadcast_to(logits.array.reshape(-1, 1, Digit.size), (Height.size, Width.size, Digit.size)) + check_gen_is_equal( + lambda k, s: jax.random.categorical(k, raw_logits, shape=s, axis=-1), + lambda k, s: hax.random.categorical(k, logits, Digit, shape=s), + ) + + # check str arg for selector + check_gen_is_equal( + lambda k, s: jax.random.categorical(k, raw_logits, shape=s, axis=-1), + lambda k, s: hax.random.categorical(k, logits, "Digit", shape=s), + ) + + def test_categorical(): logits = hax.random.uniform( jax.random.PRNGKey(0), commit 55124a040a339c95369ec739e69b8646286363b0 Date: 2025-07-06T23:46:14-07:00 Ruff, typing, agents.md (#156) * trying desperately to make typing work nicely * document * agents.md diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml index dc590d0..beb7e93 100644 --- a/.pre-commit-config.yaml +++ b/.pre-commit-config.yaml @@ -2,7 +2,7 @@ # See https://pre-commit.com/hooks.html for more hooks exclude: ".git" default_stages: - - commit + - pre-commit fail_fast: true repos: @@ -16,24 +16,24 @@ repos: - id: check-merge-conflict - id: check-added-large-files -- repo: https://github.com/psf/black - rev: 22.3.0 - hooks: - - id: black - -- repo: https://github.com/timothycrosley/isort - rev: 5.11.5 - hooks: - - id: isort +- repo: https://github.com/astral-sh/ruff-pre-commit + rev: v0.11.10 + hooks: + - id: ruff + args: [ --fix, --exit-non-zero-on-fix ] -- repo: https://github.com/PyCQA/flake8 - rev: 3.9.2 - hooks: - - id: flake8 - additional_dependencies: [flake8-isort] +#- repo: local +# hooks: +# - id: ty-check +# name: ty-check +# language: python +# entry: ty check +# pass_filenames: false +# args: [--python=.venv/] +# additional_dependencies: [ty] - repo: https://github.com/pre-commit/mirrors-mypy - rev: 'v1.5.1' + rev: 'v1.16.1' hooks: - id: mypy args: [--ignore-missing-imports, --check-untyped-defs] diff --git a/AGENTS.md b/AGENTS.md new file mode 100644 index 0000000..42b19ab --- /dev/null +++ b/AGENTS.md @@ -0,0 +1,79 @@ +# Haliax LLM Agent Guidelines + +This document summarizes important conventions for contributing code or documentation to the Haliax +repository. Follow these notes when implementing new features or fixing bugs. + +## General Guidelines + +* **Get better.** Whenever you discover something missing from these guidelines, or the requester + suggests a better way to do something, please update this document. The goal is to make it easier for + everyone to contribute and maintain the codebase. Generally speaking, you should add bullets or new sections. + Be sure to do this when directed to. For example, if directed that you should never relax tolerances in + floating point tests, add that to the list. +* **Playbooks.** Sometimes, there are repeatable tasks (e.g. porting models) for which we follow a standard set of steps. + Please reference `.playbooks/` to see what playbooks are available, or see the list below. If you want to add a playbook + write a markdown doc named e.g. `.playbooks/port-models.md` and add a pointer to it in the list below. + +## Playbook + +- At the moment, there are no playbooks available. If you have a repeatable task that you think + should be documented, please create a new markdown file in `.playbooks/` and add it to the list above. + +## Code Style + +* **Python version**: the project targets Python >=3.10. +* **Formatting and Linting**: We use `ruff` via `pre-commit`. +* **Typing**: the code base uses `mypy` for static type checking. `mypy` is run by pre‑commit and the + configuration is found in `pyproject.toml`. +* **Run `pre-commit run --all-files`** before committing. The CI workflows run the same checks. +* **Doc Strings**: All public functions, classes, and modules should have docstrings, unless + their purpose is painfully obvious. Use + [Google style](https://google.github.io/styleguide/pyguide.html#38-comments-and-docstrings) for + consistency. +* **Commenting**: Use comments to explain why something is done a certain way, especially if it is not + immediately obvious. Avoid commenting on every line of code; focus on the intent and purpose of + complex logic. Demarcating logical groups of code with comments is encouraged, unless it is better + to refactor the code into smaller functions or classes. +* **Mkdocs**: We use [Mkdocs](https://www.mkdocs.org/) for documentation. The main documentation is in + the `docs` directory. Use Markdown for writing docs, and follow the existing structure. When linking to + symbols, prefer using mkdocs-style links (e.g. With a custom title: `[full.path.object2][]` or + `[Object 1][full.path.object1]`) +* **Documentation**: When adding new features, ensure that the documentation is updated accordingly. + This includes updating the Mkdocs files and any relevant docstrings. If you add a new module or + significant functionality, consider adding a dedicated section in the documentation. + +## Testing + +* Tests are executed with `pytest`. The default workflow runs + `pytest tests -m "not entry and not slow and not ray"`. +* In general, never relax tolerances in floating point tests unless specifically discussed with the + team. Use `assert_allclose` with appropriate tolerances for numerical comparisons. We typically use + 1e-4 for more complex modules, and 1e-5 for simpler ones. +* Tests should be reasonably fast. Mark long-running tests with @pytest.mark.slow so they are excluded from the default suite. +* Always mark tests that depend on pytorch with `@skip_if_no_torch` to ensure they are skipped + when PyTorch is not available. This is particularly important for tests that require PyTorch-specific + functionality. + + +## Design Preferences + +* **Generic code**: many utilities are written with Python generics and dataclasses. Where possible, + write reusable functions or classes that operate over TypeVars instead of hard coding concrete types. +* **Configurations**: configuration files are dataclasses loaded via `draccus`. Keep configs + declarative and typed. +* **Reproducibility**: Levanter aims for deterministic training where possible. Avoid sources of + nondeterminism unless explicitly required. +* Prefer Stacked with fold or scan over writing custom loops, for better compile times and gradient checkpointing support + +## Library conventions +- Haliax revolves around `NamedArray` and explicit `Axis` objects. Prefer APIs that accept + axes or axis names rather than hard‑coding positional dimensions. +- Utilities should be written so they work with arbitrary axis names. Avoid relying on + fixed axis orders when possible. +- Use the provided modules in `haliax.nn` or Equinox when building neural network layers. +- Type annotations can use named shapes shorthand provided in `haliax.haxtyping`: `ht.f32[NamedArray, "batch"]` + for a float32 array with a "batch" axis, or `ht.Float[NamedArray, "batch"]` for any floating point dtype. + +## Documentation +- Public functions and modules require docstrings. If behavior is non‑obvious, + add examples in `docs/`. diff --git a/docs/nn.md b/docs/nn.md index fcb16c7..84f2fde 100644 --- a/docs/nn.md +++ b/docs/nn.md @@ -55,7 +55,6 @@ We don't provide an explicit attention module, but we do provide an attention fu :::haliax.nn.attention.dot_product_attention :::haliax.nn.attention.dot_product_attention_weights -:::haliax.nn.attention.self_attention ### Masks ::: haliax.nn.attention.causal_mask diff --git a/docs/state-dict.md b/docs/state-dict.md index 395c1ce..af9d7d7 100644 --- a/docs/state-dict.md +++ b/docs/state-dict.md @@ -97,6 +97,7 @@ and use `_state_dict_key_map` to rename keys. For instance, the `Gpt2Transformer from typing import Optional from haliax.state_dict import ModuleWithStateDictSerialization + class Gpt2Transformer(ModuleWithStateDictSerialization): ... @@ -122,7 +123,6 @@ For example, below is the implementation of `to_state_dict()` in [levanter.model In this class, we want to preserve HF compatibility by saving untied output embeddings. (We chose not to implement non-weight-tied embeddings.) - ```python from typing import Optional diff --git a/docs/typing.md b/docs/typing.md index 528e9da..5b9cb75 100644 --- a/docs/typing.md +++ b/docs/typing.md @@ -1,26 +1,26 @@ +from haliax import NamedArrayfrom haliax import NamedArray + # NamedArray Type Annotations -Haliax supports a lightweight syntax for specifying the axes of a `NamedArray` -in type annotations. Internally, `Named[...]` expands to -`Annotated[NamedArray, axes]`, so it works well with static type checkers like -``mypy``. The syntax mirrors normal indexing with axis names. Some examples: +Haliax supports an extension to [`jaxtyping`](https://docs.kidger.site/jaxtyping/) +that allows you to annotate functions and methods that take or return +[`NamedArray`][haliax.core.NamedArray] objects. If you are familiar with +[`jaxtyping`](https://docs.kidger.site/jaxtyping/), the syntax is very similar. +In fact, for non-NamedArrays, it is exactly the same. ```python -from haliax import Named - -arr: Named["batch", "embed"] -arr: Named["batch embed ..."] # starts with these axes -arr: Named["... embed"] # ends with this axis -arr: Named["batch ... embed"] # contains these axes in order -arr: Named[{"batch", "embed"}] # has exactly these axes, order ignored -arr: Named[{"batch", "embed", ...}] # has at least these axes +from haliax import NamedArray +import haliax.haxtyping as ht + +def foo(x: ht.Float[NamedArray, "batch embed ..."]): + ... ``` At runtime you can verify that a `NamedArray` conforms to a particular annotation using `matches_axes`: ```python -if not arr.matches_axes(Named["batch embed ..."]): +if not arr.matches_axes(Float[NamedArray, "batch embed ..."]): raise ValueError("unexpected axes") ``` @@ -32,12 +32,12 @@ JAX's common dtypes that can be indexed just like ``Named``. In documentation examples we'll use ``import haliax.typing as ht``: ```python -import haliax.typing as ht +import haliax.haxtyping as ht -def foo(x: ht.f32["batch"]): +def foo(x: ht.f32[NamedArray, "batch"]): ... -def bar(x: ht.i32["batch"]): +def bar(x: ht.i32[NamedArray, "batch"]): ... ``` @@ -46,7 +46,7 @@ For convenience the module also provides aggregate categories ``Float``, signed integer or unsigned integer dtype respectively: ```python -def baz(x: ht.Float["batch"]): +def baz(x: ht.Float[NamedArray, "batch"]): ... ``` @@ -54,8 +54,47 @@ At runtime ``matches_axes`` also checks the dtype when one is present: ```python from haliax import Axis, zeros -import haliax.typing as ht +import haliax.haxtyping as ht arr = zeros({"batch": 4}) assert arr.matches_axes(ht.f32["batch"]) # dtype and axes both match ``` + +## FAQ + +### Why not use `NamedArray` directly in type annotations? + +Using `NamedArray` directly in type annotations doesn't work well with +type checkers like `mypy` or `pyright`. These tools expect types to be +subscripted with other types or forward references (which are strings). +Using `NamedArray` directly would lead to type errors. + +### Why not use `jaxtyping` directly? + +While `jaxtyping` is a powerful library for type annotations in JAX, it does not +support `NamedArray` objects directly. The `haliax.haxtyping` module extends +`jaxtyping` to include `NamedArray` support, allowing you to annotate functions +and methods that take or return `NamedArray` objects with specific axes and dtypes. + +### Why do I have to specify the `NamedArray` type in the annotation? + +I hate this, but it's the only way to get type checkers like `mypy` and `pyright` to understand that the type is +a `NamedArray`. Underneath the hood, during type checking, `jaxtyping.Float` (and `haxtyping.Float`) are +essentially type aliases of [`Annotated`](https://docs.python.org/3/library/typing.html#typing.Annotated) +with the `NamedArray` type. There's no other way I could find to get type checkers to understand that the type is a +`NamedArray` or to accept strings like `"batch embed ..."` as valid type annotations. + +### How do I use single axes in type annotations with flake or ruff. + +Like `jaxtyping`, you need to prepend a space before the axis name to use single axes in type annotations with +flake or ruff. For example, to use a single axis named `batch`, you would write: + +```python +def foo(x: ht.Float[NamedArray, " batch"]): + ... +``` + +Then suppress F722 in your linter to suppress that error. + +See the [jaxtyping documentation](https://docs.kidger.site/jaxtyping/faq/#flake8-or-ruff-are-throwing-an-error) for more +details on the workaround. diff --git a/pyproject.toml b/pyproject.toml index c9e9f18..4453622 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -72,6 +72,11 @@ src_paths = ["src", "tests"] "Bug Tracker" = "https://github.com/stanford-crfm/haliax/issues/" "Documentation" = "https://haliax.readthedocs.io/en/latest/" +[tool.ruff.lint] +ignore = [ "E203", "E501", "W605", "F821", "E266", "F722", "E731", "E741" ] + +[tool.setuptools.package-data] +"haliax" = ["*.pyi"] [tool.coverage.report] exclude_also = [ diff --git a/src/haliax/__init__.py b/src/haliax/__init__.py index e26ac12..12cc604 100644 --- a/src/haliax/__init__.py +++ b/src/haliax/__init__.py @@ -1,4 +1,4 @@ -import typing +import typing as t from typing import Optional, Sequence import jax @@ -42,11 +42,8 @@ from .axis import ( to_jax_shape, ) from .core import ( - Named, NamedArray, - NamedArrayAxes, - NamedArrayAxesSpec, - NamedOrNumeric, + NamedArrayAxes, NamedArrayAxesSpec, NamedOrNumeric, are_shape_checks_enabled, broadcast_arrays, broadcast_axis, @@ -66,6 +63,7 @@ from .core import ( unflatten_axis, updated_slice, ) +from .haxtyping import Named from .hof import fold, map, scan, vmap from .jax_utils import tree_checkpoint_name from .ops import clip, isclose, pad_left, trace, tril, triu, where @@ -83,8 +81,8 @@ from .wrap import ( ) -T = typing.TypeVar("T") -A = typing.TypeVar("A", Scalar, NamedArray, jnp.ndarray) +T = t.TypeVar("T") +A = t.TypeVar("A", Scalar, NamedArray, jnp.ndarray) # creation routines @@ -148,11 +146,6 @@ def arange(axis: AxisSpec, *, start=0, step=1, dtype: Optional[DTypeLike] = None ``` """ - from haliax.jax_utils import to_jax_shape - from haliax.util import ensure_tuple - - # if start is a tracer, we need to be a bit cleverer since arange doesn't support tracers - # return NamedArray(jnp.arange(start, stop, step, dtype=dtype), (axis,)) size = axis_size(axis) arr = jax.lax.iota(dtype=dtype or jnp.result_type(start), size=size) * step + start @@ -274,7 +267,7 @@ def concatenate(axis: AxisSelector, arrays: Sequence[NamedArray]) -> NamedArray: if axis_index is None: raise ValueError(f"Axis {aname} not found in 0th array {arrays[0]}") - axes: typing.Tuple[AxisSelector, ...] = arrays[0].axes + axes: tuple[AxisSelector, ...] = arrays[0].axes # we want to use the axis name for `axis`, because it's not uncommon for those to be different lengths in the arrays axes = axes[:axis_index] + (aname,) + axes[axis_index + 1 :] arrays = [a.rearrange(axes) for a in arrays] @@ -931,9 +924,6 @@ __all__ = [ "make_axes", "axis_name", "axis_size", - "NamedArrayAxesSpec", - "NamedArrayAxes", - "Named", "NamedArray", "broadcast_to", "broadcast_axis", @@ -1106,4 +1096,14 @@ __all__ = [ "is_named_array", "tree_checkpoint_name", "ScanCheckpointPolicy", + "quantization", + "util", + "einsum", + "broadcast_arrays", + "unflatten_axis", + "ReductionFunction", + "SimpleReductionFunction", + "NamedArrayAxes", + "NamedArrayAxesSpec", + "Named", ] diff --git a/src/haliax/_src/dot.py b/src/haliax/_src/dot.py index 966452e..9475831 100644 --- a/src/haliax/_src/dot.py +++ b/src/haliax/_src/dot.py @@ -4,7 +4,6 @@ import warnings from typing import Dict, Optional, Tuple import jax -import jax.numpy as jnp import haliax from haliax.axis import ( @@ -20,7 +19,6 @@ from haliax.axis import ( from haliax.core import NamedArray from haliax.jax_utils import _jittable_dg_einsum from haliax.types import DTypeLike, PrecisionLike -from haliax.util import ensure_tuple # deprecated overload diff --git a/src/haliax/_src/fp8.py b/src/haliax/_src/fp8.py index b89e4ab..72f46d0 100644 --- a/src/haliax/_src/fp8.py +++ b/src/haliax/_src/fp8.py @@ -1,4 +1,3 @@ -import warnings from functools import partial from jax import custom_jvp, custom_vjp, lax diff --git a/src/haliax/_src/state_dict.py b/src/haliax/_src/state_dict.py index 11ec001..505bcf9 100644 --- a/src/haliax/_src/state_dict.py +++ b/src/haliax/_src/state_dict.py @@ -15,8 +15,7 @@ from jaxtyping import PyTree import haliax.partitioning as partitioning from haliax._src.util import index_where -from haliax.axis import Axis -from haliax.core import NamedArray, flatten_axes, named +from haliax.core import NamedArray, named from haliax.jax_utils import is_jax_array_like, is_scalarish from haliax.tree_util import scan_aware_tree_map @@ -209,14 +208,14 @@ def from_state_dict(tree: T, state_dict: StateDict, prefix: Optional[str] = None array = named(array, tree.axes) array = partitioning.auto_sharded(array) - return array + return array # type: ignore elif is_jax_array_like(tree): if prefix is None: raise ValueError("Cannot extract a leaf value from a state dict without a prefix") # TODO: add "strict" flag so we can return None in cases where it's just missing return jnp.array(state_dict[prefix]) elif tree is None: - return None + return None # type: ignore else: if prefix is None: return tree diff --git a/src/haliax/core.py b/src/haliax/core.py index 3c50b92..4e93715 100644 --- a/src/haliax/core.py +++ b/src/haliax/core.py @@ -1,3 +1,5 @@ +from __future__ import annotations + import contextlib import functools as ft import typing @@ -32,7 +34,6 @@ from .axis import ( ) from .types import GatherScatterModeStr, IntScalar, PrecisionLike, Scalar - NamedOrNumeric = Union[Scalar, "NamedArray"] NamedIndex = Union[int, slice_t, "NamedArray", dslice, list[int], jnp.ndarray] @@ -181,19 +182,6 @@ def _parse_namedarray_axes( raise TypeError(f"Invalid NamedArray typing spec: {item}") -class Named: - """Type annotation helper for :class:`NamedArray`. - - ``Named["batch embed"]`` expands to ``Annotated[NamedArray, axes]`` so that - type checkers treat it as a ``NamedArray`` at static time while the axis - metadata is available at runtime via :func:`typing.get_args`. - """ - - def __class_getitem__(cls, item: NamedArrayAxesSpec) -> typing.Any: - axes = _parse_namedarray_axes(item) - return typing.Annotated[NamedArray, axes] - - class NamedArrayMeta(type): def __getitem__(cls, item: NamedArrayAxesSpec) -> typing.Any: axes = _parse_namedarray_axes(item) @@ -2112,7 +2100,6 @@ def _convert_index_expr_to_dict(idx) -> dict[AxisSelector, NamedIndex]: __all__ = [ "NamedArrayAxesSpec", "NamedArrayAxes", - "Named", "NamedArray", "named", "slice", diff --git a/src/haliax/haxtyping.py b/src/haliax/haxtyping.py new file mode 100644 index 0000000..4f131ff --- /dev/null +++ b/src/haliax/haxtyping.py @@ -0,0 +1,138 @@ +from __future__ import annotations +from dataclasses import dataclass +from typing import TYPE_CHECKING, Any + + +@dataclass(frozen=True) +class DTypeCategory: + """Represents a dtype category such as ``float`` or ``int``.""" + + name: str + category: Any + + def __repr__(self) -> str: # pragma: no cover - trivial + return self.name + +if TYPE_CHECKING: + # ── STATIC ONLY: re‑export jaxtyping’s aliases so mypy/Pyright/PyCharm see them + from jaxtyping import ( + Float32 as f32, Float64 as f64, Float16 as f16, BFloat16 as bf16, + Int8 as i8, Int16 as i16, Int32 as i32, Int64 as i64, + UInt8 as u8, UInt16 as u16, UInt32 as u32, UInt64 as u64, + Bool as bool_, Complex64 as complex64, Complex128 as complex128, + Float as Float, Int as Int, UInt as UInt, + ) + # axes‑only helper + from typing import Annotated as Named + +else: + # ── RUNTIME: custom wrappers for NamedArray, plus delegation to jaxtyping ── + import jaxtyping as jt + import jax.numpy as jnp + from typing import Annotated + from dataclasses import dataclass, replace + + from .core import ( + NamedArray, + NamedArrayAxes, + NamedArrayAxesSpec, + _parse_namedarray_axes, + ) + + def _with_dtype(axes: NamedArrayAxes, dtype): + """Attach dtype to axes metadata if not already set.""" + return axes if axes.dtype is not None else replace(axes, dtype=dtype) + + def _make_dtype_wrapper(dtype): + """Factory for f32, i32, etc.""" + class _Wrapper: + def __class_getitem__(cls, item): + # two‑arg form: (BaseType, axes_spec) + if isinstance(item, tuple) and len(item) == 2: + base, axes_spec = item + else: + base, axes_spec = NamedArray, item + + # Delegate non‑NamedArray to jaxtyping + if base is not NamedArray: + # e.g. use jt.Float32 for jnp.float32 + jaxt = getattr(jt, f"Float{dtype.itemsize*8}") \ + if hasattr(dtype, "itemsize") else jt.Float + return jaxt[base, axes_spec] + + # Handle NamedArray path + axes = _parse_namedarray_axes(axes_spec) + return Annotated[NamedArray, _with_dtype(axes, dtype)] + + return _Wrapper + + # ── Build all dtype wrappers ───────────────────────────────────────────── + f32 = _make_dtype_wrapper(jnp.float32) + f64 = _make_dtype_wrapper(jnp.float64) + f16 = _make_dtype_wrapper(jnp.float16) + bf16 = _make_dtype_wrapper(jnp.bfloat16) + + i8 = _make_dtype_wrapper(jnp.int8) + i16 = _make_dtype_wrapper(jnp.int16) + i32 = _make_dtype_wrapper(jnp.int32) + i64 = _make_dtype_wrapper(jnp.int64) + + u8 = _make_dtype_wrapper(jnp.uint8) + u16 = _make_dtype_wrapper(jnp.uint16) + u32 = _make_dtype_wrapper(jnp.uint32) + u64 = _make_dtype_wrapper(jnp.uint64) + + bool_ = _make_dtype_wrapper(jnp.bool_) + complex64 = _make_dtype_wrapper(jnp.complex64) + complex128 = _make_dtype_wrapper(jnp.complex128) + + + + + def _make_category_wrapper(name: str, category): + """Like _make_dtype_wrapper but matches any dtype in the JAX category.""" + + class _Wrapper: + def __class_getitem__(cls, item): + # same base/axes unpack logic + if isinstance(item, tuple) and len(item) == 2: + base, axes_spec = item + else: + base, axes_spec = NamedArray, item + + # non‑NamedArray → delegate to jaxtyping’s category wrapper + if base is not NamedArray: + return getattr(jt, name)[base, axes_spec] + + # NamedArray path + axes = _parse_namedarray_axes(axes_spec) + cat = DTypeCategory(name, category) + return Annotated[NamedArray, _with_dtype(axes, cat)] + + return _Wrapper + + + # Build the category wrappers + Float = _make_category_wrapper("float", jnp.floating) + Complex = _make_category_wrapper("complex", jnp.complexfloating) + Int = _make_category_wrapper("int", jnp.signedinteger) + UInt = _make_category_wrapper("uInt", jnp.unsignedinteger) + + + # ── Named: axes‑only helper ─────────────────────────────────────────────── + class _NamedHelper: + @classmethod + def __class_getitem__(self, axes_spec_: tuple[type[NamedArray], NamedArrayAxesSpec]): + _, axes_spec = axes_spec_ + axes = _parse_namedarray_axes(axes_spec) + return Annotated[NamedArray, axes] + + Named = _NamedHelper + + __all__ = [ + "Named", + "f32", "f64", "f16", "bf16", + "i8", "i16", "i32", "i64", + "u8", "u16", "u32", "u64", + "bool_", "complex64", "complex128", + ] diff --git a/src/haliax/hof.py b/src/haliax/hof.py index f386f3c..c4a4a1a 100644 --- a/src/haliax/hof.py +++ b/src/haliax/hof.py @@ -23,7 +23,7 @@ from .axis import Axis, AxisSelection, AxisSelector, axis_spec_to_shape_dict, ax from .core import NamedArray from .jax_utils import Static, broadcast_prefix, is_jax_array_like from .partitioning import physical_axis_name -from .util import ensure_tuple, is_named_array +from .util import is_named_array def vmap( diff --git a/src/haliax/nn/attention.py b/src/haliax/nn/attention.py index 560bee3..447ad50 100644 --- a/src/haliax/nn/attention.py +++ b/src/haliax/nn/attention.py @@ -11,7 +11,6 @@ import haliax.random as hrandom from haliax.axis import Axis, AxisSelection, AxisSelector, AxisSpec, axis_name, axis_spec_to_shape_dict from haliax.core import NamedArray from haliax.types import PrecisionLike -from haliax.util import ensure_tuple # With attention, we usually distinguish between the mask and the bias, though the former is just a special case of the diff --git a/src/haliax/nn/embedding.py b/src/haliax/nn/embedding.py index 04ba8ec..21b2aa5 100644 --- a/src/haliax/nn/embedding.py +++ b/src/haliax/nn/embedding.py @@ -1,5 +1,4 @@ import dataclasses -import math import warnings from typing import Optional @@ -12,7 +11,6 @@ from ..axis import Axis, AxisSpec, concat_axes from ..core import NamedArray from ..jax_utils import named_call from ..tree_util import resize_axis -from ..util import ensure_tuple class Embedding(eqx.Module): diff --git a/src/haliax/nn/scan.py b/src/haliax/nn/scan.py index a199e51..cac66f9 100644 --- a/src/haliax/nn/scan.py +++ b/src/haliax/nn/scan.py @@ -2,7 +2,7 @@ import dataclasses import functools import re import warnings -from typing import Any, Dict, Generic, Literal, Optional, Protocol, Sequence, Type, TypeVar, Union, cast +from typing import Any, Dict, Generic, Optional, Protocol, Sequence, Type, TypeVar, cast import equinox as eqx import jax @@ -169,7 +169,7 @@ class BlockSeq(ModuleWithStateDictSerialization, Generic[M]): @staticmethod def _slice_out(Block, i, x): - if haliax.is_named_array(x): + if isinstance(x, haliax.core.NamedArray): if haliax.selects_axis(x.axes, Block): return x[Block, i] else: @@ -411,7 +411,7 @@ class Stacked(ModuleWithStateDictSerialization, Generic[M]): else: return tuple(x for _ in range(self.Block.size)) - leaves, structure = jax.tree_util.tree_flatten(self.stacked, is_leaf=haliax.is_named_array) + leaves, structure = jax.tree_util.tree_flatten(self.stacked, is_leaf=haliax.util.is_named_array) unstacked_leaves = tuple(map(unbatch_leaf, leaves)) # now we need to transpose the leaves unstacked_leaves = tuple(zip(*unstacked_leaves)) diff --git a/src/haliax/partitioning.py b/src/haliax/partitioning.py index bce942c..4043671 100644 --- a/src/haliax/partitioning.py +++ b/src/haliax/partitioning.py @@ -20,7 +20,7 @@ from .axis import Axis, AxisSelection, AxisSelector, axis_spec_to_shape_dict from .core import NamedArray from .jax_utils import Static, is_in_jit, is_jax_array_like, is_on_mac_metal from .tree_util import hashable_combine, hashable_partition -from .util import StringHolderEnum, ensure_tuple +from .util import StringHolderEnum PhysicalAxisSpec = Union[(str), Sequence[str]] diff --git a/src/haliax/random.py b/src/haliax/random.py index a2561da..3ab8ad8 100644 --- a/src/haliax/random.py +++ b/src/haliax/random.py @@ -1,7 +1,4 @@ """Wrappers around jax.random functions.""" -import functools -import inspect -import warnings from typing import Optional import jax.random as jrandom diff --git a/src/haliax/typing.py b/src/haliax/typing.py deleted file mode 100644 index 6cfc6e0..0000000 --- a/src/haliax/typing.py +++ /dev/null @@ -1,88 +0,0 @@ -from __future__ import annotations - -import typing as tp -from dataclasses import dataclass, replace - -import jax.numpy as jnp - -from .core import NamedArray, NamedArrayAxes, _parse_namedarray_axes - - -@dataclass(frozen=True) -class DTypeCategory: - """Represents a dtype category such as ``float`` or ``int``.""" - - name: str - category: tp.Any - - def __repr__(self) -> str: # pragma: no cover - trivial - return self.name - - -def _wrap_namedarray_with_dtype(dtype): - class DTypeType: - def __class_getitem__(cls, axes_spec): - axes = _parse_namedarray_axes(axes_spec) - axes_with_dtype = replace(axes, dtype=dtype) - return tp.Annotated[NamedArray, axes_with_dtype] - - return DTypeType - - -def _wrap_namedarray_with_category(category: DTypeCategory): - class DTypeType: - def __class_getitem__(cls, axes_spec): - axes = _parse_namedarray_axes(axes_spec) - axes_with_dtype = replace(axes, dtype=category) - return tp.Annotated[NamedArray, axes_with_dtype] - - return DTypeType - - -f32 = _wrap_namedarray_with_dtype(jnp.float32) -f64 = _wrap_namedarray_with_dtype(jnp.float64) -f16 = _wrap_namedarray_with_dtype(jnp.float16) -bf16 = _wrap_namedarray_with_dtype(jnp.bfloat16) - -i8 = _wrap_namedarray_with_dtype(jnp.int8) -i16 = _wrap_namedarray_with_dtype(jnp.int16) -i32 = _wrap_namedarray_with_dtype(jnp.int32) -i64 = _wrap_namedarray_with_dtype(jnp.int64) - -u8 = _wrap_namedarray_with_dtype(jnp.uint8) -u16 = _wrap_namedarray_with_dtype(jnp.uint16) -u32 = _wrap_namedarray_with_dtype(jnp.uint32) -u64 = _wrap_namedarray_with_dtype(jnp.uint64) - -bool_ = _wrap_namedarray_with_dtype(jnp.bool_) -complex64 = _wrap_namedarray_with_dtype(jnp.complex64) -complex128 = _wrap_namedarray_with_dtype(jnp.complex128) - - -Float = _wrap_namedarray_with_category(DTypeCategory("float", jnp.floating)) -Complex = _wrap_namedarray_with_category(DTypeCategory("complex", jnp.complexfloating)) -Int = _wrap_namedarray_with_category(DTypeCategory("int", jnp.signedinteger)) -UInt = _wrap_namedarray_with_category(DTypeCategory("uint", jnp.unsignedinteger)) - - -__all__ = [ - "f32", - "f64", - "f16", - "bf16", - "i8", - "i16", - "i32", - "i64", - "u8", - "u16", - "u32", - "u64", - "bool_", - "complex64", - "complex128", - "Float", - "Complex", - "Int", - "UInt", -] diff --git a/src/haliax/wrap.py b/src/haliax/wrap.py index 8a19bde..8af9063 100644 --- a/src/haliax/wrap.py +++ b/src/haliax/wrap.py @@ -1,11 +1,8 @@ -import typing from typing import Optional, Protocol import jax -import jax.numpy as jnp from haliax.core import NamedArray, _broadcast_order, broadcast_to -from haliax.jax_utils import is_scalarish from .axis import AxisSelection, AxisSelector, axis_spec_to_shape_dict, eliminate_axes diff --git a/tests/test_attention.py b/tests/test_attention.py index 9d5479d..11b9e77 100644 --- a/tests/test_attention.py +++ b/tests/test_attention.py @@ -1,4 +1,3 @@ -import jax.numpy as jnp import numpy as np from jax.random import PRNGKey diff --git a/tests/test_dot.py b/tests/test_dot.py index d4c306c..9f9d2fa 100644 --- a/tests/test_dot.py +++ b/tests/test_dot.py @@ -3,7 +3,7 @@ import pytest from jax import numpy as jnp import haliax as hax -from haliax import Axis, NamedArray +from haliax import Axis def test_dot(): diff --git a/tests/test_dtype_typing.py b/tests/test_dtype_typing.py index 805ae27..ef52e58 100644 --- a/tests/test_dtype_typing.py +++ b/tests/test_dtype_typing.py @@ -5,7 +5,7 @@ import typing import jax.numpy as jnp from haliax import Axis, NamedArray -from haliax.typing import Float, Int, f32, i32 +from haliax.haxtyping import Float, Int, f32, i32 def test_dtype_and_axes_annotation(): diff --git a/tests/test_namedarray_typing.py b/tests/test_namedarray_typing.py index 6259796..00a0ee3 100644 --- a/tests/test_namedarray_typing.py +++ b/tests/test_namedarray_typing.py @@ -4,13 +4,13 @@ import typing import jax.numpy as jnp -from haliax import Axis, Named, NamedArray -from haliax.typing import Float, Int, f32, i32 +from haliax import Axis, NamedArray +from haliax.haxtyping import Float, Int, f32, i32, Named def test_namedarray_type_syntax(): axes1 = typing.get_args(NamedArray["batch", "embed"])[1] - axes2 = typing.get_args(Named["batch embed"])[1] # type: ignore + axes2 = typing.get_args(Named[NamedArray, "batch embed"])[1] # type: ignore assert axes1 == axes2 axes3 = typing.get_args(NamedArray["batch embed ..."])[1] @@ -30,7 +30,7 @@ def test_namedarray_type_syntax(): def test_named_param_annotation(): - def foo(x: Named["batch", "embed"]): # type: ignore + def foo(x: f32[NamedArray, "batch embed"]): # type: ignore # noqa: F722 pass axes = typing.get_args(typing.get_type_hints(foo, include_extras=True)["x"])[1] @@ -42,7 +42,7 @@ def test_namedarray_runtime_check(): Embed = Axis("embed", 3) arr = NamedArray(jnp.zeros((Batch.size, Embed.size)), (Batch, Embed)) assert arr.matches_axes(NamedArray["batch", "embed"]) - assert arr.matches_axes(Named["batch embed"]) # type: ignore + assert arr.matches_axes(Named[NamedArray,"batch embed"]) # type: ignore assert arr.matches_axes(NamedArray["batch embed ..."]) assert arr.matches_axes(NamedArray[{"batch", "embed"}]) assert arr.matches_axes(NamedArray[{"batch", "embed", ...}]) @@ -60,5 +60,5 @@ def test_namedarray_runtime_check_with_dtype(): def test_namedarray_runtime_check_with_category(): B = Axis("batch", 1) arr = NamedArray(jnp.zeros((B.size,), dtype=jnp.float32), (B,)) - assert arr.matches_axes(Float["batch"]) # type: ignore - assert not arr.matches_axes(Int["batch"]) # type: ignore + assert arr.matches_axes(Float[NamedArray, "batch"]) # type: ignore + assert not arr.matches_axes(Int[NamedArray, "batch"]) # type: ignore diff --git a/tests/test_scatter_gather.py b/tests/test_scatter_gather.py index 18793b7..7ab0684 100644 --- a/tests/test_scatter_gather.py +++ b/tests/test_scatter_gather.py @@ -1,4 +1,3 @@ -import jax import jax.numpy as jnp import haliax as hax diff --git a/tests/test_tree_util.py b/tests/test_tree_util.py index 4ad7f55..901f6d4 100644 --- a/tests/test_tree_util.py +++ b/tests/test_tree_util.py @@ -3,7 +3,6 @@ import dataclasses import equinox as eqx import jax import jax.numpy as jnp -from chex import assert_trees_all_close import haliax as hax import haliax.tree_util as htu commit 8e912d32c74ed85c8017e47c1c079785eeecc864 Date: 2025-07-07T11:36:03-07:00 pre-commit in dev diff --git a/pyproject.toml b/pyproject.toml index 4453622..6759162 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -38,7 +38,8 @@ dev=["pytest >= 7.4.0", "mypy >= 0.910", "mkdocs >= 1.4.3", "mkdocs-material >= "pymdown-extensions", "pygments", "pymdown-extensions", - "chex>=0.1.86" + "chex>=0.1.86", + "pre-commit", ] commit 76c5481785c45becb1a484a4041ecb0ce3620ebb Date: 2025-07-07T23:28:09-07:00 Document uv workflow (#158) * docs: document uv run usage * Update AGENTS.md diff --git a/AGENTS.md b/AGENTS.md index 42b19ab..1d91b54 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -25,7 +25,8 @@ repository. Follow these notes when implementing new features or fixing bugs. * **Formatting and Linting**: We use `ruff` via `pre-commit`. * **Typing**: the code base uses `mypy` for static type checking. `mypy` is run by pre‑commit and the configuration is found in `pyproject.toml`. -* **Run `pre-commit run --all-files`** before committing. The CI workflows run the same checks. +* **Run `uv run pre-commit run --all-files`** before committing. The CI workflows run the same checks. +* **Use `uv run` for commands.** When running tools like `pytest` or other scripts, invoke them via `uv run` so the development dependencies are active. * **Doc Strings**: All public functions, classes, and modules should have docstrings, unless their purpose is painfully obvious. Use [Google style](https://google.github.io/styleguide/pyguide.html#38-comments-and-docstrings) for @@ -44,12 +45,10 @@ repository. Follow these notes when implementing new features or fixing bugs. ## Testing -* Tests are executed with `pytest`. The default workflow runs - `pytest tests -m "not entry and not slow and not ray"`. +* Tests are executed with `pytest`. The default workflow runs `uv run pytest tests`. * In general, never relax tolerances in floating point tests unless specifically discussed with the team. Use `assert_allclose` with appropriate tolerances for numerical comparisons. We typically use 1e-4 for more complex modules, and 1e-5 for simpler ones. -* Tests should be reasonably fast. Mark long-running tests with @pytest.mark.slow so they are excluded from the default suite. * Always mark tests that depend on pytorch with `@skip_if_no_torch` to ensure they are skipped when PyTorch is not available. This is particularly important for tests that require PyTorch-specific functionality. @@ -59,11 +58,6 @@ repository. Follow these notes when implementing new features or fixing bugs. * **Generic code**: many utilities are written with Python generics and dataclasses. Where possible, write reusable functions or classes that operate over TypeVars instead of hard coding concrete types. -* **Configurations**: configuration files are dataclasses loaded via `draccus`. Keep configs - declarative and typed. -* **Reproducibility**: Levanter aims for deterministic training where possible. Avoid sources of - nondeterminism unless explicitly required. -* Prefer Stacked with fold or scan over writing custom loops, for better compile times and gradient checkpointing support ## Library conventions - Haliax revolves around `NamedArray` and explicit `Axis` objects. Prefer APIs that accept diff --git a/pyproject.toml b/pyproject.toml index 6759162..29f202e 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -31,13 +31,20 @@ dependencies = [ ] dynamic =[ "version" ] -[project.optional-dependencies] -dev=["pytest >= 7.4.0", "mypy >= 0.910", "mkdocs >= 1.4.3", "mkdocs-material >= 7.3.3", "mkdocstrings >= 0.22.0", - "mkdocs-literate-nav >= 0.6.0", "mkdocs-macros-plugin >= 0.7.0", "mkdocstrings-python >= 1.1.2", + +[dependency-groups] +dev = [ + "pytest >= 7.4.0", + "mypy >= 0.910", + "mkdocs >= 1.4.3", + "mkdocs-material >= 7.3.3", + "mkdocstrings >= 0.22.0", + "mkdocs-literate-nav >= 0.6.0", + "mkdocs-macros-plugin >= 0.7.0", + "mkdocstrings-python >= 1.1.2", "mkdocs-include-markdown-plugin", "pymdown-extensions", "pygments", - "pymdown-extensions", "chex>=0.1.86", "pre-commit", ] commit 0c9522be137d8b7ff1594846023e48e0ee74fef5 Date: 2025-07-07T23:30:36-07:00 docs: add playbook for type annotations (#149) diff --git a/.playbooks/add-types.md b/.playbooks/add-types.md new file mode 100644 index 0000000..a10bb7f --- /dev/null +++ b/.playbooks/add-types.md @@ -0,0 +1,45 @@ +# Adding NamedArray Type Annotations + +This playbook explains how to migrate existing code to use the new type +annotation helpers described in `docs/typing.md`. + +1. **Read the documentation**: Familiarise yourself with `docs/typing.md`. + It describes the `Named[...]` syntax and the dtype aware helpers in + `haliax.typing`. +2. **Annotate parameters**: Replace plain `NamedArray` annotations with + `Named[...]` that lists the required axes. Use ellipses or sets when the + exact order is flexible. + + ```python + from haliax import Named + + # old + def foo(x: NamedArray) -> NamedArray: + ... + + # new + def foo(x: Named["batch", "embed"]) -> Named["batch", "embed"]: + ... + ``` +3. **Annotate dtypes when needed**: If the dtype matters, import symbolic dtypes + from `haliax.typing` (e.g. `ht.f32`, `ht.i32`). They can be indexed just + like `Named`. + + ```python + import haliax.typing as ht + + def bar(x: ht.f32["batch"]): + ... + ``` +4. **Runtime validation**: Use `arr.matches_axes(...)` to check that a + `NamedArray` conforms to the expected axes and dtype at runtime. + + ```python + if not arr.matches_axes(Named["batch embed ..."]): + raise ValueError("unexpected axes") + ``` +5. **Update return types**: Functions returning `NamedArray` should annotate + their return values using the same conventions. + +Following these steps will gradually port legacy code to the new +annotation style. commit 2d8c424276206937a55fed924aaa6afd1ba08f55 Date: 2025-07-07T23:32:45-07:00 Add vmap docs for Stacked (#153) * Add docs for Stacked.vmap * Merge branch 'main' into work diff --git a/AGENTS.md b/AGENTS.md index 1d91b54..ac360a7 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -16,8 +16,7 @@ repository. Follow these notes when implementing new features or fixing bugs. ## Playbook -- At the moment, there are no playbooks available. If you have a repeatable task that you think - should be documented, please create a new markdown file in `.playbooks/` and add it to the list above. +- Adding Haliax-style tensor typing annotations are described in @.playbooks/add-typing.md ## Code Style @@ -58,6 +57,11 @@ repository. Follow these notes when implementing new features or fixing bugs. * **Generic code**: many utilities are written with Python generics and dataclasses. Where possible, write reusable functions or classes that operate over TypeVars instead of hard coding concrete types. +* **Configurations**: configuration files are dataclasses loaded via `draccus`. Keep configs + declarative and typed. +* **Reproducibility**: Levanter aims for deterministic training where possible. Avoid sources of + nondeterminism unless explicitly required. +* Prefer Stacked with fold or scan over writing custom loops, for better compile times and gradient checkpointing support ## Library conventions - Haliax revolves around `NamedArray` and explicit `Axis` objects. Prefer APIs that accept diff --git a/docs/scan.md b/docs/scan.md index 4fe9d4f..1a70c98 100644 --- a/docs/scan.md +++ b/docs/scan.md @@ -405,6 +405,17 @@ blocks = Stacked.init(Layers, Gpt2Block)( Any NamedArray passed to the Stacked init will have its Layers axis (if present) vmapped over. Any JAX array will have its first axis vmapped over. +#### Apply Blocks in Parallel with `vmap` + +Sometimes you may want to apply each block independently, without feeding the +output of one block into the next. `Stacked.vmap` does exactly that: it uses +[`haliax.vmap`][] to broadcast the initial value to every block and evaluates +them in parallel, returning the stack of outputs. + +```python +y = stacked.vmap(x) +``` + #### Fold Blocks vs Scan Blocks diff --git a/docs/vmap.md b/docs/vmap.md index e2c7394..5931e11 100644 --- a/docs/vmap.md +++ b/docs/vmap.md @@ -1,5 +1,9 @@ ## Vectorization + +This primitive is also used by [`Stacked.vmap`](scan.md#apply-blocks-in-parallel-with-vmap) +to apply an entire stack of blocks in parallel. + (This is a work in progress. Please contact dlwh for more information.) ::: haliax.vmap diff --git a/src/haliax/nn/scan.py b/src/haliax/nn/scan.py index cac66f9..dc3c6e8 100644 --- a/src/haliax/nn/scan.py +++ b/src/haliax/nn/scan.py @@ -233,6 +233,8 @@ class Stacked(ModuleWithStateDictSerialization, Generic[M]): output, while "scan" is the same as a for loop that accumulates a list of outputs as well as the final output. Stacked also supports gradient checkpointing, which is useful for very large models that don't fit in memory. + If your blocks are independent of each other you can instead use :py:meth:`Stacked.vmap` + to apply every block in parallel. Typically only one of "fold" or "scan" can be used with a given Stacked module, depending on the what the module returns: if the module returns a single output, use "fold"; if the module returns a sequence of outputs and @@ -382,6 +384,35 @@ class Stacked(ModuleWithStateDictSerialization, Generic[M]): return do_fold(init, *args, **kwargs) + def vmap(self, init, *extra_args, **extra_kwargs): + """Apply each block independently using :func:`haliax.vmap`. + + This maps ``init`` through every block in parallel, so each block + receives the same ``init`` but its own parameters. Extra ``args`` and + ``kwargs`` are also mapped over the block axis by default. + + Returns the stacked outputs of each block. + """ + + if haliax.is_named_array(init): + init = init.broadcast_axis(self.Block) + elif haliax.jax_utils.is_jax_array_like(init): + init = jnp.broadcast_to(init, (self.Block.size,) + init.shape) + else: + init = tuple(init for _ in range(self.Block.size)) + + arg_spec = (0, 0) + (0,) * len(extra_args) + kwarg_spec = {k: 0 for k in extra_kwargs} + + do_vmap = haliax.vmap( + Stacked._do_block, + self.Block, + default=0, + args=arg_spec, + kwargs=kwarg_spec, + ) + return do_vmap(init, self.stacked, *extra_args, **extra_kwargs) + @staticmethod def _do_block(carry, block, *extra_args, **extra_kwargs): return block(carry, *extra_args, **extra_kwargs) diff --git a/tests/test_scan.py b/tests/test_scan.py index eb1865d..b807147 100644 --- a/tests/test_scan.py +++ b/tests/test_scan.py @@ -45,6 +45,30 @@ def test_unstacked(): assert hax.all(module.array == m.stacked.array[i]) +def test_vmap(): + class Module(eqx.Module): + weight: hax.NamedArray + + def __call__(self, x): + return x + self.weight + + @staticmethod + def init(weight): + return Module(weight=weight) + + Block = hax.Axis("block", 4) + E = hax.Axis("E", 10) + + weights = hax.random.uniform(jax.random.PRNGKey(0), (Block, E)) + m = Stacked.init(Block, Module)(weight=weights) + + x = hax.random.uniform(jax.random.PRNGKey(1), (E,)) + y = m.vmap(x) + + assert y.axes == (Block, E) + assert hax.all(y == weights + x) + + def test_seq_and_stacked_give_same_results(): class Module(eqx.Module): named: hax.NamedArray commit 56628bd2b7b06fa321b9663a4a926070fbc98191 Date: 2025-07-07T23:57:28-07:00 Add fold_via and scan_via to Stacked (#157) diff --git a/src/haliax/nn/scan.py b/src/haliax/nn/scan.py index dc3c6e8..ba8278c 100644 --- a/src/haliax/nn/scan.py +++ b/src/haliax/nn/scan.py @@ -2,7 +2,7 @@ import dataclasses import functools import re import warnings -from typing import Any, Dict, Generic, Optional, Protocol, Sequence, Type, TypeVar, cast +from typing import Any, Callable, Dict, Generic, Optional, Protocol, Sequence, Type, TypeVar, cast, overload, ParamSpec import equinox as eqx import jax @@ -20,8 +20,21 @@ from ..axis import Axis M = TypeVar("M", bound=eqx.Module) M_co = TypeVar("M_co", bound=eqx.Module, covariant=True) +M_contra = TypeVar("M_contra", bound=eqx.Module, contravariant=True) S = TypeVar("S", bound=eqx.Module) T = TypeVar("T") +CarryT = TypeVar("CarryT") +OutputT_co = TypeVar("OutputT_co", covariant=True) +P = ParamSpec("P") + +class FoldFunction(Protocol[M_contra, CarryT]): + def __call__(self, module: M_contra, carry: CarryT) -> CarryT: + ... + + +class ScanFunction(Protocol[M_contra, CarryT, OutputT_co]): + def __call__(self, module: M_contra, carry: CarryT) -> tuple[CarryT, OutputT_co]: + ... class ModuleInit(Protocol[M_co]): @@ -384,6 +397,52 @@ class Stacked(ModuleWithStateDictSerialization, Generic[M]): return do_fold(init, *args, **kwargs) + @overload + def fold_via(self, fn: FoldFunction[M, CarryT]) -> Callable[[CarryT], CarryT]: + ... + + @overload + def fold_via(self, fn: Callable[[M, CarryT], CarryT]) -> Callable[[CarryT], CarryT]: + ... + + def fold_via(self, fn: Callable[..., CarryT]): + """Return a function that folds over the stack using ``fn``. + + ``fn`` should take a block and a carry and return a new carry. The + returned function mirrors :func:`haliax.fold` over the block axis. + """ + + def do_block(carry: CarryT, block: M) -> CarryT: + return fn(block, carry) + + def do_fold(init: CarryT) -> CarryT: + return haliax.fold(do_block, self.Block, remat=self.gradient_checkpointing)(init, self.stacked) + + return do_fold + + @overload + def scan_via(self, fn: ScanFunction[M, CarryT, OutputT_co]) -> Callable[[CarryT], tuple[CarryT, OutputT_co]]: + ... + + @overload + def scan_via(self, fn: Callable[[M, CarryT], tuple[CarryT, OutputT_co]]) -> Callable[[CarryT], tuple[CarryT, OutputT_co]]: + ... + + def scan_via(self, fn: Callable[..., tuple[CarryT, OutputT_co]]): + """Return a function that scans over the stack using ``fn``. + + ``fn`` should take a block and a carry and return ``(carry, output)``. + Semantics match :func:`haliax.scan` over the block axis. + """ + + def do_block(carry: CarryT, block: M) -> tuple[CarryT, OutputT_co]: + return fn(block, carry) + + def do_scan(init: CarryT) -> tuple[CarryT, OutputT_co]: + return haliax.scan(do_block, self.Block, remat=self.gradient_checkpointing)(init, self.stacked) + + return do_scan + def vmap(self, init, *extra_args, **extra_kwargs): """Apply each block independently using :func:`haliax.vmap`. diff --git a/tests/test_scan.py b/tests/test_scan.py index b807147..c251d3d 100644 --- a/tests/test_scan.py +++ b/tests/test_scan.py @@ -309,3 +309,58 @@ def test_checkpoint_carries(name, policy, expected_scan_shapes, check_offloading assert target is not None, f"Could not find named value for {name}" assert found_saved, f"Could not find offloaded value for {name}" + + +def test_fold_via(): + class Module(eqx.Module): + w: hax.NamedArray + + def __call__(self, x): + return x + self.w + + def intermediate(self, x): + return x + 2 * self.w + + @staticmethod + def init(named): + return Module(w=named) + + Block = hax.Axis("block", 3) + E = hax.Axis("E", 5) + + named = hax.random.uniform(jax.random.PRNGKey(0), (Block, E)) + m = Stacked.init(Block, Module)(named=named) + + x = hax.random.uniform(jax.random.PRNGKey(1), (E,)) + result = m.fold_via(Module.intermediate)(x) + + expected = x + 2 * hax.sum(named, Block) + assert hax.all(hax.isclose(result, expected)) + + +def test_scan_via(): + class Module(eqx.Module): + w: hax.NamedArray + + def with_output(self, x): + out = x + self.w + return out, 2 * self.w + + @staticmethod + def init(named): + return Module(w=named) + + Block = hax.Axis("block", 4) + E = hax.Axis("E", 6) + + named = hax.random.uniform(jax.random.PRNGKey(0), (Block, E)) + m = Stacked.init(Block, Module)(named=named) + + x = hax.random.uniform(jax.random.PRNGKey(1), (E,)) + carry, outs = m.scan_via(Module.with_output)(x) + + expected_carry = x + hax.sum(named, Block) + expected_outs = 2 * named + + assert hax.all(hax.isclose(carry, expected_carry)) + assert hax.all(hax.isclose(outs, expected_outs)) commit a19c82028c9dfb37dae141963f64a84179e325d6 Date: 2025-07-07T23:57:54-07:00 use uv in tests, fix agents.md env variable (#160) diff --git a/.github/workflows/run_tests.yaml b/.github/workflows/run_tests.yaml index e376f96..9d805f1 100644 --- a/.github/workflows/run_tests.yaml +++ b/.github/workflows/run_tests.yaml @@ -15,9 +15,8 @@ jobs: python-version: 3.10.11 - name: Install dependencies run: | - python -m pip install --upgrade pip - pip install flake8 pytest - pip install -e .[dev] + python -m pip install uv + uv sync - name: Test with pytest run: | - XLA_FLAGS=--xla_force_host_platform_device_count=8 PYTHONPATH=tests:src:. pytest tests + XLA_FLAGS=--xla_force_host_platform_device_count=8 PYTHONPATH=tests:src:. uv run pytest tests diff --git a/AGENTS.md b/AGENTS.md index ac360a7..2642efa 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -12,11 +12,11 @@ repository. Follow these notes when implementing new features or fixing bugs. floating point tests, add that to the list. * **Playbooks.** Sometimes, there are repeatable tasks (e.g. porting models) for which we follow a standard set of steps. Please reference `.playbooks/` to see what playbooks are available, or see the list below. If you want to add a playbook - write a markdown doc named e.g. `.playbooks/port-models.md` and add a pointer to it in the list below. + write a markdown doc named e.g. `.playbooks/add-types.md` and add a pointer to it in the list below. ## Playbook -- Adding Haliax-style tensor typing annotations are described in @.playbooks/add-typing.md +- Adding Haliax-style tensor typing annotations are described in @.playbooks/add-types.md ## Code Style @@ -44,7 +44,7 @@ repository. Follow these notes when implementing new features or fixing bugs. ## Testing -* Tests are executed with `pytest`. The default workflow runs `uv run pytest tests`. +* Tests are executed with `pytest`. The default workflow runs ` XLA_FLAGS=--xla_force_host_platform_device_count=8 PYTHONPATH=tests:src:. uv run pytest tests`. * In general, never relax tolerances in floating point tests unless specifically discussed with the team. Use `assert_allclose` with appropriate tolerances for numerical comparisons. We typically use 1e-4 for more complex modules, and 1e-5 for simpler ones. commit d7d09c4227e9f8185c6345a1eb9d54ca7d60efa3 Date: 2025-07-08T00:17:14-07:00 Num devices test (#161) * use uv in tests, fix agents.md env variable * uv lock diff --git a/uv.lock b/uv.lock new file mode 100644 index 0000000..53078e3 --- /dev/null +++ b/uv.lock @@ -0,0 +1,1711 @@ +version = 1 +revision = 1 +requires-python = ">=3.10" +resolution-markers = [ + "python_full_version >= '3.13'", + "python_full_version == '3.12.*'", + "python_full_version == '3.11.*'", + "python_full_version < '3.11'", +] + +[[package]] +name = "absl-py" +version = "2.3.1" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/10/2a/c93173ffa1b39c1d0395b7e842bbdc62e556ca9d8d3b5572926f3e4ca752/absl_py-2.3.1.tar.gz", hash = "sha256:a97820526f7fbfd2ec1bce83f3f25e3a14840dac0d8e02a0b71cd75db3f77fc9", size = 116588 } +wheels = [ + { url = "https://files.pythonhosted.org/packages/8f/aa/ba0014cc4659328dc818a28827be78e6d97312ab0cb98105a770924dc11e/absl_py-2.3.1-py3-none-any.whl", hash = "sha256:eeecf07f0c2a93ace0772c92e596ace6d3d3996c042b2128459aaae2a76de11d", size = 135811 }, +] + +[[package]] +name = "aqtp" +version = "0.8.4" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "absl-py" }, + { name = "flax" }, + { name = "jax" }, + { name = "jaxlib" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/c3/29/efd4017ad572cca8453f17c2e6613a22bc5b1d8680a8c350d955570d3dba/aqtp-0.8.4.tar.gz", hash = "sha256:e3a887f0f78e3f5ce5ba1dfe57b4de074fd978054d3457217d92c90538654ba6", size = 884549 } +wheels = [ + { url = "https://files.pythonhosted.org/packages/81/dc/f15b71bdf6c20b362005c37e6d9d3ddf582cb00c57b01b2734299e699e35/aqtp-0.8.4-py3-none-any.whl", hash = "sha256:36c7b88973d7cb892fbaba95550383ef6c011943af6e3407a4c19d8f7682abdb", size = 900357 }, +] + +[[package]] +name = "babel" +version = "2.17.0" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/7d/6b/d52e42361e1aa00709585ecc30b3f9684b3ab62530771402248b1b1d6240/babel-2.17.0.tar.gz", hash = "sha256:0c54cffb19f690cdcc52a3b50bcbf71e07a808d1c80d549f2459b9d2cf0afb9d", size = 9951852 } +wheels = [ + { url = "https://files.pythonhosted.org/packages/b7/b8/3fe70c75fe32afc4bb507f75563d39bc5642255d1d94f1f23604725780bf/babel-2.17.0-py3-none-any.whl", hash = "sha256:4d0b53093fdfb4b21c92b5213dba5a1b23885afa8383709427046b21c366e5f2", size = 10182537 }, +] + +[[package]] +name = "backrefs" +version = "5.9" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/eb/a7/312f673df6a79003279e1f55619abbe7daebbb87c17c976ddc0345c04c7b/backrefs-5.9.tar.gz", hash = "sha256:808548cb708d66b82ee231f962cb36faaf4f2baab032f2fbb783e9c2fdddaa59", size = 5765857 } +wheels = [ + { url = "https://files.pythonhosted.org/packages/19/4d/798dc1f30468134906575156c089c492cf79b5a5fd373f07fe26c4d046bf/backrefs-5.9-py310-none-any.whl", hash = "sha256:db8e8ba0e9de81fcd635f440deab5ae5f2591b54ac1ebe0550a2ca063488cd9f", size = 380267 }, + { url = "https://files.pythonhosted.org/packages/55/07/f0b3375bf0d06014e9787797e6b7cc02b38ac9ff9726ccfe834d94e9991e/backrefs-5.9-py311-none-any.whl", hash = "sha256:6907635edebbe9b2dc3de3a2befff44d74f30a4562adbb8b36f21252ea19c5cf", size = 392072 }, + { url = "https://files.pythonhosted.org/packages/9d/12/4f345407259dd60a0997107758ba3f221cf89a9b5a0f8ed5b961aef97253/backrefs-5.9-py312-none-any.whl", hash = "sha256:7fdf9771f63e6028d7fee7e0c497c81abda597ea45d6b8f89e8ad76994f5befa", size = 397947 }, + { url = "https://files.pythonhosted.org/packages/10/bf/fa31834dc27a7f05e5290eae47c82690edc3a7b37d58f7fb35a1bdbf355b/backrefs-5.9-py313-none-any.whl", hash = "sha256:cc37b19fa219e93ff825ed1fed8879e47b4d89aa7a1884860e2db64ccd7c676b", size = 399843 }, + { url = "https://files.pythonhosted.org/packages/fc/24/b29af34b2c9c41645a9f4ff117bae860291780d73880f449e0b5d948c070/backrefs-5.9-py314-none-any.whl", hash = "sha256:df5e169836cc8acb5e440ebae9aad4bf9d15e226d3bad049cf3f6a5c20cc8dc9", size = 411762 }, + { url = "https://files.pythonhosted.org/packages/41/ff/392bff89415399a979be4a65357a41d92729ae8580a66073d8ec8d810f98/backrefs-5.9-py39-none-any.whl", hash = "sha256:f48ee18f6252b8f5777a22a00a09a85de0ca931658f1dd96d4406a34f3748c60", size = 380265 }, +] + +[[package]] +name = "bracex" +version = "2.6" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/63/9a/fec38644694abfaaeca2798b58e276a8e61de49e2e37494ace423395febc/bracex-2.6.tar.gz", hash = "sha256:98f1347cd77e22ee8d967a30ad4e310b233f7754dbf31ff3fceb76145ba47dc7", size = 26642 } +wheels = [ + { url = "https://files.pythonhosted.org/packages/9d/2a/9186535ce58db529927f6cf5990a849aa9e052eea3e2cfefe20b9e1802da/bracex-2.6-py3-none-any.whl", hash = "sha256:0b0049264e7340b3ec782b5cb99beb325f36c3782a32e36e876452fd49a09952", size = 11508 }, +] + +[[package]] +name = "certifi" +version = "2025.6.15" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/73/f7/f14b46d4bcd21092d7d3ccef689615220d8a08fb25e564b65d20738e672e/certifi-2025.6.15.tar.gz", hash = "sha256:d747aa5a8b9bbbb1bb8c22bb13e22bd1f18e9796defa16bab421f7f7a317323b", size = 158753 } +wheels = [ + { url = "https://files.pythonhosted.org/packages/84/ae/320161bd181fc06471eed047ecce67b693fd7515b16d495d8932db763426/certifi-2025.6.15-py3-none-any.whl", hash = "sha256:2e0c7ce7cb5d8f8634ca55d2ba7e6ec2689a2fd6537d8dec1296a477a4910057", size = 157650 }, +] + +[[package]] +name = "cfgv" +version = "3.4.0" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/11/74/539e56497d9bd1d484fd863dd69cbbfa653cd2aa27abfe35653494d85e94/cfgv-3.4.0.tar.gz", hash = "sha256:e52591d4c5f5dead8e0f673fb16db7949d2cfb3f7da4582893288f0ded8fe560", size = 7114 } +wheels = [ + { url = "https://files.pythonhosted.org/packages/c5/55/51844dd50c4fc7a33b653bfaba4c2456f06955289ca770a5dbd5fd267374/cfgv-3.4.0-py2.py3-none-any.whl", hash = "sha256:b7265b1f29fd3316bfcd2b330d63d024f2bfd8bcb8b0272f8e19a504856c48f9", size = 7249 }, +] + +[[package]] +name = "charset-normalizer" +version = "3.4.2" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/e4/33/89c2ced2b67d1c2a61c19c6751aa8902d46ce3dacb23600a283619f5a12d/charset_normalizer-3.4.2.tar.gz", hash = "sha256:5baececa9ecba31eff645232d59845c07aa030f0c81ee70184a90d35099a0e63", size = 126367 } +wheels = [ + { url = "https://files.pythonhosted.org/packages/95/28/9901804da60055b406e1a1c5ba7aac1276fb77f1dde635aabfc7fd84b8ab/charset_normalizer-3.4.2-cp310-cp310-macosx_10_9_universal2.whl", hash = "sha256:7c48ed483eb946e6c04ccbe02c6b4d1d48e51944b6db70f697e089c193404941", size = 201818 }, + { url = "https://files.pythonhosted.org/packages/d9/9b/892a8c8af9110935e5adcbb06d9c6fe741b6bb02608c6513983048ba1a18/charset_normalizer-3.4.2-cp310-cp310-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:b2d318c11350e10662026ad0eb71bb51c7812fc8590825304ae0bdd4ac283acd", size = 144649 }, + { url = "https://files.pythonhosted.org/packages/7b/a5/4179abd063ff6414223575e008593861d62abfc22455b5d1a44995b7c101/charset_normalizer-3.4.2-cp310-cp310-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:9cbfacf36cb0ec2897ce0ebc5d08ca44213af24265bd56eca54bee7923c48fd6", size = 155045 }, + { url = "https://files.pythonhosted.org/packages/3b/95/bc08c7dfeddd26b4be8c8287b9bb055716f31077c8b0ea1cd09553794665/charset_normalizer-3.4.2-cp310-cp310-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:18dd2e350387c87dabe711b86f83c9c78af772c748904d372ade190b5c7c9d4d", size = 147356 }, + { url = "https://files.pythonhosted.org/packages/a8/2d/7a5b635aa65284bf3eab7653e8b4151ab420ecbae918d3e359d1947b4d61/charset_normalizer-3.4.2-cp310-cp310-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:8075c35cd58273fee266c58c0c9b670947c19df5fb98e7b66710e04ad4e9ff86", size = 149471 }, + { url = "https://files.pythonhosted.org/packages/ae/38/51fc6ac74251fd331a8cfdb7ec57beba8c23fd5493f1050f71c87ef77ed0/charset_normalizer-3.4.2-cp310-cp310-manylinux_2_5_i686.manylinux1_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:5bf4545e3b962767e5c06fe1738f951f77d27967cb2caa64c28be7c4563e162c", size = 151317 }, + { url = "https://files.pythonhosted.org/packages/b7/17/edee1e32215ee6e9e46c3e482645b46575a44a2d72c7dfd49e49f60ce6bf/charset_normalizer-3.4.2-cp310-cp310-musllinux_1_2_aarch64.whl", hash = "sha256:7a6ab32f7210554a96cd9e33abe3ddd86732beeafc7a28e9955cdf22ffadbab0", size = 146368 }, + { url = "https://files.pythonhosted.org/packages/26/2c/ea3e66f2b5f21fd00b2825c94cafb8c326ea6240cd80a91eb09e4a285830/charset_normalizer-3.4.2-cp310-cp310-musllinux_1_2_i686.whl", hash = "sha256:b33de11b92e9f75a2b545d6e9b6f37e398d86c3e9e9653c4864eb7e89c5773ef", size = 154491 }, + { url = "https://files.pythonhosted.org/packages/52/47/7be7fa972422ad062e909fd62460d45c3ef4c141805b7078dbab15904ff7/charset_normalizer-3.4.2-cp310-cp310-musllinux_1_2_ppc64le.whl", hash = "sha256:8755483f3c00d6c9a77f490c17e6ab0c8729e39e6390328e42521ef175380ae6", size = 157695 }, + { url = "https://files.pythonhosted.org/packages/2f/42/9f02c194da282b2b340f28e5fb60762de1151387a36842a92b533685c61e/charset_normalizer-3.4.2-cp310-cp310-musllinux_1_2_s390x.whl", hash = "sha256:68a328e5f55ec37c57f19ebb1fdc56a248db2e3e9ad769919a58672958e8f366", size = 154849 }, + { url = "https://files.pythonhosted.org/packages/67/44/89cacd6628f31fb0b63201a618049be4be2a7435a31b55b5eb1c3674547a/charset_normalizer-3.4.2-cp310-cp310-musllinux_1_2_x86_64.whl", hash = "sha256:21b2899062867b0e1fde9b724f8aecb1af14f2778d69aacd1a5a1853a597a5db", size = 150091 }, + { url = "https://files.pythonhosted.org/packages/1f/79/4b8da9f712bc079c0f16b6d67b099b0b8d808c2292c937f267d816ec5ecc/charset_normalizer-3.4.2-cp310-cp310-win32.whl", hash = "sha256:e8082b26888e2f8b36a042a58307d5b917ef2b1cacab921ad3323ef91901c71a", size = 98445 }, + { url = "https://files.pythonhosted.org/packages/7d/d7/96970afb4fb66497a40761cdf7bd4f6fca0fc7bafde3a84f836c1f57a926/charset_normalizer-3.4.2-cp310-cp310-win_amd64.whl", hash = "sha256:f69a27e45c43520f5487f27627059b64aaf160415589230992cec34c5e18a509", size = 105782 }, + { url = "https://files.pythonhosted.org/packages/05/85/4c40d00dcc6284a1c1ad5de5e0996b06f39d8232f1031cd23c2f5c07ee86/charset_normalizer-3.4.2-cp311-cp311-macosx_10_9_universal2.whl", hash = "sha256:be1e352acbe3c78727a16a455126d9ff83ea2dfdcbc83148d2982305a04714c2", size = 198794 }, + { url = "https://files.pythonhosted.org/packages/41/d9/7a6c0b9db952598e97e93cbdfcb91bacd89b9b88c7c983250a77c008703c/charset_normalizer-3.4.2-cp311-cp311-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:aa88ca0b1932e93f2d961bf3addbb2db902198dca337d88c89e1559e066e7645", size = 142846 }, + { url = "https://files.pythonhosted.org/packages/66/82/a37989cda2ace7e37f36c1a8ed16c58cf48965a79c2142713244bf945c89/charset_normalizer-3.4.2-cp311-cp311-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:d524ba3f1581b35c03cb42beebab4a13e6cdad7b36246bd22541fa585a56cccd", size = 153350 }, + { url = "https://files.pythonhosted.org/packages/df/68/a576b31b694d07b53807269d05ec3f6f1093e9545e8607121995ba7a8313/charset_normalizer-3.4.2-cp311-cp311-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:28a1005facc94196e1fb3e82a3d442a9d9110b8434fc1ded7a24a2983c9888d8", size = 145657 }, + { url = "https://files.pythonhosted.org/packages/92/9b/ad67f03d74554bed3aefd56fe836e1623a50780f7c998d00ca128924a499/charset_normalizer-3.4.2-cp311-cp311-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:fdb20a30fe1175ecabed17cbf7812f7b804b8a315a25f24678bcdf120a90077f", size = 147260 }, + { url = "https://files.pythonhosted.org/packages/a6/e6/8aebae25e328160b20e31a7e9929b1578bbdc7f42e66f46595a432f8539e/charset_normalizer-3.4.2-cp311-cp311-manylinux_2_5_i686.manylinux1_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:0f5d9ed7f254402c9e7d35d2f5972c9bbea9040e99cd2861bd77dc68263277c7", size = 149164 }, + { url = "https://files.pythonhosted.org/packages/8b/f2/b3c2f07dbcc248805f10e67a0262c93308cfa149a4cd3d1fe01f593e5fd2/charset_normalizer-3.4.2-cp311-cp311-musllinux_1_2_aarch64.whl", hash = "sha256:efd387a49825780ff861998cd959767800d54f8308936b21025326de4b5a42b9", size = 144571 }, + { url = "https://files.pythonhosted.org/packages/60/5b/c3f3a94bc345bc211622ea59b4bed9ae63c00920e2e8f11824aa5708e8b7/charset_normalizer-3.4.2-cp311-cp311-musllinux_1_2_i686.whl", hash = "sha256:f0aa37f3c979cf2546b73e8222bbfa3dc07a641585340179d768068e3455e544", size = 151952 }, + { url = "https://files.pythonhosted.org/packages/e2/4d/ff460c8b474122334c2fa394a3f99a04cf11c646da895f81402ae54f5c42/charset_normalizer-3.4.2-cp311-cp311-musllinux_1_2_ppc64le.whl", hash = "sha256:e70e990b2137b29dc5564715de1e12701815dacc1d056308e2b17e9095372a82", size = 155959 }, + { url = "https://files.pythonhosted.org/packages/a2/2b/b964c6a2fda88611a1fe3d4c400d39c66a42d6c169c924818c848f922415/charset_normalizer-3.4.2-cp311-cp311-musllinux_1_2_s390x.whl", hash = "sha256:0c8c57f84ccfc871a48a47321cfa49ae1df56cd1d965a09abe84066f6853b9c0", size = 153030 }, + { url = "https://files.pythonhosted.org/packages/59/2e/d3b9811db26a5ebf444bc0fa4f4be5aa6d76fc6e1c0fd537b16c14e849b6/charset_normalizer-3.4.2-cp311-cp311-musllinux_1_2_x86_64.whl", hash = "sha256:6b66f92b17849b85cad91259efc341dce9c1af48e2173bf38a85c6329f1033e5", size = 148015 }, + { url = "https://files.pythonhosted.org/packages/90/07/c5fd7c11eafd561bb51220d600a788f1c8d77c5eef37ee49454cc5c35575/charset_normalizer-3.4.2-cp311-cp311-win32.whl", hash = "sha256:daac4765328a919a805fa5e2720f3e94767abd632ae410a9062dff5412bae65a", size = 98106 }, + { url = "https://files.pythonhosted.org/packages/a8/05/5e33dbef7e2f773d672b6d79f10ec633d4a71cd96db6673625838a4fd532/charset_normalizer-3.4.2-cp311-cp311-win_amd64.whl", hash = "sha256:e53efc7c7cee4c1e70661e2e112ca46a575f90ed9ae3fef200f2a25e954f4b28", size = 105402 }, + { url = "https://files.pythonhosted.org/packages/d7/a4/37f4d6035c89cac7930395a35cc0f1b872e652eaafb76a6075943754f095/charset_normalizer-3.4.2-cp312-cp312-macosx_10_13_universal2.whl", hash = "sha256:0c29de6a1a95f24b9a1aa7aefd27d2487263f00dfd55a77719b530788f75cff7", size = 199936 }, + { url = "https://files.pythonhosted.org/packages/ee/8a/1a5e33b73e0d9287274f899d967907cd0bf9c343e651755d9307e0dbf2b3/charset_normalizer-3.4.2-cp312-cp312-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:cddf7bd982eaa998934a91f69d182aec997c6c468898efe6679af88283b498d3", size = 143790 }, + { url = "https://files.pythonhosted.org/packages/66/52/59521f1d8e6ab1482164fa21409c5ef44da3e9f653c13ba71becdd98dec3/charset_normalizer-3.4.2-cp312-cp312-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:fcbe676a55d7445b22c10967bceaaf0ee69407fbe0ece4d032b6eb8d4565982a", size = 153924 }, + { url = "https://files.pythonhosted.org/packages/86/2d/fb55fdf41964ec782febbf33cb64be480a6b8f16ded2dbe8db27a405c09f/charset_normalizer-3.4.2-cp312-cp312-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:d41c4d287cfc69060fa91cae9683eacffad989f1a10811995fa309df656ec214", size = 146626 }, + { url = "https://files.pythonhosted.org/packages/8c/73/6ede2ec59bce19b3edf4209d70004253ec5f4e319f9a2e3f2f15601ed5f7/charset_normalizer-3.4.2-cp312-cp312-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:4e594135de17ab3866138f496755f302b72157d115086d100c3f19370839dd3a", size = 148567 }, + { url = "https://files.pythonhosted.org/packages/09/14/957d03c6dc343c04904530b6bef4e5efae5ec7d7990a7cbb868e4595ee30/charset_normalizer-3.4.2-cp312-cp312-manylinux_2_5_i686.manylinux1_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:cf713fe9a71ef6fd5adf7a79670135081cd4431c2943864757f0fa3a65b1fafd", size = 150957 }, + { url = "https://files.pythonhosted.org/packages/0d/c8/8174d0e5c10ccebdcb1b53cc959591c4c722a3ad92461a273e86b9f5a302/charset_normalizer-3.4.2-cp312-cp312-musllinux_1_2_aarch64.whl", hash = "sha256:a370b3e078e418187da8c3674eddb9d983ec09445c99a3a263c2011993522981", size = 145408 }, + { url = "https://files.pythonhosted.org/packages/58/aa/8904b84bc8084ac19dc52feb4f5952c6df03ffb460a887b42615ee1382e8/charset_normalizer-3.4.2-cp312-cp312-musllinux_1_2_i686.whl", hash = "sha256:a955b438e62efdf7e0b7b52a64dc5c3396e2634baa62471768a64bc2adb73d5c", size = 153399 }, + { url = "https://files.pythonhosted.org/packages/c2/26/89ee1f0e264d201cb65cf054aca6038c03b1a0c6b4ae998070392a3ce605/charset_normalizer-3.4.2-cp312-cp312-musllinux_1_2_ppc64le.whl", hash = "sha256:7222ffd5e4de8e57e03ce2cef95a4c43c98fcb72ad86909abdfc2c17d227fc1b", size = 156815 }, + { url = "https://files.pythonhosted.org/packages/fd/07/68e95b4b345bad3dbbd3a8681737b4338ff2c9df29856a6d6d23ac4c73cb/charset_normalizer-3.4.2-cp312-cp312-musllinux_1_2_s390x.whl", hash = "sha256:bee093bf902e1d8fc0ac143c88902c3dfc8941f7ea1d6a8dd2bcb786d33db03d", size = 154537 }, + { url = "https://files.pythonhosted.org/packages/77/1a/5eefc0ce04affb98af07bc05f3bac9094513c0e23b0562d64af46a06aae4/charset_normalizer-3.4.2-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:dedb8adb91d11846ee08bec4c8236c8549ac721c245678282dcb06b221aab59f", size = 149565 }, + { url = "https://files.pythonhosted.org/packages/37/a0/2410e5e6032a174c95e0806b1a6585eb21e12f445ebe239fac441995226a/charset_normalizer-3.4.2-cp312-cp312-win32.whl", hash = "sha256:db4c7bf0e07fc3b7d89ac2a5880a6a8062056801b83ff56d8464b70f65482b6c", size = 98357 }, + { url = "https://files.pythonhosted.org/packages/6c/4f/c02d5c493967af3eda9c771ad4d2bbc8df6f99ddbeb37ceea6e8716a32bc/charset_normalizer-3.4.2-cp312-cp312-win_amd64.whl", hash = "sha256:5a9979887252a82fefd3d3ed2a8e3b937a7a809f65dcb1e068b090e165bbe99e", size = 105776 }, + { url = "https://files.pythonhosted.org/packages/ea/12/a93df3366ed32db1d907d7593a94f1fe6293903e3e92967bebd6950ed12c/charset_normalizer-3.4.2-cp313-cp313-macosx_10_13_universal2.whl", hash = "sha256:926ca93accd5d36ccdabd803392ddc3e03e6d4cd1cf17deff3b989ab8e9dbcf0", size = 199622 }, + { url = "https://files.pythonhosted.org/packages/04/93/bf204e6f344c39d9937d3c13c8cd5bbfc266472e51fc8c07cb7f64fcd2de/charset_normalizer-3.4.2-cp313-cp313-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:eba9904b0f38a143592d9fc0e19e2df0fa2e41c3c3745554761c5f6447eedabf", size = 143435 }, + { url = "https://files.pythonhosted.org/packages/22/2a/ea8a2095b0bafa6c5b5a55ffdc2f924455233ee7b91c69b7edfcc9e02284/charset_normalizer-3.4.2-cp313-cp313-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:3fddb7e2c84ac87ac3a947cb4e66d143ca5863ef48e4a5ecb83bd48619e4634e", size = 153653 }, + { url = "https://files.pythonhosted.org/packages/b6/57/1b090ff183d13cef485dfbe272e2fe57622a76694061353c59da52c9a659/charset_normalizer-3.4.2-cp313-cp313-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:98f862da73774290f251b9df8d11161b6cf25b599a66baf087c1ffe340e9bfd1", size = 146231 }, + { url = "https://files.pythonhosted.org/packages/e2/28/ffc026b26f441fc67bd21ab7f03b313ab3fe46714a14b516f931abe1a2d8/charset_normalizer-3.4.2-cp313-cp313-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:6c9379d65defcab82d07b2a9dfbfc2e95bc8fe0ebb1b176a3190230a3ef0e07c", size = 148243 }, + { url = "https://files.pythonhosted.org/packages/c0/0f/9abe9bd191629c33e69e47c6ef45ef99773320e9ad8e9cb08b8ab4a8d4cb/charset_normalizer-3.4.2-cp313-cp313-manylinux_2_5_i686.manylinux1_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:e635b87f01ebc977342e2697d05b56632f5f879a4f15955dfe8cef2448b51691", size = 150442 }, + { url = "https://files.pythonhosted.org/packages/67/7c/a123bbcedca91d5916c056407f89a7f5e8fdfce12ba825d7d6b9954a1a3c/charset_normalizer-3.4.2-cp313-cp313-musllinux_1_2_aarch64.whl", hash = "sha256:1c95a1e2902a8b722868587c0e1184ad5c55631de5afc0eb96bc4b0d738092c0", size = 145147 }, + { url = "https://files.pythonhosted.org/packages/ec/fe/1ac556fa4899d967b83e9893788e86b6af4d83e4726511eaaad035e36595/charset_normalizer-3.4.2-cp313-cp313-musllinux_1_2_i686.whl", hash = "sha256:ef8de666d6179b009dce7bcb2ad4c4a779f113f12caf8dc77f0162c29d20490b", size = 153057 }, + { url = "https://files.pythonhosted.org/packages/2b/ff/acfc0b0a70b19e3e54febdd5301a98b72fa07635e56f24f60502e954c461/charset_normalizer-3.4.2-cp313-cp313-musllinux_1_2_ppc64le.whl", hash = "sha256:32fc0341d72e0f73f80acb0a2c94216bd704f4f0bce10aedea38f30502b271ff", size = 156454 }, + { url = "https://files.pythonhosted.org/packages/92/08/95b458ce9c740d0645feb0e96cea1f5ec946ea9c580a94adfe0b617f3573/charset_normalizer-3.4.2-cp313-cp313-musllinux_1_2_s390x.whl", hash = "sha256:289200a18fa698949d2b39c671c2cc7a24d44096784e76614899a7ccf2574b7b", size = 154174 }, + { url = "https://files.pythonhosted.org/packages/78/be/8392efc43487ac051eee6c36d5fbd63032d78f7728cb37aebcc98191f1ff/charset_normalizer-3.4.2-cp313-cp313-musllinux_1_2_x86_64.whl", hash = "sha256:4a476b06fbcf359ad25d34a057b7219281286ae2477cc5ff5e3f70a246971148", size = 149166 }, + { url = "https://files.pythonhosted.org/packages/44/96/392abd49b094d30b91d9fbda6a69519e95802250b777841cf3bda8fe136c/charset_normalizer-3.4.2-cp313-cp313-win32.whl", hash = "sha256:aaeeb6a479c7667fbe1099af9617c83aaca22182d6cf8c53966491a0f1b7ffb7", size = 98064 }, + { url = "https://files.pythonhosted.org/packages/e9/b0/0200da600134e001d91851ddc797809e2fe0ea72de90e09bec5a2fbdaccb/charset_normalizer-3.4.2-cp313-cp313-win_amd64.whl", hash = "sha256:aa6af9e7d59f9c12b33ae4e9450619cf2488e2bbe9b44030905877f0b2324980", size = 105641 }, + { url = "https://files.pythonhosted.org/packages/20/94/c5790835a017658cbfabd07f3bfb549140c3ac458cfc196323996b10095a/charset_normalizer-3.4.2-py3-none-any.whl", hash = "sha256:7f56930ab0abd1c45cd15be65cc741c28b1c9a34876ce8c17a2fa107810c0af0", size = 52626 }, +] + +[[package]] +name = "chex" +version = "0.1.89" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "absl-py" }, + { name = "jax" }, + { name = "jaxlib" }, + { name = "numpy", version = "2.2.6", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version < '3.11'" }, + { name = "numpy", version = "2.3.1", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version >= '3.11'" }, + { name = "setuptools", marker = "python_full_version >= '3.12'" }, + { name = "toolz" }, + { name = "typing-extensions" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/ca/ac/504a8019f7ef372fc6cc3999ec9e3d0fbb38e6992f55d845d5b928010c11/chex-0.1.89.tar.gz", hash = "sha256:78f856e6a0a8459edfcbb402c2c044d2b8102eac4b633838cbdfdcdb09c6c8e0", size = 90676 } +wheels = [ + { url = "https://files.pythonhosted.org/packages/5e/6c/309972937d931069816dc8b28193a650485bc35cca92c04c8c15c4bd181e/chex-0.1.89-py3-none-any.whl", hash = "sha256:145241c27d8944adb634fb7d472a460e1c1b643f561507d4031ad5156ef82dfa", size = 99908 }, +] + +[[package]] +name = "click" +version = "8.2.1" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "colorama", marker = "sys_platform == 'win32'" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/60/6c/8ca2efa64cf75a977a0d7fac081354553ebe483345c734fb6b6515d96bbc/click-8.2.1.tar.gz", hash = "sha256:27c491cc05d968d271d5a1db13e3b5a184636d9d930f148c50b038f0d0646202", size = 286342 } +wheels = [ + { url = "https://files.pythonhosted.org/packages/85/32/10bb5764d90a8eee674e9dc6f4db6a0ab47c8c4d0d83c27f7c39ac415a4d/click-8.2.1-py3-none-any.whl", hash = "sha256:61a3265b914e850b85317d0b3109c7f8cd35a670f963866005d6ef1d5175a12b", size = 102215 }, +] + +[[package]] +name = "colorama" +version = "0.4.6" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/d8/53/6f443c9a4a8358a93a6792e2acffb9d9d5cb0a5cfd8802644b7b1c9a02e4/colorama-0.4.6.tar.gz", hash = "sha256:08695f5cb7ed6e0531a20572697297273c47b8cae5a63ffc6d6ed5c201be6e44", size = 27697 } +wheels = [ + { url = "https://files.pythonhosted.org/packages/d1/d6/3965ed04c63042e047cb6a3e6ed1a63a35087b6a609aa3a15ed8ac56c221/colorama-0.4.6-py2.py3-none-any.whl", hash = "sha256:4f1d9991f5acc0ca119f9d443620b77f9d6b33703e51011c16baf57afb285fc6", size = 25335 }, +] + +[[package]] +name = "distlib" +version = "0.3.9" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/0d/dd/1bec4c5ddb504ca60fc29472f3d27e8d4da1257a854e1d96742f15c1d02d/distlib-0.3.9.tar.gz", hash = "sha256:a60f20dea646b8a33f3e7772f74dc0b2d0772d2837ee1342a00645c81edf9403", size = 613923 } +wheels = [ + { url = "https://files.pythonhosted.org/packages/91/a1/cf2472db20f7ce4a6be1253a81cfdf85ad9c7885ffbed7047fb72c24cf87/distlib-0.3.9-py2.py3-none-any.whl", hash = "sha256:47f8c22fd27c27e25a65601af709b38e4f0a45ea4fc2e710f65755fa8caaaf87", size = 468973 }, +] + +[[package]] +name = "equinox" +version = "0.12.2" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "jax" }, + { name = "jaxtyping" }, + { name = "typing-extensions" }, + { name = "wadler-lindig" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/4c/1c/da174caa2902cee108a542cfb801bd4366a5e44541b625d5a0984c9238e0/equinox-0.12.2.tar.gz", hash = "sha256:648e4206bbc53b228922e8f18cd3cffe543ddda1172c0002f8954e484bab0023", size = 139007 } +wheels = [ + { url = "https://files.pythonhosted.org/packages/8e/a7/5961a7cad10df1e165a8b9c4ba0661aaec9497861e53682effa1787d97aa/equinox-0.12.2-py3-none-any.whl", hash = "sha256:0d9c09c077e7895a5334930ddb9ecd7d39840c3ad252cf8262aa8ddc6bb8ae97", size = 177247 }, +] + +[[package]] +name = "etils" +version = "1.12.2" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/e4/12/1cc11e88a0201280ff389bc4076df7c3432e39d9f22cba8b71aa263f67b8/etils-1.12.2.tar.gz", hash = "sha256:c6b9e1f0ce66d1bbf54f99201b08a60ba396d3446d9eb18d4bc39b26a2e1a5ee", size = 104711 } +wheels = [ + { url = "https://files.pythonhosted.org/packages/dd/71/40ee142e564b8a34a7ae9546e99e665e0001011a3254d5bbbe113d72ccba/etils-1.12.2-py3-none-any.whl", hash = "sha256:4600bec9de6cf5cb043a171e1856e38b5f273719cf3ecef90199f7091a6b3912", size = 167613 }, +] + +[package.optional-dependencies] +epath = [ + { name = "fsspec" }, + { name = "importlib-resources" }, + { name = "typing-extensions" }, + { name = "zipp" }, +] +epy = [ + { name = "typing-extensions" }, +] + +[[package]] +name = "exceptiongroup" +version = "1.3.0" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "typing-extensions", marker = "python_full_version < '3.11'" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/0b/9f/a65090624ecf468cdca03533906e7c69ed7588582240cfe7cc9e770b50eb/exceptiongroup-1.3.0.tar.gz", hash = "sha256:b241f5885f560bc56a59ee63ca4c6a8bfa46ae4ad651af316d4e81817bb9fd88", size = 29749 } +wheels = [ + { url = "https://files.pythonhosted.org/packages/36/f4/c6e662dade71f56cd2f3735141b265c3c79293c109549c1e6933b0651ffc/exceptiongroup-1.3.0-py3-none-any.whl", hash = "sha256:4d111e6e0c13d0644cad6ddaa7ed0261a0b36971f6d23e7ec9b4b9097da78a10", size = 16674 }, +] + +[[package]] +name = "filelock" +version = "3.18.0" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/0a/10/c23352565a6544bdc5353e0b15fc1c563352101f30e24bf500207a54df9a/filelock-3.18.0.tar.gz", hash = "sha256:adbc88eabb99d2fec8c9c1b229b171f18afa655400173ddc653d5d01501fb9f2", size = 18075 } +wheels = [ + { url = "https://files.pythonhosted.org/packages/4d/36/2a115987e2d8c300a974597416d9de88f2444426de9571f4b59b2cca3acc/filelock-3.18.0-py3-none-any.whl", hash = "sha256:c401f4f8377c4464e6db25fff06205fd89bdd83b65eb0488ed1b160f780e21de", size = 16215 }, +] + +[[package]] +name = "flax" +version = "0.10.7" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "jax" }, + { name = "msgpack" }, + { name = "numpy", version = "2.3.1", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version >= '3.11'" }, + { name = "optax" }, + { name = "orbax-checkpoint" }, + { name = "pyyaml" }, + { name = "rich" }, + { name = "tensorstore" }, + { name = "treescope" }, + { name = "typing-extensions" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/e6/76/4ea55a60a47e98fcff591238ee26ed4624cb4fdc4893aa3ebf78d0d021f4/flax-0.10.7.tar.gz", hash = "sha256:2930d6671e23076f6db3b96afacf45c5060898f5c189ecab6dda7e05d26c2085", size = 5136099 } +wheels = [ + { url = "https://files.pythonhosted.org/packages/11/f6/560d338687d40182c8429cf35c64cc022e0d57ba3e52191c4a78ed239b4e/flax-0.10.7-py3-none-any.whl", hash = "sha256:4033223a9a9969ba0b252e085e9714d0a1e9124ac300aaf48e92c40769c420f6", size = 456944 }, +] + +[[package]] +name = "fsspec" +version = "2025.5.1" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/00/f7/27f15d41f0ed38e8fcc488584b57e902b331da7f7c6dcda53721b15838fc/fsspec-2025.5.1.tar.gz", hash = "sha256:2e55e47a540b91843b755e83ded97c6e897fa0942b11490113f09e9c443c2475", size = 303033 } +wheels = [ + { url = "https://files.pythonhosted.org/packages/bb/61/78c7b3851add1481b048b5fdc29067397a1784e2910592bc81bb3f608635/fsspec-2025.5.1-py3-none-any.whl", hash = "sha256:24d3a2e663d5fc735ab256263c4075f374a174c3410c0b25e5bd1970bceaa462", size = 199052 }, +] + +[[package]] +name = "ghp-import" +version = "2.1.0" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "python-dateutil" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/d9/29/d40217cbe2f6b1359e00c6c307bb3fc876ba74068cbab3dde77f03ca0dc4/ghp-import-2.1.0.tar.gz", hash = "sha256:9c535c4c61193c2df8871222567d7fd7e5014d835f97dc7b7439069e2413d343", size = 10943 } +wheels = [ + { url = "https://files.pythonhosted.org/packages/f7/ec/67fbef5d497f86283db54c22eec6f6140243aae73265799baaaa19cd17fb/ghp_import-2.1.0-py3-none-any.whl", hash = "sha256:8337dd7b50877f163d4c0289bc1f1c7f127550241988d568c1db512c4324a619", size = 11034 }, +] + +[[package]] +name = "griffe" +version = "1.7.3" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "colorama" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/a9/3e/5aa9a61f7c3c47b0b52a1d930302992229d191bf4bc76447b324b731510a/griffe-1.7.3.tar.gz", hash = "sha256:52ee893c6a3a968b639ace8015bec9d36594961e156e23315c8e8e51401fa50b", size = 395137 } +wheels = [ + { url = "https://files.pythonhosted.org/packages/58/c6/5c20af38c2a57c15d87f7f38bee77d63c1d2a3689f74fefaf35915dd12b2/griffe-1.7.3-py3-none-any.whl", hash = "sha256:c6b3ee30c2f0f17f30bcdef5068d6ab7a2a4f1b8bf1a3e74b56fffd21e1c5f75", size = 129303 }, +] + +[[package]] +name = "haliax" +source = { editable = "." } +dependencies = [ + { name = "aqtp" }, + { name = "equinox" }, + { name = "jaxtyping" }, + { name = "jmp" }, + { name = "safetensors" }, +] + +[package.dev-dependencies] +dev = [ + { name = "chex" }, + { name = "mkdocs" }, + { name = "mkdocs-include-markdown-plugin" }, + { name = "mkdocs-literate-nav" }, + { name = "mkdocs-macros-plugin" }, + { name = "mkdocs-material" }, + { name = "mkdocstrings" }, + { name = "mkdocstrings-python" }, + { name = "mypy" }, + { name = "pre-commit" }, + { name = "pygments" }, + { name = "pymdown-extensions" }, + { name = "pytest" }, +] + +[package.metadata] +requires-dist = [ + { name = "aqtp", specifier = ">=0.8.2" }, + { name = "equinox", specifier = ">=0.10.6" }, + { name = "jaxtyping", specifier = ">=0.2.20" }, + { name = "jmp", specifier = ">=0.0.4" }, + { name = "safetensors", specifier = ">=0.4.3" }, +] + +[package.metadata.requires-dev] +dev = [ + { name = "chex", specifier = ">=0.1.86" }, + { name = "mkdocs", specifier = ">=1.4.3" }, + { name = "mkdocs-include-markdown-plugin" }, + { name = "mkdocs-literate-nav", specifier = ">=0.6.0" }, + { name = "mkdocs-macros-plugin", specifier = ">=0.7.0" }, + { name = "mkdocs-material", specifier = ">=7.3.3" }, + { name = "mkdocstrings", specifier = ">=0.22.0" }, + { name = "mkdocstrings-python", specifier = ">=1.1.2" }, + { name = "mypy", specifier = ">=0.910" }, + { name = "pre-commit" }, + { name = "pygments" }, + { name = "pymdown-extensions" }, + { name = "pytest", specifier = ">=7.4.0" }, +] + +[[package]] +name = "hjson" +version = "3.1.0" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/82/e5/0b56d723a76ca67abadbf7fb71609fb0ea7e6926e94fcca6c65a85b36a0e/hjson-3.1.0.tar.gz", hash = "sha256:55af475a27cf83a7969c808399d7bccdec8fb836a07ddbd574587593b9cdcf75", size = 40541 } +wheels = [ + { url = "https://files.pythonhosted.org/packages/1f/7f/13cd798d180af4bf4c0ceddeefba2b864a63c71645abc0308b768d67bb81/hjson-3.1.0-py3-none-any.whl", hash = "sha256:65713cdcf13214fb554eb8b4ef803419733f4f5e551047c9b711098ab7186b89", size = 54018 }, +] + +[[package]] +name = "humanize" +version = "4.12.3" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/22/d1/bbc4d251187a43f69844f7fd8941426549bbe4723e8ff0a7441796b0789f/humanize-4.12.3.tar.gz", hash = "sha256:8430be3a615106fdfceb0b2c1b41c4c98c6b0fc5cc59663a5539b111dd325fb0", size = 80514 } +wheels = [ + { url = "https://files.pythonhosted.org/packages/a0/1e/62a2ec3104394a2975a2629eec89276ede9dbe717092f6966fcf963e1bf0/humanize-4.12.3-py3-none-any.whl", hash = "sha256:2cbf6370af06568fa6d2da77c86edb7886f3160ecd19ee1ffef07979efc597f6", size = 128487 }, +] + +[[package]] +name = "identify" +version = "2.6.12" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/a2/88/d193a27416618628a5eea64e3223acd800b40749a96ffb322a9b55a49ed1/identify-2.6.12.tar.gz", hash = "sha256:d8de45749f1efb108badef65ee8386f0f7bb19a7f26185f74de6367bffbaf0e6", size = 99254 } +wheels = [ + { url = "https://files.pythonhosted.org/packages/7a/cd/18f8da995b658420625f7ef13f037be53ae04ec5ad33f9b718240dcfd48c/identify-2.6.12-py2.py3-none-any.whl", hash = "sha256:ad9672d5a72e0d2ff7c5c8809b62dfa60458626352fb0eb7b55e69bdc45334a2", size = 99145 }, +] + +[[package]] +name = "idna" +version = "3.10" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/f1/70/7703c29685631f5a7590aa73f1f1d3fa9a380e654b86af429e0934a32f7d/idna-3.10.tar.gz", hash = "sha256:12f65c9b470abda6dc35cf8e63cc574b1c52b11df2c86030af0ac09b01b13ea9", size = 190490 } +wheels = [ + { url = "https://files.pythonhosted.org/packages/76/c6/c88e154df9c4e1a2a66ccf0005a88dfb2650c1dffb6f5ce603dfbd452ce3/idna-3.10-py3-none-any.whl", hash = "sha256:946d195a0d259cbba61165e88e65941f16e9b36ea6ddb97f00452bae8b1287d3", size = 70442 }, +] + +[[package]] +name = "importlib-resources" +version = "6.5.2" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/cf/8c/f834fbf984f691b4f7ff60f50b514cc3de5cc08abfc3295564dd89c5e2e7/importlib_resources-6.5.2.tar.gz", hash = "sha256:185f87adef5bcc288449d98fb4fba07cea78bc036455dd44c5fc4a2fe78fed2c", size = 44693 } +wheels = [ + { url = "https://files.pythonhosted.org/packages/a4/ed/1f1afb2e9e7f38a545d628f864d562a5ae64fe6f7a10e28ffb9b185b4e89/importlib_resources-6.5.2-py3-none-any.whl", hash = "sha256:789cfdc3ed28c78b67a06acb8126751ced69a3d5f79c095a98298cd8a760ccec", size = 37461 }, +] + +[[package]] +name = "iniconfig" +version = "2.1.0" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/f2/97/ebf4da567aa6827c909642694d71c9fcf53e5b504f2d96afea02718862f3/iniconfig-2.1.0.tar.gz", hash = "sha256:3abbd2e30b36733fee78f9c7f7308f2d0050e88f0087fd25c2645f63c773e1c7", size = 4793 } +wheels = [ + { url = "https://files.pythonhosted.org/packages/2c/e1/e6716421ea10d38022b952c159d5161ca1193197fb744506875fbb87ea7b/iniconfig-2.1.0-py3-none-any.whl", hash = "sha256:9deba5723312380e77435581c6bf4935c94cbfab9b1ed33ef8d238ea168eb760", size = 6050 }, +] + +[[package]] +name = "jax" +version = "0.6.2" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "jaxlib" }, + { name = "ml-dtypes" }, + { name = "numpy", version = "2.2.6", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version < '3.11'" }, + { name = "numpy", version = "2.3.1", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version >= '3.11'" }, + { name = "opt-einsum" }, + { name = "scipy", version = "1.15.3", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version < '3.11'" }, + { name = "scipy", version = "1.16.0", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version >= '3.11'" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/cf/1e/267f59c8fb7f143c3f778c76cb7ef1389db3fd7e4540f04b9f42ca90764d/jax-0.6.2.tar.gz", hash = "sha256:a437d29038cbc8300334119692744704ca7941490867b9665406b7f90665cd96", size = 2334091 } +wheels = [ + { url = "https://files.pythonhosted.org/packages/31/a8/97ef0cbb7a17143ace2643d600a7b80d6705b2266fc31078229e406bdef2/jax-0.6.2-py3-none-any.whl", hash = "sha256:bb24a82dc60ccf704dcaf6dbd07d04957f68a6c686db19630dd75260d1fb788c", size = 2722396 }, +] + +[[package]] +name = "jaxlib" +version = "0.6.2" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "ml-dtypes" }, + { name = "numpy", version = "2.2.6", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version < '3.11'" }, + { name = "numpy", version = "2.3.1", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version >= '3.11'" }, + { name = "scipy", version = "1.15.3", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version < '3.11'" }, + { name = "scipy", version = "1.16.0", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version >= '3.11'" }, +] +wheels = [ + { url = "https://files.pythonhosted.org/packages/15/c5/41598634c99cbebba46e6777286fb76abc449d33d50aeae5d36128ca8803/jaxlib-0.6.2-cp310-cp310-macosx_11_0_arm64.whl", hash = "sha256:da4601b2b5dc8c23d6afb293eacfb9aec4e1d1871cb2f29c5a151d103e73b0f8", size = 54298019 }, + { url = "https://files.pythonhosted.org/packages/81/af/db07d746cd5867d5967528e7811da53374e94f64e80a890d6a5a4b95b130/jaxlib-0.6.2-cp310-cp310-manylinux2014_aarch64.whl", hash = "sha256:4205d098ce8efb5f7fe2fe5098bae6036094dc8d8829f5e0e0d7a9b155326336", size = 79440052 }, + { url = "https://files.pythonhosted.org/packages/7e/d8/b7ae9e819c62c1854dbc2c70540a5c041173fbc8bec5e78ab7fd615a4aee/jaxlib-0.6.2-cp310-cp310-manylinux2014_x86_64.whl", hash = "sha256:c087a0eb6fb7f6f8f54d56f4730328dfde5040dd3b5ddfa810e7c28ea7102b42", size = 89917034 }, + { url = "https://files.pythonhosted.org/packages/fd/e5/87e91bc70569ac5c3e3449eefcaf47986e892f10cfe1d5e5720dceae3068/jaxlib-0.6.2-cp310-cp310-win_amd64.whl", hash = "sha256:153eaa51f778b60851720729d4f461a91edd9ba3932f6f3bc598d4413870038b", size = 57896337 }, + { url = "https://files.pythonhosted.org/packages/a4/ee/6899b0aed36a4acc51319465ddd83c7c300a062a9e236cceee00984ffe0b/jaxlib-0.6.2-cp311-cp311-macosx_11_0_arm64.whl", hash = "sha256:a208ff61c58128d306bb4e5ad0858bd2b0960f2c1c10ad42c548f74a60c0020e", size = 54300346 }, + { url = "https://files.pythonhosted.org/packages/e6/03/34bb6b346609079a71942cfbf507892e3c877a06a430a0df8429c455cebc/jaxlib-0.6.2-cp311-cp311-manylinux2014_aarch64.whl", hash = "sha256:11eae7e05bc5a79875da36324afb9eddd4baeaef2a0386caf6d4f3720b9aef28", size = 79438425 }, + { url = "https://files.pythonhosted.org/packages/80/02/49b05cbab519ffd3cb79586336451fbbf8b6523f67128a794acc9f179000/jaxlib-0.6.2-cp311-cp311-manylinux2014_x86_64.whl", hash = "sha256:335d7e3515ce78b52a410136f46aa4a7ea14d0e7d640f34e1e137409554ad0ac", size = 89920354 }, + { url = "https://files.pythonhosted.org/packages/a7/7a/93b28d9452b46c15fc28dd65405672fc8a158b35d46beabaa0fe9631afb0/jaxlib-0.6.2-cp311-cp311-win_amd64.whl", hash = "sha256:c6815509997d6b05e5c9daa7994b9ad473ce3e8c8a17bdbbcacc3c744f76f7a0", size = 57895707 }, + { url = "https://files.pythonhosted.org/packages/ac/db/05e702d2534e87abf606b1067b46a273b120e6adc7d459696e3ce7399317/jaxlib-0.6.2-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:34d8a684a8be949dd87dd4acc97101b4106a0dc9ad151ec891da072319a57b99", size = 54301644 }, + { url = "https://files.pythonhosted.org/packages/0d/8a/b0a96887b97a25d45ae2c30e4acecd2f95acd074c18ec737dda8c5cc7016/jaxlib-0.6.2-cp312-cp312-manylinux2014_aarch64.whl", hash = "sha256:87ec2dc9c3ed9ab936eec8535160c5fbd2c849948559f1c5daa75f63fabe5942", size = 79439161 }, + { url = "https://files.pythonhosted.org/packages/ba/e8/71c2555431edb5dd115cf86a7b599aa7e1be26728d89ae59aa11251d299c/jaxlib-0.6.2-cp312-cp312-manylinux2014_x86_64.whl", hash = "sha256:f1dd09b481a93c1d4c750013f467f74194493ba7bd29fcd4d1cec16e3a214f65", size = 89942952 }, + { url = "https://files.pythonhosted.org/packages/de/3a/06849113c844b86d20174df54735c84202ccf82cbd36d805f478c834418b/jaxlib-0.6.2-cp312-cp312-win_amd64.whl", hash = "sha256:921dbd4db214eba19a29ba9f2450d880e08b2b2c7b968f28cc89da3e62366af4", size = 57919603 }, + { url = "https://files.pythonhosted.org/packages/af/38/bed4279c2a3407820ed8bcd72dbad43c330ada35f88fafe9952b35abf785/jaxlib-0.6.2-cp313-cp313-macosx_11_0_arm64.whl", hash = "sha256:bff67b188133ce1f0111c7b163ac321fd646b59ed221ea489063e2e0f85cb967", size = 54300638 }, + { url = "https://files.pythonhosted.org/packages/52/dc/9e35a1dc089ddf3d6be53ef2e6ba4718c5b6c0f90bccc535a20edac0c895/jaxlib-0.6.2-cp313-cp313-manylinux2014_aarch64.whl", hash = "sha256:70498837caf538bd458ff6858c8bfd404db82015aba8f663670197fa9900ff02", size = 79439983 }, + { url = "https://files.pythonhosted.org/packages/34/16/e93f0184b80a4e1ad38c6998aa3a2f7569c0b0152cbae39f7572393eda04/jaxlib-0.6.2-cp313-cp313-manylinux2014_x86_64.whl", hash = "sha256:f94163f14c8fd3ba93ae14b631abacf14cb031bba0b59138869984b4d10375f8", size = 89941720 }, + { url = "https://files.pythonhosted.org/packages/06/b9/ea50792ee0333dba764e06c305fe098bce1cb938dcb66fbe2fc47ef5dd02/jaxlib-0.6.2-cp313-cp313-win_amd64.whl", hash = "sha256:b977604cd36c74b174d25ed685017379468138eb747d865f75e466cb273c801d", size = 57919073 }, + { url = "https://files.pythonhosted.org/packages/09/ce/9596391c104a0547fcaf6a8c72078bbae79dbc8e7f0843dc8318f6606328/jaxlib-0.6.2-cp313-cp313t-manylinux2014_aarch64.whl", hash = "sha256:39cf9555f85ae1ce2e2c1a59fc71f2eca4f9867a7cb934fef881ba56b11371d1", size = 79579638 }, + { url = "https://files.pythonhosted.org/packages/10/79/f6e80f7f4cacfc9f03e64ac57ecb856b140de7c2f939b25f8dcf1aff63f9/jaxlib-0.6.2-cp313-cp313t-manylinux2014_x86_64.whl", hash = "sha256:3abd536e44b05fb1657507e3ff1fc3691f99613bae3921ecab9e82f27255f784", size = 90066675 }, +] + +[[package]] +name = "jaxtyping" +version = "0.3.2" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "wadler-lindig" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/88/a8/416bd7ea110ec6b68e8868b0f99c985c735adcf7badc491d3c343937260a/jaxtyping-0.3.2.tar.gz", hash = "sha256:f30483fac4b42e915db8ad2414a85c3b63284aa7d3c100b96b59f755cf4a86ad", size = 44989 } +wheels = [ + { url = "https://files.pythonhosted.org/packages/c9/b9/281e10e2d967ea5e481683eaec99f55ac5a61085ee60551c36942ef32bef/jaxtyping-0.3.2-py3-none-any.whl", hash = "sha256:6a020fd276226ddb5ac4f5725323843dd65e3c7e85c64fd62431e5f738c74e04", size = 55409 }, +] + +[[package]] +name = "jinja2" +version = "3.1.6" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "markupsafe" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/df/bf/f7da0350254c0ed7c72f3e33cef02e048281fec7ecec5f032d4aac52226b/jinja2-3.1.6.tar.gz", hash = "sha256:0137fb05990d35f1275a587e9aee6d56da821fc83491a0fb838183be43f66d6d", size = 245115 } +wheels = [ + { url = "https://files.pythonhosted.org/packages/62/a1/3d680cbfd5f4b8f15abc1d571870c5fc3e594bb582bc3b64ea099db13e56/jinja2-3.1.6-py3-none-any.whl", hash = "sha256:85ece4451f492d0c13c5dd7c13a64681a86afae63a5f347908daf103ce6d2f67", size = 134899 }, +] + +[[package]] +name = "jmp" +version = "0.0.4" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "numpy", version = "2.2.6", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version < '3.11'" }, + { name = "numpy", version = "2.3.1", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version >= '3.11'" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/ab/b0/e90fbbffef4b345329c878a69f0336d3edc5a1f9fcba193931aca2132d62/jmp-0.0.4.tar.gz", hash = "sha256:5dfeb0fd7c7a9f72a70fff0aab9d0cbfae32a809c02f4037ff3485ceb33e1730", size = 18582 } +wheels = [ + { url = "https://files.pythonhosted.org/packages/27/e5/cce82de2831e5aff9332d8d624bb57188f1b2af6ccf6979caf898a8a4348/jmp-0.0.4-py3-none-any.whl", hash = "sha256:6aa7adbddf2bd574b28c7faf6e81a735eb11f53386447896909c6968dc36807d", size = 18274 }, +] + +[[package]] +name = "markdown" +version = "3.8.2" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/d7/c2/4ab49206c17f75cb08d6311171f2d65798988db4360c4d1485bd0eedd67c/markdown-3.8.2.tar.gz", hash = "sha256:247b9a70dd12e27f67431ce62523e675b866d254f900c4fe75ce3dda62237c45", size = 362071 } +wheels = [ + { url = "https://files.pythonhosted.org/packages/96/2b/34cc11786bc00d0f04d0f5fdc3a2b1ae0b6239eef72d3d345805f9ad92a1/markdown-3.8.2-py3-none-any.whl", hash = "sha256:5c83764dbd4e00bdd94d85a19b8d55ccca20fe35b2e678a1422b380324dd5f24", size = 106827 }, +] + +[[package]] +name = "markdown-it-py" +version = "3.0.0" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "mdurl" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/38/71/3b932df36c1a044d397a1f92d1cf91ee0a503d91e470cbd670aa66b07ed0/markdown-it-py-3.0.0.tar.gz", hash = "sha256:e3f60a94fa066dc52ec76661e37c851cb232d92f9886b15cb560aaada2df8feb", size = 74596 } +wheels = [ + { url = "https://files.pythonhosted.org/packages/42/d7/1ec15b46af6af88f19b8e5ffea08fa375d433c998b8a7639e76935c14f1f/markdown_it_py-3.0.0-py3-none-any.whl", hash = "sha256:355216845c60bd96232cd8d8c40e8f9765cc86f46880e43a8fd22dc1a1a8cab1", size = 87528 }, +] + +[[package]] +name = "markupsafe" +version = "3.0.2" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/b2/97/5d42485e71dfc078108a86d6de8fa46db44a1a9295e89c5d6d4a06e23a62/markupsafe-3.0.2.tar.gz", hash = "sha256:ee55d3edf80167e48ea11a923c7386f4669df67d7994554387f84e7d8b0a2bf0", size = 20537 } +wheels = [ + { url = "https://files.pythonhosted.org/packages/04/90/d08277ce111dd22f77149fd1a5d4653eeb3b3eaacbdfcbae5afb2600eebd/MarkupSafe-3.0.2-cp310-cp310-macosx_10_9_universal2.whl", hash = "sha256:7e94c425039cde14257288fd61dcfb01963e658efbc0ff54f5306b06054700f8", size = 14357 }, + { url = "https://files.pythonhosted.org/packages/04/e1/6e2194baeae0bca1fae6629dc0cbbb968d4d941469cbab11a3872edff374/MarkupSafe-3.0.2-cp310-cp310-macosx_11_0_arm64.whl", hash = "sha256:9e2d922824181480953426608b81967de705c3cef4d1af983af849d7bd619158", size = 12393 }, + { url = "https://files.pythonhosted.org/packages/1d/69/35fa85a8ece0a437493dc61ce0bb6d459dcba482c34197e3efc829aa357f/MarkupSafe-3.0.2-cp310-cp310-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:38a9ef736c01fccdd6600705b09dc574584b89bea478200c5fbf112a6b0d5579", size = 21732 }, + { url = "https://files.pythonhosted.org/packages/22/35/137da042dfb4720b638d2937c38a9c2df83fe32d20e8c8f3185dbfef05f7/MarkupSafe-3.0.2-cp310-cp310-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:bbcb445fa71794da8f178f0f6d66789a28d7319071af7a496d4d507ed566270d", size = 20866 }, + { url = "https://files.pythonhosted.org/packages/29/28/6d029a903727a1b62edb51863232152fd335d602def598dade38996887f0/MarkupSafe-3.0.2-cp310-cp310-manylinux_2_5_i686.manylinux1_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:57cb5a3cf367aeb1d316576250f65edec5bb3be939e9247ae594b4bcbc317dfb", size = 20964 }, + { url = "https://files.pythonhosted.org/packages/cc/cd/07438f95f83e8bc028279909d9c9bd39e24149b0d60053a97b2bc4f8aa51/MarkupSafe-3.0.2-cp310-cp310-musllinux_1_2_aarch64.whl", hash = "sha256:3809ede931876f5b2ec92eef964286840ed3540dadf803dd570c3b7e13141a3b", size = 21977 }, + { url = "https://files.pythonhosted.org/packages/29/01/84b57395b4cc062f9c4c55ce0df7d3108ca32397299d9df00fedd9117d3d/MarkupSafe-3.0.2-cp310-cp310-musllinux_1_2_i686.whl", hash = "sha256:e07c3764494e3776c602c1e78e298937c3315ccc9043ead7e685b7f2b8d47b3c", size = 21366 }, + { url = "https://files.pythonhosted.org/packages/bd/6e/61ebf08d8940553afff20d1fb1ba7294b6f8d279df9fd0c0db911b4bbcfd/MarkupSafe-3.0.2-cp310-cp310-musllinux_1_2_x86_64.whl", hash = "sha256:b424c77b206d63d500bcb69fa55ed8d0e6a3774056bdc4839fc9298a7edca171", size = 21091 }, + { url = "https://files.pythonhosted.org/packages/11/23/ffbf53694e8c94ebd1e7e491de185124277964344733c45481f32ede2499/MarkupSafe-3.0.2-cp310-cp310-win32.whl", hash = "sha256:fcabf5ff6eea076f859677f5f0b6b5c1a51e70a376b0579e0eadef8db48c6b50", size = 15065 }, + { url = "https://files.pythonhosted.org/packages/44/06/e7175d06dd6e9172d4a69a72592cb3f7a996a9c396eee29082826449bbc3/MarkupSafe-3.0.2-cp310-cp310-win_amd64.whl", hash = "sha256:6af100e168aa82a50e186c82875a5893c5597a0c1ccdb0d8b40240b1f28b969a", size = 15514 }, + { url = "https://files.pythonhosted.org/packages/6b/28/bbf83e3f76936960b850435576dd5e67034e200469571be53f69174a2dfd/MarkupSafe-3.0.2-cp311-cp311-macosx_10_9_universal2.whl", hash = "sha256:9025b4018f3a1314059769c7bf15441064b2207cb3f065e6ea1e7359cb46db9d", size = 14353 }, + { url = "https://files.pythonhosted.org/packages/6c/30/316d194b093cde57d448a4c3209f22e3046c5bb2fb0820b118292b334be7/MarkupSafe-3.0.2-cp311-cp311-macosx_11_0_arm64.whl", hash = "sha256:93335ca3812df2f366e80509ae119189886b0f3c2b81325d39efdb84a1e2ae93", size = 12392 }, + { url = "https://files.pythonhosted.org/packages/f2/96/9cdafba8445d3a53cae530aaf83c38ec64c4d5427d975c974084af5bc5d2/MarkupSafe-3.0.2-cp311-cp311-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:2cb8438c3cbb25e220c2ab33bb226559e7afb3baec11c4f218ffa7308603c832", size = 23984 }, + { url = "https://files.pythonhosted.org/packages/f1/a4/aefb044a2cd8d7334c8a47d3fb2c9f328ac48cb349468cc31c20b539305f/MarkupSafe-3.0.2-cp311-cp311-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:a123e330ef0853c6e822384873bef7507557d8e4a082961e1defa947aa59ba84", size = 23120 }, + { url = "https://files.pythonhosted.org/packages/8d/21/5e4851379f88f3fad1de30361db501300d4f07bcad047d3cb0449fc51f8c/MarkupSafe-3.0.2-cp311-cp311-manylinux_2_5_i686.manylinux1_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:1e084f686b92e5b83186b07e8a17fc09e38fff551f3602b249881fec658d3eca", size = 23032 }, + { url = "https://files.pythonhosted.org/packages/00/7b/e92c64e079b2d0d7ddf69899c98842f3f9a60a1ae72657c89ce2655c999d/MarkupSafe-3.0.2-cp311-cp311-musllinux_1_2_aarch64.whl", hash = "sha256:d8213e09c917a951de9d09ecee036d5c7d36cb6cb7dbaece4c71a60d79fb9798", size = 24057 }, + { url = "https://files.pythonhosted.org/packages/f9/ac/46f960ca323037caa0a10662ef97d0a4728e890334fc156b9f9e52bcc4ca/MarkupSafe-3.0.2-cp311-cp311-musllinux_1_2_i686.whl", hash = "sha256:5b02fb34468b6aaa40dfc198d813a641e3a63b98c2b05a16b9f80b7ec314185e", size = 23359 }, + { url = "https://files.pythonhosted.org/packages/69/84/83439e16197337b8b14b6a5b9c2105fff81d42c2a7c5b58ac7b62ee2c3b1/MarkupSafe-3.0.2-cp311-cp311-musllinux_1_2_x86_64.whl", hash = "sha256:0bff5e0ae4ef2e1ae4fdf2dfd5b76c75e5c2fa4132d05fc1b0dabcd20c7e28c4", size = 23306 }, + { url = "https://files.pythonhosted.org/packages/9a/34/a15aa69f01e2181ed8d2b685c0d2f6655d5cca2c4db0ddea775e631918cd/MarkupSafe-3.0.2-cp311-cp311-win32.whl", hash = "sha256:6c89876f41da747c8d3677a2b540fb32ef5715f97b66eeb0c6b66f5e3ef6f59d", size = 15094 }, + { url = "https://files.pythonhosted.org/packages/da/b8/3a3bd761922d416f3dc5d00bfbed11f66b1ab89a0c2b6e887240a30b0f6b/MarkupSafe-3.0.2-cp311-cp311-win_amd64.whl", hash = "sha256:70a87b411535ccad5ef2f1df5136506a10775d267e197e4cf531ced10537bd6b", size = 15521 }, + { url = "https://files.pythonhosted.org/packages/22/09/d1f21434c97fc42f09d290cbb6350d44eb12f09cc62c9476effdb33a18aa/MarkupSafe-3.0.2-cp312-cp312-macosx_10_13_universal2.whl", hash = "sha256:9778bd8ab0a994ebf6f84c2b949e65736d5575320a17ae8984a77fab08db94cf", size = 14274 }, + { url = "https://files.pythonhosted.org/packages/6b/b0/18f76bba336fa5aecf79d45dcd6c806c280ec44538b3c13671d49099fdd0/MarkupSafe-3.0.2-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:846ade7b71e3536c4e56b386c2a47adf5741d2d8b94ec9dc3e92e5e1ee1e2225", size = 12348 }, + { url = "https://files.pythonhosted.org/packages/e0/25/dd5c0f6ac1311e9b40f4af06c78efde0f3b5cbf02502f8ef9501294c425b/MarkupSafe-3.0.2-cp312-cp312-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:1c99d261bd2d5f6b59325c92c73df481e05e57f19837bdca8413b9eac4bd8028", size = 24149 }, + { url = "https://files.pythonhosted.org/packages/f3/f0/89e7aadfb3749d0f52234a0c8c7867877876e0a20b60e2188e9850794c17/MarkupSafe-3.0.2-cp312-cp312-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:e17c96c14e19278594aa4841ec148115f9c7615a47382ecb6b82bd8fea3ab0c8", size = 23118 }, + { url = "https://files.pythonhosted.org/packages/d5/da/f2eeb64c723f5e3777bc081da884b414671982008c47dcc1873d81f625b6/MarkupSafe-3.0.2-cp312-cp312-manylinux_2_5_i686.manylinux1_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:88416bd1e65dcea10bc7569faacb2c20ce071dd1f87539ca2ab364bf6231393c", size = 22993 }, + { url = "https://files.pythonhosted.org/packages/da/0e/1f32af846df486dce7c227fe0f2398dc7e2e51d4a370508281f3c1c5cddc/MarkupSafe-3.0.2-cp312-cp312-musllinux_1_2_aarch64.whl", hash = "sha256:2181e67807fc2fa785d0592dc2d6206c019b9502410671cc905d132a92866557", size = 24178 }, + { url = "https://files.pythonhosted.org/packages/c4/f6/bb3ca0532de8086cbff5f06d137064c8410d10779c4c127e0e47d17c0b71/MarkupSafe-3.0.2-cp312-cp312-musllinux_1_2_i686.whl", hash = "sha256:52305740fe773d09cffb16f8ed0427942901f00adedac82ec8b67752f58a1b22", size = 23319 }, + { url = "https://files.pythonhosted.org/packages/a2/82/8be4c96ffee03c5b4a034e60a31294daf481e12c7c43ab8e34a1453ee48b/MarkupSafe-3.0.2-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:ad10d3ded218f1039f11a75f8091880239651b52e9bb592ca27de44eed242a48", size = 23352 }, + { url = "https://files.pythonhosted.org/packages/51/ae/97827349d3fcffee7e184bdf7f41cd6b88d9919c80f0263ba7acd1bbcb18/MarkupSafe-3.0.2-cp312-cp312-win32.whl", hash = "sha256:0f4ca02bea9a23221c0182836703cbf8930c5e9454bacce27e767509fa286a30", size = 15097 }, + { url = "https://files.pythonhosted.org/packages/c1/80/a61f99dc3a936413c3ee4e1eecac96c0da5ed07ad56fd975f1a9da5bc630/MarkupSafe-3.0.2-cp312-cp312-win_amd64.whl", hash = "sha256:8e06879fc22a25ca47312fbe7c8264eb0b662f6db27cb2d3bbbc74b1df4b9b87", size = 15601 }, + { url = "https://files.pythonhosted.org/packages/83/0e/67eb10a7ecc77a0c2bbe2b0235765b98d164d81600746914bebada795e97/MarkupSafe-3.0.2-cp313-cp313-macosx_10_13_universal2.whl", hash = "sha256:ba9527cdd4c926ed0760bc301f6728ef34d841f405abf9d4f959c478421e4efd", size = 14274 }, + { url = "https://files.pythonhosted.org/packages/2b/6d/9409f3684d3335375d04e5f05744dfe7e9f120062c9857df4ab490a1031a/MarkupSafe-3.0.2-cp313-cp313-macosx_11_0_arm64.whl", hash = "sha256:f8b3d067f2e40fe93e1ccdd6b2e1d16c43140e76f02fb1319a05cf2b79d99430", size = 12352 }, + { url = "https://files.pythonhosted.org/packages/d2/f5/6eadfcd3885ea85fe2a7c128315cc1bb7241e1987443d78c8fe712d03091/MarkupSafe-3.0.2-cp313-cp313-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:569511d3b58c8791ab4c2e1285575265991e6d8f8700c7be0e88f86cb0672094", size = 24122 }, + { url = "https://files.pythonhosted.org/packages/0c/91/96cf928db8236f1bfab6ce15ad070dfdd02ed88261c2afafd4b43575e9e9/MarkupSafe-3.0.2-cp313-cp313-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:15ab75ef81add55874e7ab7055e9c397312385bd9ced94920f2802310c930396", size = 23085 }, + { url = "https://files.pythonhosted.org/packages/c2/cf/c9d56af24d56ea04daae7ac0940232d31d5a8354f2b457c6d856b2057d69/MarkupSafe-3.0.2-cp313-cp313-manylinux_2_5_i686.manylinux1_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:f3818cb119498c0678015754eba762e0d61e5b52d34c8b13d770f0719f7b1d79", size = 22978 }, + { url = "https://files.pythonhosted.org/packages/2a/9f/8619835cd6a711d6272d62abb78c033bda638fdc54c4e7f4272cf1c0962b/MarkupSafe-3.0.2-cp313-cp313-musllinux_1_2_aarch64.whl", hash = "sha256:cdb82a876c47801bb54a690c5ae105a46b392ac6099881cdfb9f6e95e4014c6a", size = 24208 }, + { url = "https://files.pythonhosted.org/packages/f9/bf/176950a1792b2cd2102b8ffeb5133e1ed984547b75db47c25a67d3359f77/MarkupSafe-3.0.2-cp313-cp313-musllinux_1_2_i686.whl", hash = "sha256:cabc348d87e913db6ab4aa100f01b08f481097838bdddf7c7a84b7575b7309ca", size = 23357 }, + { url = "https://files.pythonhosted.org/packages/ce/4f/9a02c1d335caabe5c4efb90e1b6e8ee944aa245c1aaaab8e8a618987d816/MarkupSafe-3.0.2-cp313-cp313-musllinux_1_2_x86_64.whl", hash = "sha256:444dcda765c8a838eaae23112db52f1efaf750daddb2d9ca300bcae1039adc5c", size = 23344 }, + { url = "https://files.pythonhosted.org/packages/ee/55/c271b57db36f748f0e04a759ace9f8f759ccf22b4960c270c78a394f58be/MarkupSafe-3.0.2-cp313-cp313-win32.whl", hash = "sha256:bcf3e58998965654fdaff38e58584d8937aa3096ab5354d493c77d1fdd66d7a1", size = 15101 }, + { url = "https://files.pythonhosted.org/packages/29/88/07df22d2dd4df40aba9f3e402e6dc1b8ee86297dddbad4872bd5e7b0094f/MarkupSafe-3.0.2-cp313-cp313-win_amd64.whl", hash = "sha256:e6a2a455bd412959b57a172ce6328d2dd1f01cb2135efda2e4576e8a23fa3b0f", size = 15603 }, + { url = "https://files.pythonhosted.org/packages/62/6a/8b89d24db2d32d433dffcd6a8779159da109842434f1dd2f6e71f32f738c/MarkupSafe-3.0.2-cp313-cp313t-macosx_10_13_universal2.whl", hash = "sha256:b5a6b3ada725cea8a5e634536b1b01c30bcdcd7f9c6fff4151548d5bf6b3a36c", size = 14510 }, + { url = "https://files.pythonhosted.org/packages/7a/06/a10f955f70a2e5a9bf78d11a161029d278eeacbd35ef806c3fd17b13060d/MarkupSafe-3.0.2-cp313-cp313t-macosx_11_0_arm64.whl", hash = "sha256:a904af0a6162c73e3edcb969eeeb53a63ceeb5d8cf642fade7d39e7963a22ddb", size = 12486 }, + { url = "https://files.pythonhosted.org/packages/34/cf/65d4a571869a1a9078198ca28f39fba5fbb910f952f9dbc5220afff9f5e6/MarkupSafe-3.0.2-cp313-cp313t-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:4aa4e5faecf353ed117801a068ebab7b7e09ffb6e1d5e412dc852e0da018126c", size = 25480 }, + { url = "https://files.pythonhosted.org/packages/0c/e3/90e9651924c430b885468b56b3d597cabf6d72be4b24a0acd1fa0e12af67/MarkupSafe-3.0.2-cp313-cp313t-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:c0ef13eaeee5b615fb07c9a7dadb38eac06a0608b41570d8ade51c56539e509d", size = 23914 }, + { url = "https://files.pythonhosted.org/packages/66/8c/6c7cf61f95d63bb866db39085150df1f2a5bd3335298f14a66b48e92659c/MarkupSafe-3.0.2-cp313-cp313t-manylinux_2_5_i686.manylinux1_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:d16a81a06776313e817c951135cf7340a3e91e8c1ff2fac444cfd75fffa04afe", size = 23796 }, + { url = "https://files.pythonhosted.org/packages/bb/35/cbe9238ec3f47ac9a7c8b3df7a808e7cb50fe149dc7039f5f454b3fba218/MarkupSafe-3.0.2-cp313-cp313t-musllinux_1_2_aarch64.whl", hash = "sha256:6381026f158fdb7c72a168278597a5e3a5222e83ea18f543112b2662a9b699c5", size = 25473 }, + { url = "https://files.pythonhosted.org/packages/e6/32/7621a4382488aa283cc05e8984a9c219abad3bca087be9ec77e89939ded9/MarkupSafe-3.0.2-cp313-cp313t-musllinux_1_2_i686.whl", hash = "sha256:3d79d162e7be8f996986c064d1c7c817f6df3a77fe3d6859f6f9e7be4b8c213a", size = 24114 }, + { url = "https://files.pythonhosted.org/packages/0d/80/0985960e4b89922cb5a0bac0ed39c5b96cbc1a536a99f30e8c220a996ed9/MarkupSafe-3.0.2-cp313-cp313t-musllinux_1_2_x86_64.whl", hash = "sha256:131a3c7689c85f5ad20f9f6fb1b866f402c445b220c19fe4308c0b147ccd2ad9", size = 24098 }, + { url = "https://files.pythonhosted.org/packages/82/78/fedb03c7d5380df2427038ec8d973587e90561b2d90cd472ce9254cf348b/MarkupSafe-3.0.2-cp313-cp313t-win32.whl", hash = "sha256:ba8062ed2cf21c07a9e295d5b8a2a5ce678b913b45fdf68c32d95d6c1291e0b6", size = 15208 }, + { url = "https://files.pythonhosted.org/packages/4f/65/6079a46068dfceaeabb5dcad6d674f5f5c61a6fa5673746f42a9f4c233b3/MarkupSafe-3.0.2-cp313-cp313t-win_amd64.whl", hash = "sha256:e444a31f8db13eb18ada366ab3cf45fd4b31e4db1236a4448f68778c1d1a5a2f", size = 15739 }, +] + +[[package]] +name = "mdurl" +version = "0.1.2" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/d6/54/cfe61301667036ec958cb99bd3efefba235e65cdeb9c84d24a8293ba1d90/mdurl-0.1.2.tar.gz", hash = "sha256:bb413d29f5eea38f31dd4754dd7377d4465116fb207585f97bf925588687c1ba", size = 8729 } +wheels = [ + { url = "https://files.pythonhosted.org/packages/b3/38/89ba8ad64ae25be8de66a6d463314cf1eb366222074cfda9ee839c56a4b4/mdurl-0.1.2-py3-none-any.whl", hash = "sha256:84008a41e51615a49fc9966191ff91509e3c40b939176e643fd50a5c2196b8f8", size = 9979 }, +] + +[[package]] +name = "mergedeep" +version = "1.3.4" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/3a/41/580bb4006e3ed0361b8151a01d324fb03f420815446c7def45d02f74c270/mergedeep-1.3.4.tar.gz", hash = "sha256:0096d52e9dad9939c3d975a774666af186eda617e6ca84df4c94dec30004f2a8", size = 4661 } +wheels = [ + { url = "https://files.pythonhosted.org/packages/2c/19/04f9b178c2d8a15b076c8b5140708fa6ffc5601fb6f1e975537072df5b2a/mergedeep-1.3.4-py3-none-any.whl", hash = "sha256:70775750742b25c0d8f36c55aed03d24c3384d17c951b3175d898bd778ef0307", size = 6354 }, +] + +[[package]] +name = "mkdocs" +version = "1.6.1" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "click" }, + { name = "colorama", marker = "sys_platform == 'win32'" }, + { name = "ghp-import" }, + { name = "jinja2" }, + { name = "markdown" }, + { name = "markupsafe" }, + { name = "mergedeep" }, + { name = "mkdocs-get-deps" }, + { name = "packaging" }, + { name = "pathspec" }, + { name = "pyyaml" }, + { name = "pyyaml-env-tag" }, + { name = "watchdog" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/bc/c6/bbd4f061bd16b378247f12953ffcb04786a618ce5e904b8c5a01a0309061/mkdocs-1.6.1.tar.gz", hash = "sha256:7b432f01d928c084353ab39c57282f29f92136665bdd6abf7c1ec8d822ef86f2", size = 3889159 } +wheels = [ + { url = "https://files.pythonhosted.org/packages/22/5b/dbc6a8cddc9cfa9c4971d59fb12bb8d42e161b7e7f8cc89e49137c5b279c/mkdocs-1.6.1-py3-none-any.whl", hash = "sha256:db91759624d1647f3f34aa0c3f327dd2601beae39a366d6e064c03468d35c20e", size = 3864451 }, +] + +[[package]] +name = "mkdocs-autorefs" +version = "1.4.2" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "markdown" }, + { name = "markupsafe" }, + { name = "mkdocs" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/47/0c/c9826f35b99c67fa3a7cddfa094c1a6c43fafde558c309c6e4403e5b37dc/mkdocs_autorefs-1.4.2.tar.gz", hash = "sha256:e2ebe1abd2b67d597ed19378c0fff84d73d1dbce411fce7a7cc6f161888b6749", size = 54961 } +wheels = [ + { url = "https://files.pythonhosted.org/packages/87/dc/fc063b78f4b769d1956319351704e23ebeba1e9e1d6a41b4b602325fd7e4/mkdocs_autorefs-1.4.2-py3-none-any.whl", hash = "sha256:83d6d777b66ec3c372a1aad4ae0cf77c243ba5bcda5bf0c6b8a2c5e7a3d89f13", size = 24969 }, +] + +[[package]] +name = "mkdocs-get-deps" +version = "0.2.0" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "mergedeep" }, + { name = "platformdirs" }, + { name = "pyyaml" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/98/f5/ed29cd50067784976f25ed0ed6fcd3c2ce9eb90650aa3b2796ddf7b6870b/mkdocs_get_deps-0.2.0.tar.gz", hash = "sha256:162b3d129c7fad9b19abfdcb9c1458a651628e4b1dea628ac68790fb3061c60c", size = 10239 } +wheels = [ + { url = "https://files.pythonhosted.org/packages/9f/d4/029f984e8d3f3b6b726bd33cafc473b75e9e44c0f7e80a5b29abc466bdea/mkdocs_get_deps-0.2.0-py3-none-any.whl", hash = "sha256:2bf11d0b133e77a0dd036abeeb06dec8775e46efa526dc70667d8863eefc6134", size = 9521 }, +] + +[[package]] +name = "mkdocs-include-markdown-plugin" +version = "7.1.6" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "mkdocs" }, + { name = "wcmatch" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/2c/17/988d97ac6849b196f54d45ca9c60ca894880c160a512785f03834704b3d9/mkdocs_include_markdown_plugin-7.1.6.tar.gz", hash = "sha256:a0753cb82704c10a287f1e789fc9848f82b6beb8749814b24b03dd9f67816677", size = 23391 } +wheels = [ + { url = "https://files.pythonhosted.org/packages/e2/a1/6cf1667a05e5f468e1263fcf848772bca8cc9e358cd57ae19a01f92c9f6f/mkdocs_include_markdown_plugin-7.1.6-py3-none-any.whl", hash = "sha256:7975a593514887c18ecb68e11e35c074c5499cfa3e51b18cd16323862e1f7345", size = 27161 }, +] + +[[package]] +name = "mkdocs-literate-nav" +version = "0.6.2" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "mkdocs" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/f6/5f/99aa379b305cd1c2084d42db3d26f6de0ea9bf2cc1d10ed17f61aff35b9a/mkdocs_literate_nav-0.6.2.tar.gz", hash = "sha256:760e1708aa4be86af81a2b56e82c739d5a8388a0eab1517ecfd8e5aa40810a75", size = 17419 } +wheels = [ + { url = "https://files.pythonhosted.org/packages/8a/84/b5b14d2745e4dd1a90115186284e9ee1b4d0863104011ab46abb7355a1c3/mkdocs_literate_nav-0.6.2-py3-none-any.whl", hash = "sha256:0a6489a26ec7598477b56fa112056a5e3a6c15729f0214bea8a4dbc55bd5f630", size = 13261 }, +] + +[[package]] +name = "mkdocs-macros-plugin" +version = "1.3.7" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "hjson" }, + { name = "jinja2" }, + { name = "mkdocs" }, + { name = "packaging" }, + { name = "pathspec" }, + { name = "python-dateutil" }, + { name = "pyyaml" }, + { name = "super-collections" }, + { name = "termcolor" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/43/65/61a746c56788867221aebf07fe4b6b4c08ac99cf341fd51d728c89d1456e/mkdocs_macros_plugin-1.3.7.tar.gz", hash = "sha256:17c7fd1a49b94defcdb502fd453d17a1e730f8836523379d21292eb2be4cb523", size = 33466 } +wheels = [ + { url = "https://files.pythonhosted.org/packages/55/cf/f03331298ee50a4da6fb72ccec79078041158c1f8b5fc24835c1be42232e/mkdocs_macros_plugin-1.3.7-py3-none-any.whl", hash = "sha256:02432033a5b77fb247d6ec7924e72fc4ceec264165b1644ab8d0dc159c22ce59", size = 37799 }, +] + +[[package]] +name = "mkdocs-material" +version = "9.6.15" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "babel" }, + { name = "backrefs" }, + { name = "colorama" }, + { name = "jinja2" }, + { name = "markdown" }, + { name = "mkdocs" }, + { name = "mkdocs-material-extensions" }, + { name = "paginate" }, + { name = "pygments" }, + { name = "pymdown-extensions" }, + { name = "requests" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/95/c1/f804ba2db2ddc2183e900befe7dad64339a34fa935034e1ab405289d0a97/mkdocs_material-9.6.15.tar.gz", hash = "sha256:64adf8fa8dba1a17905b6aee1894a5aafd966d4aeb44a11088519b0f5ca4f1b5", size = 3951836 } +wheels = [ + { url = "https://files.pythonhosted.org/packages/1d/30/dda19f0495a9096b64b6b3c07c4bfcff1c76ee0fc521086d53593f18b4c0/mkdocs_material-9.6.15-py3-none-any.whl", hash = "sha256:ac969c94d4fe5eb7c924b6d2f43d7db41159ea91553d18a9afc4780c34f2717a", size = 8716840 }, +] + +[[package]] +name = "mkdocs-material-extensions" +version = "1.3.1" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/79/9b/9b4c96d6593b2a541e1cb8b34899a6d021d208bb357042823d4d2cabdbe7/mkdocs_material_extensions-1.3.1.tar.gz", hash = "sha256:10c9511cea88f568257f960358a467d12b970e1f7b2c0e5fb2bb48cab1928443", size = 11847 } +wheels = [ + { url = "https://files.pythonhosted.org/packages/5b/54/662a4743aa81d9582ee9339d4ffa3c8fd40a4965e033d77b9da9774d3960/mkdocs_material_extensions-1.3.1-py3-none-any.whl", hash = "sha256:adff8b62700b25cb77b53358dad940f3ef973dd6db797907c49e3c2ef3ab4e31", size = 8728 }, +] + +[[package]] +name = "mkdocstrings" +version = "0.29.1" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "jinja2" }, + { name = "markdown" }, + { name = "markupsafe" }, + { name = "mkdocs" }, + { name = "mkdocs-autorefs" }, + { name = "pymdown-extensions" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/41/e8/d22922664a627a0d3d7ff4a6ca95800f5dde54f411982591b4621a76225d/mkdocstrings-0.29.1.tar.gz", hash = "sha256:8722f8f8c5cd75da56671e0a0c1bbed1df9946c0cef74794d6141b34011abd42", size = 1212686 } +wheels = [ + { url = "https://files.pythonhosted.org/packages/98/14/22533a578bf8b187e05d67e2c1721ce10e3f526610eebaf7a149d557ea7a/mkdocstrings-0.29.1-py3-none-any.whl", hash = "sha256:37a9736134934eea89cbd055a513d40a020d87dfcae9e3052c2a6b8cd4af09b6", size = 1631075 }, +] + +[[package]] +name = "mkdocstrings-python" +version = "1.16.12" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "griffe" }, + { name = "mkdocs-autorefs" }, + { name = "mkdocstrings" }, + { name = "typing-extensions", marker = "python_full_version < '3.11'" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/bf/ed/b886f8c714fd7cccc39b79646b627dbea84cd95c46be43459ef46852caf0/mkdocstrings_python-1.16.12.tar.gz", hash = "sha256:9b9eaa066e0024342d433e332a41095c4e429937024945fea511afe58f63175d", size = 206065 } +wheels = [ + { url = "https://files.pythonhosted.org/packages/3b/dd/a24ee3de56954bfafb6ede7cd63c2413bb842cc48eb45e41c43a05a33074/mkdocstrings_python-1.16.12-py3-none-any.whl", hash = "sha256:22ded3a63b3d823d57457a70ff9860d5a4de9e8b1e482876fc9baabaf6f5f374", size = 124287 }, +] + +[[package]] +name = "ml-dtypes" +version = "0.5.1" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "numpy", version = "2.2.6", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version < '3.11'" }, + { name = "numpy", version = "2.3.1", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version >= '3.11'" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/32/49/6e67c334872d2c114df3020e579f3718c333198f8312290e09ec0216703a/ml_dtypes-0.5.1.tar.gz", hash = "sha256:ac5b58559bb84a95848ed6984eb8013249f90b6bab62aa5acbad876e256002c9", size = 698772 } +wheels = [ + { url = "https://files.pythonhosted.org/packages/f4/88/11ebdbc75445eeb5b6869b708a0d787d1ed812ff86c2170bbfb95febdce1/ml_dtypes-0.5.1-cp310-cp310-macosx_10_9_universal2.whl", hash = "sha256:bd73f51957949069573ff783563486339a9285d72e2f36c18e0c1aa9ca7eb190", size = 671450 }, + { url = "https://files.pythonhosted.org/packages/a4/a4/9321cae435d6140f9b0e7af8334456a854b60e3a9c6101280a16e3594965/ml_dtypes-0.5.1-cp310-cp310-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:810512e2eccdfc3b41eefa3a27402371a3411453a1efc7e9c000318196140fed", size = 4621075 }, + { url = "https://files.pythonhosted.org/packages/16/d8/4502e12c6a10d42e13a552e8d97f20198e3cf82a0d1411ad50be56a5077c/ml_dtypes-0.5.1-cp310-cp310-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:141b2ea2f20bb10802ddca55d91fe21231ef49715cfc971998e8f2a9838f3dbe", size = 4738414 }, + { url = "https://files.pythonhosted.org/packages/6b/7e/bc54ae885e4d702e60a4bf50aa9066ff35e9c66b5213d11091f6bffb3036/ml_dtypes-0.5.1-cp310-cp310-win_amd64.whl", hash = "sha256:26ebcc69d7b779c8f129393e99732961b5cc33fcff84090451f448c89b0e01b4", size = 209718 }, + { url = "https://files.pythonhosted.org/packages/c9/fd/691335926126bb9beeb030b61a28f462773dcf16b8e8a2253b599013a303/ml_dtypes-0.5.1-cp311-cp311-macosx_10_9_universal2.whl", hash = "sha256:023ce2f502efd4d6c1e0472cc58ce3640d051d40e71e27386bed33901e201327", size = 671448 }, + { url = "https://files.pythonhosted.org/packages/ff/a6/63832d91f2feb250d865d069ba1a5d0c686b1f308d1c74ce9764472c5e22/ml_dtypes-0.5.1-cp311-cp311-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:7000b6e4d8ef07542c05044ec5d8bbae1df083b3f56822c3da63993a113e716f", size = 4625792 }, + { url = "https://files.pythonhosted.org/packages/cc/2a/5421fd3dbe6eef9b844cc9d05f568b9fb568503a2e51cb1eb4443d9fc56b/ml_dtypes-0.5.1-cp311-cp311-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:c09526488c3a9e8b7a23a388d4974b670a9a3dd40c5c8a61db5593ce9b725bab", size = 4743893 }, + { url = "https://files.pythonhosted.org/packages/60/30/d3f0fc9499a22801219679a7f3f8d59f1429943c6261f445fb4bfce20718/ml_dtypes-0.5.1-cp311-cp311-win_amd64.whl", hash = "sha256:15ad0f3b0323ce96c24637a88a6f44f6713c64032f27277b069f285c3cf66478", size = 209712 }, + { url = "https://files.pythonhosted.org/packages/47/56/1bb21218e1e692506c220ffabd456af9733fba7aa1b14f73899979f4cc20/ml_dtypes-0.5.1-cp312-cp312-macosx_10_9_universal2.whl", hash = "sha256:6f462f5eca22fb66d7ff9c4744a3db4463af06c49816c4b6ac89b16bfcdc592e", size = 670372 }, + { url = "https://files.pythonhosted.org/packages/20/95/d8bd96a3b60e00bf31bd78ca4bdd2d6bbaf5acb09b42844432d719d34061/ml_dtypes-0.5.1-cp312-cp312-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:6f76232163b5b9c34291b54621ee60417601e2e4802a188a0ea7157cd9b323f4", size = 4635946 }, + { url = "https://files.pythonhosted.org/packages/08/57/5d58fad4124192b1be42f68bd0c0ddaa26e44a730ff8c9337adade2f5632/ml_dtypes-0.5.1-cp312-cp312-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:ad4953c5eb9c25a56d11a913c2011d7e580a435ef5145f804d98efa14477d390", size = 4694804 }, + { url = "https://files.pythonhosted.org/packages/38/bc/c4260e4a6c6bf684d0313308de1c860467275221d5e7daf69b3fcddfdd0b/ml_dtypes-0.5.1-cp312-cp312-win_amd64.whl", hash = "sha256:9626d0bca1fb387d5791ca36bacbba298c5ef554747b7ebeafefb4564fc83566", size = 210853 }, + { url = "https://files.pythonhosted.org/packages/0f/92/bb6a3d18e16fddd18ce6d5f480e1919b33338c70e18cba831c6ae59812ee/ml_dtypes-0.5.1-cp313-cp313-macosx_10_13_universal2.whl", hash = "sha256:12651420130ee7cc13059fc56dac6ad300c3af3848b802d475148c9defd27c23", size = 667696 }, + { url = "https://files.pythonhosted.org/packages/6d/29/cfc89d842767e9a51146043b0fa18332c2b38f8831447e6cb1160e3c6102/ml_dtypes-0.5.1-cp313-cp313-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:c9945669d3dadf8acb40ec2e57d38c985d8c285ea73af57fc5b09872c516106d", size = 4638365 }, + { url = "https://files.pythonhosted.org/packages/be/26/adc36e3ea09603d9f6d114894e1c1b7b8e8a9ef6d0b031cc270c6624a37c/ml_dtypes-0.5.1-cp313-cp313-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:bf9975bda82a99dc935f2ae4c83846d86df8fd6ba179614acac8e686910851da", size = 4702722 }, + { url = "https://files.pythonhosted.org/packages/da/8a/a2b9375c94077e5a488a624a195621407846f504068ce22ccf805c674156/ml_dtypes-0.5.1-cp313-cp313-win_amd64.whl", hash = "sha256:fd918d4e6a4e0c110e2e05be7a7814d10dc1b95872accbf6512b80a109b71ae1", size = 210850 }, + { url = "https://files.pythonhosted.org/packages/52/38/703169100fdde27957f061d4d0ea3e00525775a09acaccf7e655d9609d55/ml_dtypes-0.5.1-cp313-cp313t-macosx_10_13_universal2.whl", hash = "sha256:05f23447a1c20ddf4dc7c2c661aa9ed93fcb2658f1017c204d1e758714dc28a8", size = 693043 }, + { url = "https://files.pythonhosted.org/packages/28/ff/4e234c9c23e0d456f5da5a326c103bf890c746d93351524d987e41f438b3/ml_dtypes-0.5.1-cp313-cp313t-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:1b7fbe5571fdf28fd3aaab3ef4aafc847de9ebf263be959958c1ca58ec8eadf5", size = 4903946 }, + { url = "https://files.pythonhosted.org/packages/b7/45/c1a1ccfdd02bc4173ca0f4a2d327683a27df85797b885eb1da1ca325b85c/ml_dtypes-0.5.1-cp313-cp313t-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:d13755f8e8445b3870114e5b6240facaa7cb0c3361e54beba3e07fa912a6e12b", size = 5052731 }, +] + +[[package]] +name = "msgpack" +version = "1.1.1" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/45/b1/ea4f68038a18c77c9467400d166d74c4ffa536f34761f7983a104357e614/msgpack-1.1.1.tar.gz", hash = "sha256:77b79ce34a2bdab2594f490c8e80dd62a02d650b91a75159a63ec413b8d104cd", size = 173555 } +wheels = [ + { url = "https://files.pythonhosted.org/packages/33/52/f30da112c1dc92cf64f57d08a273ac771e7b29dea10b4b30369b2d7e8546/msgpack-1.1.1-cp310-cp310-macosx_10_9_x86_64.whl", hash = "sha256:353b6fc0c36fde68b661a12949d7d49f8f51ff5fa019c1e47c87c4ff34b080ed", size = 81799 }, + { url = "https://files.pythonhosted.org/packages/e4/35/7bfc0def2f04ab4145f7f108e3563f9b4abae4ab0ed78a61f350518cc4d2/msgpack-1.1.1-cp310-cp310-macosx_11_0_arm64.whl", hash = "sha256:79c408fcf76a958491b4e3b103d1c417044544b68e96d06432a189b43d1215c8", size = 78278 }, + { url = "https://files.pythonhosted.org/packages/e8/c5/df5d6c1c39856bc55f800bf82778fd4c11370667f9b9e9d51b2f5da88f20/msgpack-1.1.1-cp310-cp310-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:78426096939c2c7482bf31ef15ca219a9e24460289c00dd0b94411040bb73ad2", size = 402805 }, + { url = "https://files.pythonhosted.org/packages/20/8e/0bb8c977efecfe6ea7116e2ed73a78a8d32a947f94d272586cf02a9757db/msgpack-1.1.1-cp310-cp310-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:8b17ba27727a36cb73aabacaa44b13090feb88a01d012c0f4be70c00f75048b4", size = 408642 }, + { url = "https://files.pythonhosted.org/packages/59/a1/731d52c1aeec52006be6d1f8027c49fdc2cfc3ab7cbe7c28335b2910d7b6/msgpack-1.1.1-cp310-cp310-manylinux_2_5_i686.manylinux1_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:7a17ac1ea6ec3c7687d70201cfda3b1e8061466f28f686c24f627cae4ea8efd0", size = 395143 }, + { url = "https://files.pythonhosted.org/packages/2b/92/b42911c52cda2ba67a6418ffa7d08969edf2e760b09015593c8a8a27a97d/msgpack-1.1.1-cp310-cp310-musllinux_1_2_aarch64.whl", hash = "sha256:88d1e966c9235c1d4e2afac21ca83933ba59537e2e2727a999bf3f515ca2af26", size = 395986 }, + { url = "https://files.pythonhosted.org/packages/61/dc/8ae165337e70118d4dab651b8b562dd5066dd1e6dd57b038f32ebc3e2f07/msgpack-1.1.1-cp310-cp310-musllinux_1_2_i686.whl", hash = "sha256:f6d58656842e1b2ddbe07f43f56b10a60f2ba5826164910968f5933e5178af75", size = 402682 }, + { url = "https://files.pythonhosted.org/packages/58/27/555851cb98dcbd6ce041df1eacb25ac30646575e9cd125681aa2f4b1b6f1/msgpack-1.1.1-cp310-cp310-musllinux_1_2_x86_64.whl", hash = "sha256:96decdfc4adcbc087f5ea7ebdcfd3dee9a13358cae6e81d54be962efc38f6338", size = 406368 }, + { url = "https://files.pythonhosted.org/packages/d4/64/39a26add4ce16f24e99eabb9005e44c663db00e3fce17d4ae1ae9d61df99/msgpack-1.1.1-cp310-cp310-win32.whl", hash = "sha256:6640fd979ca9a212e4bcdf6eb74051ade2c690b862b679bfcb60ae46e6dc4bfd", size = 65004 }, + { url = "https://files.pythonhosted.org/packages/7d/18/73dfa3e9d5d7450d39debde5b0d848139f7de23bd637a4506e36c9800fd6/msgpack-1.1.1-cp310-cp310-win_amd64.whl", hash = "sha256:8b65b53204fe1bd037c40c4148d00ef918eb2108d24c9aaa20bc31f9810ce0a8", size = 71548 }, + { url = "https://files.pythonhosted.org/packages/7f/83/97f24bf9848af23fe2ba04380388216defc49a8af6da0c28cc636d722502/msgpack-1.1.1-cp311-cp311-macosx_10_9_x86_64.whl", hash = "sha256:71ef05c1726884e44f8b1d1773604ab5d4d17729d8491403a705e649116c9558", size = 82728 }, + { url = "https://files.pythonhosted.org/packages/aa/7f/2eaa388267a78401f6e182662b08a588ef4f3de6f0eab1ec09736a7aaa2b/msgpack-1.1.1-cp311-cp311-macosx_11_0_arm64.whl", hash = "sha256:36043272c6aede309d29d56851f8841ba907a1a3d04435e43e8a19928e243c1d", size = 79279 }, + { url = "https://files.pythonhosted.org/packages/f8/46/31eb60f4452c96161e4dfd26dbca562b4ec68c72e4ad07d9566d7ea35e8a/msgpack-1.1.1-cp311-cp311-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:a32747b1b39c3ac27d0670122b57e6e57f28eefb725e0b625618d1b59bf9d1e0", size = 423859 }, + { url = "https://files.pythonhosted.org/packages/45/16/a20fa8c32825cc7ae8457fab45670c7a8996d7746ce80ce41cc51e3b2bd7/msgpack-1.1.1-cp311-cp311-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:8a8b10fdb84a43e50d38057b06901ec9da52baac6983d3f709d8507f3889d43f", size = 429975 }, + { url = "https://files.pythonhosted.org/packages/86/ea/6c958e07692367feeb1a1594d35e22b62f7f476f3c568b002a5ea09d443d/msgpack-1.1.1-cp311-cp311-manylinux_2_5_i686.manylinux1_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:ba0c325c3f485dc54ec298d8b024e134acf07c10d494ffa24373bea729acf704", size = 413528 }, + { url = "https://files.pythonhosted.org/packages/75/05/ac84063c5dae79722bda9f68b878dc31fc3059adb8633c79f1e82c2cd946/msgpack-1.1.1-cp311-cp311-musllinux_1_2_aarch64.whl", hash = "sha256:88daaf7d146e48ec71212ce21109b66e06a98e5e44dca47d853cbfe171d6c8d2", size = 413338 }, + { url = "https://files.pythonhosted.org/packages/69/e8/fe86b082c781d3e1c09ca0f4dacd457ede60a13119b6ce939efe2ea77b76/msgpack-1.1.1-cp311-cp311-musllinux_1_2_i686.whl", hash = "sha256:d8b55ea20dc59b181d3f47103f113e6f28a5e1c89fd5b67b9140edb442ab67f2", size = 422658 }, + { url = "https://files.pythonhosted.org/packages/3b/2b/bafc9924df52d8f3bb7c00d24e57be477f4d0f967c0a31ef5e2225e035c7/msgpack-1.1.1-cp311-cp311-musllinux_1_2_x86_64.whl", hash = "sha256:4a28e8072ae9779f20427af07f53bbb8b4aa81151054e882aee333b158da8752", size = 427124 }, + { url = "https://files.pythonhosted.org/packages/a2/3b/1f717e17e53e0ed0b68fa59e9188f3f610c79d7151f0e52ff3cd8eb6b2dc/msgpack-1.1.1-cp311-cp311-win32.whl", hash = "sha256:7da8831f9a0fdb526621ba09a281fadc58ea12701bc709e7b8cbc362feabc295", size = 65016 }, + { url = "https://files.pythonhosted.org/packages/48/45/9d1780768d3b249accecc5a38c725eb1e203d44a191f7b7ff1941f7df60c/msgpack-1.1.1-cp311-cp311-win_amd64.whl", hash = "sha256:5fd1b58e1431008a57247d6e7cc4faa41c3607e8e7d4aaf81f7c29ea013cb458", size = 72267 }, + { url = "https://files.pythonhosted.org/packages/e3/26/389b9c593eda2b8551b2e7126ad3a06af6f9b44274eb3a4f054d48ff7e47/msgpack-1.1.1-cp312-cp312-macosx_10_13_x86_64.whl", hash = "sha256:ae497b11f4c21558d95de9f64fff7053544f4d1a17731c866143ed6bb4591238", size = 82359 }, + { url = "https://files.pythonhosted.org/packages/ab/65/7d1de38c8a22cf8b1551469159d4b6cf49be2126adc2482de50976084d78/msgpack-1.1.1-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:33be9ab121df9b6b461ff91baac6f2731f83d9b27ed948c5b9d1978ae28bf157", size = 79172 }, + { url = "https://files.pythonhosted.org/packages/0f/bd/cacf208b64d9577a62c74b677e1ada005caa9b69a05a599889d6fc2ab20a/msgpack-1.1.1-cp312-cp312-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:6f64ae8fe7ffba251fecb8408540c34ee9df1c26674c50c4544d72dbf792e5ce", size = 425013 }, + { url = "https://files.pythonhosted.org/packages/4d/ec/fd869e2567cc9c01278a736cfd1697941ba0d4b81a43e0aa2e8d71dab208/msgpack-1.1.1-cp312-cp312-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:a494554874691720ba5891c9b0b39474ba43ffb1aaf32a5dac874effb1619e1a", size = 426905 }, + { url = "https://files.pythonhosted.org/packages/55/2a/35860f33229075bce803a5593d046d8b489d7ba2fc85701e714fc1aaf898/msgpack-1.1.1-cp312-cp312-manylinux_2_5_i686.manylinux1_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:cb643284ab0ed26f6957d969fe0dd8bb17beb567beb8998140b5e38a90974f6c", size = 407336 }, + { url = "https://files.pythonhosted.org/packages/8c/16/69ed8f3ada150bf92745fb4921bd621fd2cdf5a42e25eb50bcc57a5328f0/msgpack-1.1.1-cp312-cp312-musllinux_1_2_aarch64.whl", hash = "sha256:d275a9e3c81b1093c060c3837e580c37f47c51eca031f7b5fb76f7b8470f5f9b", size = 409485 }, + { url = "https://files.pythonhosted.org/packages/c6/b6/0c398039e4c6d0b2e37c61d7e0e9d13439f91f780686deb8ee64ecf1ae71/msgpack-1.1.1-cp312-cp312-musllinux_1_2_i686.whl", hash = "sha256:4fd6b577e4541676e0cc9ddc1709d25014d3ad9a66caa19962c4f5de30fc09ef", size = 412182 }, + { url = "https://files.pythonhosted.org/packages/b8/d0/0cf4a6ecb9bc960d624c93effaeaae75cbf00b3bc4a54f35c8507273cda1/msgpack-1.1.1-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:bb29aaa613c0a1c40d1af111abf025f1732cab333f96f285d6a93b934738a68a", size = 419883 }, + { url = "https://files.pythonhosted.org/packages/62/83/9697c211720fa71a2dfb632cad6196a8af3abea56eece220fde4674dc44b/msgpack-1.1.1-cp312-cp312-win32.whl", hash = "sha256:870b9a626280c86cff9c576ec0d9cbcc54a1e5ebda9cd26dab12baf41fee218c", size = 65406 }, + { url = "https://files.pythonhosted.org/packages/c0/23/0abb886e80eab08f5e8c485d6f13924028602829f63b8f5fa25a06636628/msgpack-1.1.1-cp312-cp312-win_amd64.whl", hash = "sha256:5692095123007180dca3e788bb4c399cc26626da51629a31d40207cb262e67f4", size = 72558 }, + { url = "https://files.pythonhosted.org/packages/a1/38/561f01cf3577430b59b340b51329803d3a5bf6a45864a55f4ef308ac11e3/msgpack-1.1.1-cp313-cp313-macosx_10_13_x86_64.whl", hash = "sha256:3765afa6bd4832fc11c3749be4ba4b69a0e8d7b728f78e68120a157a4c5d41f0", size = 81677 }, + { url = "https://files.pythonhosted.org/packages/09/48/54a89579ea36b6ae0ee001cba8c61f776451fad3c9306cd80f5b5c55be87/msgpack-1.1.1-cp313-cp313-macosx_11_0_arm64.whl", hash = "sha256:8ddb2bcfd1a8b9e431c8d6f4f7db0773084e107730ecf3472f1dfe9ad583f3d9", size = 78603 }, + { url = "https://files.pythonhosted.org/packages/a0/60/daba2699b308e95ae792cdc2ef092a38eb5ee422f9d2fbd4101526d8a210/msgpack-1.1.1-cp313-cp313-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:196a736f0526a03653d829d7d4c5500a97eea3648aebfd4b6743875f28aa2af8", size = 420504 }, + { url = "https://files.pythonhosted.org/packages/20/22/2ebae7ae43cd8f2debc35c631172ddf14e2a87ffcc04cf43ff9df9fff0d3/msgpack-1.1.1-cp313-cp313-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:9d592d06e3cc2f537ceeeb23d38799c6ad83255289bb84c2e5792e5a8dea268a", size = 423749 }, + { url = "https://files.pythonhosted.org/packages/40/1b/54c08dd5452427e1179a40b4b607e37e2664bca1c790c60c442c8e972e47/msgpack-1.1.1-cp313-cp313-manylinux_2_5_i686.manylinux1_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:4df2311b0ce24f06ba253fda361f938dfecd7b961576f9be3f3fbd60e87130ac", size = 404458 }, + { url = "https://files.pythonhosted.org/packages/2e/60/6bb17e9ffb080616a51f09928fdd5cac1353c9becc6c4a8abd4e57269a16/msgpack-1.1.1-cp313-cp313-musllinux_1_2_aarch64.whl", hash = "sha256:e4141c5a32b5e37905b5940aacbc59739f036930367d7acce7a64e4dec1f5e0b", size = 405976 }, + { url = "https://files.pythonhosted.org/packages/ee/97/88983e266572e8707c1f4b99c8fd04f9eb97b43f2db40e3172d87d8642db/msgpack-1.1.1-cp313-cp313-musllinux_1_2_i686.whl", hash = "sha256:b1ce7f41670c5a69e1389420436f41385b1aa2504c3b0c30620764b15dded2e7", size = 408607 }, + { url = "https://files.pythonhosted.org/packages/bc/66/36c78af2efaffcc15a5a61ae0df53a1d025f2680122e2a9eb8442fed3ae4/msgpack-1.1.1-cp313-cp313-musllinux_1_2_x86_64.whl", hash = "sha256:4147151acabb9caed4e474c3344181e91ff7a388b888f1e19ea04f7e73dc7ad5", size = 424172 }, + { url = "https://files.pythonhosted.org/packages/8c/87/a75eb622b555708fe0427fab96056d39d4c9892b0c784b3a721088c7ee37/msgpack-1.1.1-cp313-cp313-win32.whl", hash = "sha256:500e85823a27d6d9bba1d057c871b4210c1dd6fb01fbb764e37e4e8847376323", size = 65347 }, + { url = "https://files.pythonhosted.org/packages/ca/91/7dc28d5e2a11a5ad804cf2b7f7a5fcb1eb5a4966d66a5d2b41aee6376543/msgpack-1.1.1-cp313-cp313-win_amd64.whl", hash = "sha256:6d489fba546295983abd142812bda76b57e33d0b9f5d5b71c09a583285506f69", size = 72341 }, +] + +[[package]] +name = "mypy" +version = "1.16.1" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "mypy-extensions" }, + { name = "pathspec" }, + { name = "tomli", marker = "python_full_version < '3.11'" }, + { name = "typing-extensions" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/81/69/92c7fa98112e4d9eb075a239caa4ef4649ad7d441545ccffbd5e34607cbb/mypy-1.16.1.tar.gz", hash = "sha256:6bd00a0a2094841c5e47e7374bb42b83d64c527a502e3334e1173a0c24437bab", size = 3324747 } +wheels = [ + { url = "https://files.pythonhosted.org/packages/8e/12/2bf23a80fcef5edb75de9a1e295d778e0f46ea89eb8b115818b663eff42b/mypy-1.16.1-cp310-cp310-macosx_10_9_x86_64.whl", hash = "sha256:b4f0fed1022a63c6fec38f28b7fc77fca47fd490445c69d0a66266c59dd0b88a", size = 10958644 }, + { url = "https://files.pythonhosted.org/packages/08/50/bfe47b3b278eacf348291742fd5e6613bbc4b3434b72ce9361896417cfe5/mypy-1.16.1-cp310-cp310-macosx_11_0_arm64.whl", hash = "sha256:86042bbf9f5a05ea000d3203cf87aa9d0ccf9a01f73f71c58979eb9249f46d72", size = 10087033 }, + { url = "https://files.pythonhosted.org/packages/21/de/40307c12fe25675a0776aaa2cdd2879cf30d99eec91b898de00228dc3ab5/mypy-1.16.1-cp310-cp310-manylinux_2_17_aarch64.manylinux2014_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:ea7469ee5902c95542bea7ee545f7006508c65c8c54b06dc2c92676ce526f3ea", size = 11875645 }, + { url = "https://files.pythonhosted.org/packages/a6/d8/85bdb59e4a98b7a31495bd8f1a4445d8ffc86cde4ab1f8c11d247c11aedc/mypy-1.16.1-cp310-cp310-manylinux_2_17_x86_64.manylinux2014_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:352025753ef6a83cb9e7f2427319bb7875d1fdda8439d1e23de12ab164179574", size = 12616986 }, + { url = "https://files.pythonhosted.org/packages/0e/d0/bb25731158fa8f8ee9e068d3e94fcceb4971fedf1424248496292512afe9/mypy-1.16.1-cp310-cp310-musllinux_1_2_x86_64.whl", hash = "sha256:ff9fa5b16e4c1364eb89a4d16bcda9987f05d39604e1e6c35378a2987c1aac2d", size = 12878632 }, + { url = "https://files.pythonhosted.org/packages/2d/11/822a9beb7a2b825c0cb06132ca0a5183f8327a5e23ef89717c9474ba0bc6/mypy-1.16.1-cp310-cp310-win_amd64.whl", hash = "sha256:1256688e284632382f8f3b9e2123df7d279f603c561f099758e66dd6ed4e8bd6", size = 9484391 }, + { url = "https://files.pythonhosted.org/packages/9a/61/ec1245aa1c325cb7a6c0f8570a2eee3bfc40fa90d19b1267f8e50b5c8645/mypy-1.16.1-cp311-cp311-macosx_10_9_x86_64.whl", hash = "sha256:472e4e4c100062488ec643f6162dd0d5208e33e2f34544e1fc931372e806c0cc", size = 10890557 }, + { url = "https://files.pythonhosted.org/packages/6b/bb/6eccc0ba0aa0c7a87df24e73f0ad34170514abd8162eb0c75fd7128171fb/mypy-1.16.1-cp311-cp311-macosx_11_0_arm64.whl", hash = "sha256:ea16e2a7d2714277e349e24d19a782a663a34ed60864006e8585db08f8ad1782", size = 10012921 }, + { url = "https://files.pythonhosted.org/packages/5f/80/b337a12e2006715f99f529e732c5f6a8c143bb58c92bb142d5ab380963a5/mypy-1.16.1-cp311-cp311-manylinux_2_17_aarch64.manylinux2014_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:08e850ea22adc4d8a4014651575567b0318ede51e8e9fe7a68f25391af699507", size = 11802887 }, + { url = "https://files.pythonhosted.org/packages/d9/59/f7af072d09793d581a745a25737c7c0a945760036b16aeb620f658a017af/mypy-1.16.1-cp311-cp311-manylinux_2_17_x86_64.manylinux2014_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:22d76a63a42619bfb90122889b903519149879ddbf2ba4251834727944c8baca", size = 12531658 }, + { url = "https://files.pythonhosted.org/packages/82/c4/607672f2d6c0254b94a646cfc45ad589dd71b04aa1f3d642b840f7cce06c/mypy-1.16.1-cp311-cp311-musllinux_1_2_x86_64.whl", hash = "sha256:2c7ce0662b6b9dc8f4ed86eb7a5d505ee3298c04b40ec13b30e572c0e5ae17c4", size = 12732486 }, + { url = "https://files.pythonhosted.org/packages/b6/5e/136555ec1d80df877a707cebf9081bd3a9f397dedc1ab9750518d87489ec/mypy-1.16.1-cp311-cp311-win_amd64.whl", hash = "sha256:211287e98e05352a2e1d4e8759c5490925a7c784ddc84207f4714822f8cf99b6", size = 9479482 }, + { url = "https://files.pythonhosted.org/packages/b4/d6/39482e5fcc724c15bf6280ff5806548c7185e0c090712a3736ed4d07e8b7/mypy-1.16.1-cp312-cp312-macosx_10_13_x86_64.whl", hash = "sha256:af4792433f09575d9eeca5c63d7d90ca4aeceda9d8355e136f80f8967639183d", size = 11066493 }, + { url = "https://files.pythonhosted.org/packages/e6/e5/26c347890efc6b757f4d5bb83f4a0cf5958b8cf49c938ac99b8b72b420a6/mypy-1.16.1-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:66df38405fd8466ce3517eda1f6640611a0b8e70895e2a9462d1d4323c5eb4b9", size = 10081687 }, + { url = "https://files.pythonhosted.org/packages/44/c7/b5cb264c97b86914487d6a24bd8688c0172e37ec0f43e93b9691cae9468b/mypy-1.16.1-cp312-cp312-manylinux_2_17_aarch64.manylinux2014_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:44e7acddb3c48bd2713994d098729494117803616e116032af192871aed80b79", size = 11839723 }, + { url = "https://files.pythonhosted.org/packages/15/f8/491997a9b8a554204f834ed4816bda813aefda31cf873bb099deee3c9a99/mypy-1.16.1-cp312-cp312-manylinux_2_17_x86_64.manylinux2014_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:0ab5eca37b50188163fa7c1b73c685ac66c4e9bdee4a85c9adac0e91d8895e15", size = 12722980 }, + { url = "https://files.pythonhosted.org/packages/df/f0/2bd41e174b5fd93bc9de9a28e4fb673113633b8a7f3a607fa4a73595e468/mypy-1.16.1-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:dedb6229b2c9086247e21a83c309754b9058b438704ad2f6807f0d8227f6ebdd", size = 12903328 }, + { url = "https://files.pythonhosted.org/packages/61/81/5572108a7bec2c46b8aff7e9b524f371fe6ab5efb534d38d6b37b5490da8/mypy-1.16.1-cp312-cp312-win_amd64.whl", hash = "sha256:1f0435cf920e287ff68af3d10a118a73f212deb2ce087619eb4e648116d1fe9b", size = 9562321 }, + { url = "https://files.pythonhosted.org/packages/28/e3/96964af4a75a949e67df4b95318fe2b7427ac8189bbc3ef28f92a1c5bc56/mypy-1.16.1-cp313-cp313-macosx_10_13_x86_64.whl", hash = "sha256:ddc91eb318c8751c69ddb200a5937f1232ee8efb4e64e9f4bc475a33719de438", size = 11063480 }, + { url = "https://files.pythonhosted.org/packages/f5/4d/cd1a42b8e5be278fab7010fb289d9307a63e07153f0ae1510a3d7b703193/mypy-1.16.1-cp313-cp313-macosx_11_0_arm64.whl", hash = "sha256:87ff2c13d58bdc4bbe7dc0dedfe622c0f04e2cb2a492269f3b418df2de05c536", size = 10090538 }, + { url = "https://files.pythonhosted.org/packages/c9/4f/c3c6b4b66374b5f68bab07c8cabd63a049ff69796b844bc759a0ca99bb2a/mypy-1.16.1-cp313-cp313-manylinux_2_17_aarch64.manylinux2014_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:0a7cfb0fe29fe5a9841b7c8ee6dffb52382c45acdf68f032145b75620acfbd6f", size = 11836839 }, + { url = "https://files.pythonhosted.org/packages/b4/7e/81ca3b074021ad9775e5cb97ebe0089c0f13684b066a750b7dc208438403/mypy-1.16.1-cp313-cp313-manylinux_2_17_x86_64.manylinux2014_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:051e1677689c9d9578b9c7f4d206d763f9bbd95723cd1416fad50db49d52f359", size = 12715634 }, + { url = "https://files.pythonhosted.org/packages/e9/95/bdd40c8be346fa4c70edb4081d727a54d0a05382d84966869738cfa8a497/mypy-1.16.1-cp313-cp313-musllinux_1_2_x86_64.whl", hash = "sha256:d5d2309511cc56c021b4b4e462907c2b12f669b2dbeb68300110ec27723971be", size = 12895584 }, + { url = "https://files.pythonhosted.org/packages/5a/fd/d486a0827a1c597b3b48b1bdef47228a6e9ee8102ab8c28f944cb83b65dc/mypy-1.16.1-cp313-cp313-win_amd64.whl", hash = "sha256:4f58ac32771341e38a853c5d0ec0dfe27e18e27da9cdb8bbc882d2249c71a3ee", size = 9573886 }, + { url = "https://files.pythonhosted.org/packages/cf/d3/53e684e78e07c1a2bf7105715e5edd09ce951fc3f47cf9ed095ec1b7a037/mypy-1.16.1-py3-none-any.whl", hash = "sha256:5fc2ac4027d0ef28d6ba69a0343737a23c4d1b83672bf38d1fe237bdc0643b37", size = 2265923 }, +] + +[[package]] +name = "mypy-extensions" +version = "1.1.0" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/a2/6e/371856a3fb9d31ca8dac321cda606860fa4548858c0cc45d9d1d4ca2628b/mypy_extensions-1.1.0.tar.gz", hash = "sha256:52e68efc3284861e772bbcd66823fde5ae21fd2fdb51c62a211403730b916558", size = 6343 } +wheels = [ + { url = "https://files.pythonhosted.org/packages/79/7b/2c79738432f5c924bef5071f933bcc9efd0473bac3b4aa584a6f7c1c8df8/mypy_extensions-1.1.0-py3-none-any.whl", hash = "sha256:1be4cccdb0f2482337c4743e60421de3a356cd97508abadd57d47403e94f5505", size = 4963 }, +] + +[[package]] +name = "nest-asyncio" +version = "1.6.0" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/83/f8/51569ac65d696c8ecbee95938f89d4abf00f47d58d48f6fbabfe8f0baefe/nest_asyncio-1.6.0.tar.gz", hash = "sha256:6f172d5449aca15afd6c646851f4e31e02c598d553a667e38cafa997cfec55fe", size = 7418 } +wheels = [ + { url = "https://files.pythonhosted.org/packages/a0/c4/c2971a3ba4c6103a3d10c4b0f24f461ddc027f0f09763220cf35ca1401b3/nest_asyncio-1.6.0-py3-none-any.whl", hash = "sha256:87af6efd6b5e897c81050477ef65c62e2b2f35d51703cae01aff2905b1852e1c", size = 5195 }, +] + +[[package]] +name = "nodeenv" +version = "1.9.1" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/43/16/fc88b08840de0e0a72a2f9d8c6bae36be573e475a6326ae854bcc549fc45/nodeenv-1.9.1.tar.gz", hash = "sha256:6ec12890a2dab7946721edbfbcd91f3319c6ccc9aec47be7c7e6b7011ee6645f", size = 47437 } +wheels = [ + { url = "https://files.pythonhosted.org/packages/d2/1d/1b658dbd2b9fa9c4c9f32accbfc0205d532c8c6194dc0f2a4c0428e7128a/nodeenv-1.9.1-py2.py3-none-any.whl", hash = "sha256:ba11c9782d29c27c70ffbdda2d7415098754709be8a7056d79a737cd901155c9", size = 22314 }, +] + +[[package]] +name = "numpy" +version = "2.2.6" +source = { registry = "https://pypi.org/simple" } +resolution-markers = [ + "python_full_version < '3.11'", +] +sdist = { url = "https://files.pythonhosted.org/packages/76/21/7d2a95e4bba9dc13d043ee156a356c0a8f0c6309dff6b21b4d71a073b8a8/numpy-2.2.6.tar.gz", hash = "sha256:e29554e2bef54a90aa5cc07da6ce955accb83f21ab5de01a62c8478897b264fd", size = 20276440 } +wheels = [ + { url = "https://files.pythonhosted.org/packages/9a/3e/ed6db5be21ce87955c0cbd3009f2803f59fa08df21b5df06862e2d8e2bdd/numpy-2.2.6-cp310-cp310-macosx_10_9_x86_64.whl", hash = "sha256:b412caa66f72040e6d268491a59f2c43bf03eb6c96dd8f0307829feb7fa2b6fb", size = 21165245 }, + { url = "https://files.pythonhosted.org/packages/22/c2/4b9221495b2a132cc9d2eb862e21d42a009f5a60e45fc44b00118c174bff/numpy-2.2.6-cp310-cp310-macosx_11_0_arm64.whl", hash = "sha256:8e41fd67c52b86603a91c1a505ebaef50b3314de0213461c7a6e99c9a3beff90", size = 14360048 }, + { url = "https://files.pythonhosted.org/packages/fd/77/dc2fcfc66943c6410e2bf598062f5959372735ffda175b39906d54f02349/numpy-2.2.6-cp310-cp310-macosx_14_0_arm64.whl", hash = "sha256:37e990a01ae6ec7fe7fa1c26c55ecb672dd98b19c3d0e1d1f326fa13cb38d163", size = 5340542 }, + { url = "https://files.pythonhosted.org/packages/7a/4f/1cb5fdc353a5f5cc7feb692db9b8ec2c3d6405453f982435efc52561df58/numpy-2.2.6-cp310-cp310-macosx_14_0_x86_64.whl", hash = "sha256:5a6429d4be8ca66d889b7cf70f536a397dc45ba6faeb5f8c5427935d9592e9cf", size = 6878301 }, + { url = "https://files.pythonhosted.org/packages/eb/17/96a3acd228cec142fcb8723bd3cc39c2a474f7dcf0a5d16731980bcafa95/numpy-2.2.6-cp310-cp310-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:efd28d4e9cd7d7a8d39074a4d44c63eda73401580c5c76acda2ce969e0a38e83", size = 14297320 }, + { url = "https://files.pythonhosted.org/packages/b4/63/3de6a34ad7ad6646ac7d2f55ebc6ad439dbbf9c4370017c50cf403fb19b5/numpy-2.2.6-cp310-cp310-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:fc7b73d02efb0e18c000e9ad8b83480dfcd5dfd11065997ed4c6747470ae8915", size = 16801050 }, + { url = "https://files.pythonhosted.org/packages/07/b6/89d837eddef52b3d0cec5c6ba0456c1bf1b9ef6a6672fc2b7873c3ec4e2e/numpy-2.2.6-cp310-cp310-musllinux_1_2_aarch64.whl", hash = "sha256:74d4531beb257d2c3f4b261bfb0fc09e0f9ebb8842d82a7b4209415896adc680", size = 15807034 }, + { url = "https://files.pythonhosted.org/packages/01/c8/dc6ae86e3c61cfec1f178e5c9f7858584049b6093f843bca541f94120920/numpy-2.2.6-cp310-cp310-musllinux_1_2_x86_64.whl", hash = "sha256:8fc377d995680230e83241d8a96def29f204b5782f371c532579b4f20607a289", size = 18614185 }, + { url = "https://files.pythonhosted.org/packages/5b/c5/0064b1b7e7c89137b471ccec1fd2282fceaae0ab3a9550f2568782d80357/numpy-2.2.6-cp310-cp310-win32.whl", hash = "sha256:b093dd74e50a8cba3e873868d9e93a85b78e0daf2e98c6797566ad8044e8363d", size = 6527149 }, + { url = "https://files.pythonhosted.org/packages/a3/dd/4b822569d6b96c39d1215dbae0582fd99954dcbcf0c1a13c61783feaca3f/numpy-2.2.6-cp310-cp310-win_amd64.whl", hash = "sha256:f0fd6321b839904e15c46e0d257fdd101dd7f530fe03fd6359c1ea63738703f3", size = 12904620 }, + { url = "https://files.pythonhosted.org/packages/da/a8/4f83e2aa666a9fbf56d6118faaaf5f1974d456b1823fda0a176eff722839/numpy-2.2.6-cp311-cp311-macosx_10_9_x86_64.whl", hash = "sha256:f9f1adb22318e121c5c69a09142811a201ef17ab257a1e66ca3025065b7f53ae", size = 21176963 }, + { url = "https://files.pythonhosted.org/packages/b3/2b/64e1affc7972decb74c9e29e5649fac940514910960ba25cd9af4488b66c/numpy-2.2.6-cp311-cp311-macosx_11_0_arm64.whl", hash = "sha256:c820a93b0255bc360f53eca31a0e676fd1101f673dda8da93454a12e23fc5f7a", size = 14406743 }, + { url = "https://files.pythonhosted.org/packages/4a/9f/0121e375000b5e50ffdd8b25bf78d8e1a5aa4cca3f185d41265198c7b834/numpy-2.2.6-cp311-cp311-macosx_14_0_arm64.whl", hash = "sha256:3d70692235e759f260c3d837193090014aebdf026dfd167834bcba43e30c2a42", size = 5352616 }, + { url = "https://files.pythonhosted.org/packages/31/0d/b48c405c91693635fbe2dcd7bc84a33a602add5f63286e024d3b6741411c/numpy-2.2.6-cp311-cp311-macosx_14_0_x86_64.whl", hash = "sha256:481b49095335f8eed42e39e8041327c05b0f6f4780488f61286ed3c01368d491", size = 6889579 }, + { url = "https://files.pythonhosted.org/packages/52/b8/7f0554d49b565d0171eab6e99001846882000883998e7b7d9f0d98b1f934/numpy-2.2.6-cp311-cp311-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:b64d8d4d17135e00c8e346e0a738deb17e754230d7e0810ac5012750bbd85a5a", size = 14312005 }, + { url = "https://files.pythonhosted.org/packages/b3/dd/2238b898e51bd6d389b7389ffb20d7f4c10066d80351187ec8e303a5a475/numpy-2.2.6-cp311-cp311-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:ba10f8411898fc418a521833e014a77d3ca01c15b0c6cdcce6a0d2897e6dbbdf", size = 16821570 }, + { url = "https://files.pythonhosted.org/packages/83/6c/44d0325722cf644f191042bf47eedad61c1e6df2432ed65cbe28509d404e/numpy-2.2.6-cp311-cp311-musllinux_1_2_aarch64.whl", hash = "sha256:bd48227a919f1bafbdda0583705e547892342c26fb127219d60a5c36882609d1", size = 15818548 }, + { url = "https://files.pythonhosted.org/packages/ae/9d/81e8216030ce66be25279098789b665d49ff19eef08bfa8cb96d4957f422/numpy-2.2.6-cp311-cp311-musllinux_1_2_x86_64.whl", hash = "sha256:9551a499bf125c1d4f9e250377c1ee2eddd02e01eac6644c080162c0c51778ab", size = 18620521 }, + { url = "https://files.pythonhosted.org/packages/6a/fd/e19617b9530b031db51b0926eed5345ce8ddc669bb3bc0044b23e275ebe8/numpy-2.2.6-cp311-cp311-win32.whl", hash = "sha256:0678000bb9ac1475cd454c6b8c799206af8107e310843532b04d49649c717a47", size = 6525866 }, + { url = "https://files.pythonhosted.org/packages/31/0a/f354fb7176b81747d870f7991dc763e157a934c717b67b58456bc63da3df/numpy-2.2.6-cp311-cp311-win_amd64.whl", hash = "sha256:e8213002e427c69c45a52bbd94163084025f533a55a59d6f9c5b820774ef3303", size = 12907455 }, + { url = "https://files.pythonhosted.org/packages/82/5d/c00588b6cf18e1da539b45d3598d3557084990dcc4331960c15ee776ee41/numpy-2.2.6-cp312-cp312-macosx_10_13_x86_64.whl", hash = "sha256:41c5a21f4a04fa86436124d388f6ed60a9343a6f767fced1a8a71c3fbca038ff", size = 20875348 }, + { url = "https://files.pythonhosted.org/packages/66/ee/560deadcdde6c2f90200450d5938f63a34b37e27ebff162810f716f6a230/numpy-2.2.6-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:de749064336d37e340f640b05f24e9e3dd678c57318c7289d222a8a2f543e90c", size = 14119362 }, + { url = "https://files.pythonhosted.org/packages/3c/65/4baa99f1c53b30adf0acd9a5519078871ddde8d2339dc5a7fde80d9d87da/numpy-2.2.6-cp312-cp312-macosx_14_0_arm64.whl", hash = "sha256:894b3a42502226a1cac872f840030665f33326fc3dac8e57c607905773cdcde3", size = 5084103 }, + { url = "https://files.pythonhosted.org/packages/cc/89/e5a34c071a0570cc40c9a54eb472d113eea6d002e9ae12bb3a8407fb912e/numpy-2.2.6-cp312-cp312-macosx_14_0_x86_64.whl", hash = "sha256:71594f7c51a18e728451bb50cc60a3ce4e6538822731b2933209a1f3614e9282", size = 6625382 }, + { url = "https://files.pythonhosted.org/packages/f8/35/8c80729f1ff76b3921d5c9487c7ac3de9b2a103b1cd05e905b3090513510/numpy-2.2.6-cp312-cp312-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:f2618db89be1b4e05f7a1a847a9c1c0abd63e63a1607d892dd54668dd92faf87", size = 14018462 }, + { url = "https://files.pythonhosted.org/packages/8c/3d/1e1db36cfd41f895d266b103df00ca5b3cbe965184df824dec5c08c6b803/numpy-2.2.6-cp312-cp312-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:fd83c01228a688733f1ded5201c678f0c53ecc1006ffbc404db9f7a899ac6249", size = 16527618 }, + { url = "https://files.pythonhosted.org/packages/61/c6/03ed30992602c85aa3cd95b9070a514f8b3c33e31124694438d88809ae36/numpy-2.2.6-cp312-cp312-musllinux_1_2_aarch64.whl", hash = "sha256:37c0ca431f82cd5fa716eca9506aefcabc247fb27ba69c5062a6d3ade8cf8f49", size = 15505511 }, + { url = "https://files.pythonhosted.org/packages/b7/25/5761d832a81df431e260719ec45de696414266613c9ee268394dd5ad8236/numpy-2.2.6-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:fe27749d33bb772c80dcd84ae7e8df2adc920ae8297400dabec45f0dedb3f6de", size = 18313783 }, + { url = "https://files.pythonhosted.org/packages/57/0a/72d5a3527c5ebffcd47bde9162c39fae1f90138c961e5296491ce778e682/numpy-2.2.6-cp312-cp312-win32.whl", hash = "sha256:4eeaae00d789f66c7a25ac5f34b71a7035bb474e679f410e5e1a94deb24cf2d4", size = 6246506 }, + { url = "https://files.pythonhosted.org/packages/36/fa/8c9210162ca1b88529ab76b41ba02d433fd54fecaf6feb70ef9f124683f1/numpy-2.2.6-cp312-cp312-win_amd64.whl", hash = "sha256:c1f9540be57940698ed329904db803cf7a402f3fc200bfe599334c9bd84a40b2", size = 12614190 }, + { url = "https://files.pythonhosted.org/packages/f9/5c/6657823f4f594f72b5471f1db1ab12e26e890bb2e41897522d134d2a3e81/numpy-2.2.6-cp313-cp313-macosx_10_13_x86_64.whl", hash = "sha256:0811bb762109d9708cca4d0b13c4f67146e3c3b7cf8d34018c722adb2d957c84", size = 20867828 }, + { url = "https://files.pythonhosted.org/packages/dc/9e/14520dc3dadf3c803473bd07e9b2bd1b69bc583cb2497b47000fed2fa92f/numpy-2.2.6-cp313-cp313-macosx_11_0_arm64.whl", hash = "sha256:287cc3162b6f01463ccd86be154f284d0893d2b3ed7292439ea97eafa8170e0b", size = 14143006 }, + { url = "https://files.pythonhosted.org/packages/4f/06/7e96c57d90bebdce9918412087fc22ca9851cceaf5567a45c1f404480e9e/numpy-2.2.6-cp313-cp313-macosx_14_0_arm64.whl", hash = "sha256:f1372f041402e37e5e633e586f62aa53de2eac8d98cbfb822806ce4bbefcb74d", size = 5076765 }, + { url = "https://files.pythonhosted.org/packages/73/ed/63d920c23b4289fdac96ddbdd6132e9427790977d5457cd132f18e76eae0/numpy-2.2.6-cp313-cp313-macosx_14_0_x86_64.whl", hash = "sha256:55a4d33fa519660d69614a9fad433be87e5252f4b03850642f88993f7b2ca566", size = 6617736 }, + { url = "https://files.pythonhosted.org/packages/85/c5/e19c8f99d83fd377ec8c7e0cf627a8049746da54afc24ef0a0cb73d5dfb5/numpy-2.2.6-cp313-cp313-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:f92729c95468a2f4f15e9bb94c432a9229d0d50de67304399627a943201baa2f", size = 14010719 }, + { url = "https://files.pythonhosted.org/packages/19/49/4df9123aafa7b539317bf6d342cb6d227e49f7a35b99c287a6109b13dd93/numpy-2.2.6-cp313-cp313-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:1bc23a79bfabc5d056d106f9befb8d50c31ced2fbc70eedb8155aec74a45798f", size = 16526072 }, + { url = "https://files.pythonhosted.org/packages/b2/6c/04b5f47f4f32f7c2b0e7260442a8cbcf8168b0e1a41ff1495da42f42a14f/numpy-2.2.6-cp313-cp313-musllinux_1_2_aarch64.whl", hash = "sha256:e3143e4451880bed956e706a3220b4e5cf6172ef05fcc397f6f36a550b1dd868", size = 15503213 }, + { url = "https://files.pythonhosted.org/packages/17/0a/5cd92e352c1307640d5b6fec1b2ffb06cd0dabe7d7b8227f97933d378422/numpy-2.2.6-cp313-cp313-musllinux_1_2_x86_64.whl", hash = "sha256:b4f13750ce79751586ae2eb824ba7e1e8dba64784086c98cdbbcc6a42112ce0d", size = 18316632 }, + { url = "https://files.pythonhosted.org/packages/f0/3b/5cba2b1d88760ef86596ad0f3d484b1cbff7c115ae2429678465057c5155/numpy-2.2.6-cp313-cp313-win32.whl", hash = "sha256:5beb72339d9d4fa36522fc63802f469b13cdbe4fdab4a288f0c441b74272ebfd", size = 6244532 }, + { url = "https://files.pythonhosted.org/packages/cb/3b/d58c12eafcb298d4e6d0d40216866ab15f59e55d148a5658bb3132311fcf/numpy-2.2.6-cp313-cp313-win_amd64.whl", hash = "sha256:b0544343a702fa80c95ad5d3d608ea3599dd54d4632df855e4c8d24eb6ecfa1c", size = 12610885 }, + { url = "https://files.pythonhosted.org/packages/6b/9e/4bf918b818e516322db999ac25d00c75788ddfd2d2ade4fa66f1f38097e1/numpy-2.2.6-cp313-cp313t-macosx_10_13_x86_64.whl", hash = "sha256:0bca768cd85ae743b2affdc762d617eddf3bcf8724435498a1e80132d04879e6", size = 20963467 }, + { url = "https://files.pythonhosted.org/packages/61/66/d2de6b291507517ff2e438e13ff7b1e2cdbdb7cb40b3ed475377aece69f9/numpy-2.2.6-cp313-cp313t-macosx_11_0_arm64.whl", hash = "sha256:fc0c5673685c508a142ca65209b4e79ed6740a4ed6b2267dbba90f34b0b3cfda", size = 14225144 }, + { url = "https://files.pythonhosted.org/packages/e4/25/480387655407ead912e28ba3a820bc69af9adf13bcbe40b299d454ec011f/numpy-2.2.6-cp313-cp313t-macosx_14_0_arm64.whl", hash = "sha256:5bd4fc3ac8926b3819797a7c0e2631eb889b4118a9898c84f585a54d475b7e40", size = 5200217 }, + { url = "https://files.pythonhosted.org/packages/aa/4a/6e313b5108f53dcbf3aca0c0f3e9c92f4c10ce57a0a721851f9785872895/numpy-2.2.6-cp313-cp313t-macosx_14_0_x86_64.whl", hash = "sha256:fee4236c876c4e8369388054d02d0e9bb84821feb1a64dd59e137e6511a551f8", size = 6712014 }, + { url = "https://files.pythonhosted.org/packages/b7/30/172c2d5c4be71fdf476e9de553443cf8e25feddbe185e0bd88b096915bcc/numpy-2.2.6-cp313-cp313t-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:e1dda9c7e08dc141e0247a5b8f49cf05984955246a327d4c48bda16821947b2f", size = 14077935 }, + { url = "https://files.pythonhosted.org/packages/12/fb/9e743f8d4e4d3c710902cf87af3512082ae3d43b945d5d16563f26ec251d/numpy-2.2.6-cp313-cp313t-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:f447e6acb680fd307f40d3da4852208af94afdfab89cf850986c3ca00562f4fa", size = 16600122 }, + { url = "https://files.pythonhosted.org/packages/12/75/ee20da0e58d3a66f204f38916757e01e33a9737d0b22373b3eb5a27358f9/numpy-2.2.6-cp313-cp313t-musllinux_1_2_aarch64.whl", hash = "sha256:389d771b1623ec92636b0786bc4ae56abafad4a4c513d36a55dce14bd9ce8571", size = 15586143 }, + { url = "https://files.pythonhosted.org/packages/76/95/bef5b37f29fc5e739947e9ce5179ad402875633308504a52d188302319c8/numpy-2.2.6-cp313-cp313t-musllinux_1_2_x86_64.whl", hash = "sha256:8e9ace4a37db23421249ed236fdcdd457d671e25146786dfc96835cd951aa7c1", size = 18385260 }, + { url = "https://files.pythonhosted.org/packages/09/04/f2f83279d287407cf36a7a8053a5abe7be3622a4363337338f2585e4afda/numpy-2.2.6-cp313-cp313t-win32.whl", hash = "sha256:038613e9fb8c72b0a41f025a7e4c3f0b7a1b5d768ece4796b674c8f3fe13efff", size = 6377225 }, + { url = "https://files.pythonhosted.org/packages/67/0e/35082d13c09c02c011cf21570543d202ad929d961c02a147493cb0c2bdf5/numpy-2.2.6-cp313-cp313t-win_amd64.whl", hash = "sha256:6031dd6dfecc0cf9f668681a37648373bddd6421fff6c66ec1624eed0180ee06", size = 12771374 }, + { url = "https://files.pythonhosted.org/packages/9e/3b/d94a75f4dbf1ef5d321523ecac21ef23a3cd2ac8b78ae2aac40873590229/numpy-2.2.6-pp310-pypy310_pp73-macosx_10_15_x86_64.whl", hash = "sha256:0b605b275d7bd0c640cad4e5d30fa701a8d59302e127e5f79138ad62762c3e3d", size = 21040391 }, + { url = "https://files.pythonhosted.org/packages/17/f4/09b2fa1b58f0fb4f7c7963a1649c64c4d315752240377ed74d9cd878f7b5/numpy-2.2.6-pp310-pypy310_pp73-macosx_14_0_x86_64.whl", hash = "sha256:7befc596a7dc9da8a337f79802ee8adb30a552a94f792b9c9d18c840055907db", size = 6786754 }, + { url = "https://files.pythonhosted.org/packages/af/30/feba75f143bdc868a1cc3f44ccfa6c4b9ec522b36458e738cd00f67b573f/numpy-2.2.6-pp310-pypy310_pp73-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:ce47521a4754c8f4593837384bd3424880629f718d87c5d44f8ed763edd63543", size = 16643476 }, + { url = "https://files.pythonhosted.org/packages/37/48/ac2a9584402fb6c0cd5b5d1a91dcf176b15760130dd386bbafdbfe3640bf/numpy-2.2.6-pp310-pypy310_pp73-win_amd64.whl", hash = "sha256:d042d24c90c41b54fd506da306759e06e568864df8ec17ccc17e9e884634fd00", size = 12812666 }, +] + +[[package]] +name = "numpy" +version = "2.3.1" +source = { registry = "https://pypi.org/simple" } +resolution-markers = [ + "python_full_version >= '3.13'", + "python_full_version == '3.12.*'", + "python_full_version == '3.11.*'", +] +sdist = { url = "https://files.pythonhosted.org/packages/2e/19/d7c972dfe90a353dbd3efbbe1d14a5951de80c99c9dc1b93cd998d51dc0f/numpy-2.3.1.tar.gz", hash = "sha256:1ec9ae20a4226da374362cca3c62cd753faf2f951440b0e3b98e93c235441d2b", size = 20390372 } +wheels = [ + { url = "https://files.pythonhosted.org/packages/b0/c7/87c64d7ab426156530676000c94784ef55676df2f13b2796f97722464124/numpy-2.3.1-cp311-cp311-macosx_10_9_x86_64.whl", hash = "sha256:6ea9e48336a402551f52cd8f593343699003d2353daa4b72ce8d34f66b722070", size = 21199346 }, + { url = "https://files.pythonhosted.org/packages/58/0e/0966c2f44beeac12af8d836e5b5f826a407cf34c45cb73ddcdfce9f5960b/numpy-2.3.1-cp311-cp311-macosx_11_0_arm64.whl", hash = "sha256:5ccb7336eaf0e77c1635b232c141846493a588ec9ea777a7c24d7166bb8533ae", size = 14361143 }, + { url = "https://files.pythonhosted.org/packages/7d/31/6e35a247acb1bfc19226791dfc7d4c30002cd4e620e11e58b0ddf836fe52/numpy-2.3.1-cp311-cp311-macosx_14_0_arm64.whl", hash = "sha256:0bb3a4a61e1d327e035275d2a993c96fa786e4913aa089843e6a2d9dd205c66a", size = 5378989 }, + { url = "https://files.pythonhosted.org/packages/b0/25/93b621219bb6f5a2d4e713a824522c69ab1f06a57cd571cda70e2e31af44/numpy-2.3.1-cp311-cp311-macosx_14_0_x86_64.whl", hash = "sha256:e344eb79dab01f1e838ebb67aab09965fb271d6da6b00adda26328ac27d4a66e", size = 6912890 }, + { url = "https://files.pythonhosted.org/packages/ef/60/6b06ed98d11fb32e27fb59468b42383f3877146d3ee639f733776b6ac596/numpy-2.3.1-cp311-cp311-manylinux_2_28_aarch64.whl", hash = "sha256:467db865b392168ceb1ef1ffa6f5a86e62468c43e0cfb4ab6da667ede10e58db", size = 14569032 }, + { url = "https://files.pythonhosted.org/packages/75/c9/9bec03675192077467a9c7c2bdd1f2e922bd01d3a69b15c3a0fdcd8548f6/numpy-2.3.1-cp311-cp311-manylinux_2_28_x86_64.whl", hash = "sha256:afed2ce4a84f6b0fc6c1ce734ff368cbf5a5e24e8954a338f3bdffa0718adffb", size = 16930354 }, + { url = "https://files.pythonhosted.org/packages/6a/e2/5756a00cabcf50a3f527a0c968b2b4881c62b1379223931853114fa04cda/numpy-2.3.1-cp311-cp311-musllinux_1_2_aarch64.whl", hash = "sha256:0025048b3c1557a20bc80d06fdeb8cc7fc193721484cca82b2cfa072fec71a93", size = 15879605 }, + { url = "https://files.pythonhosted.org/packages/ff/86/a471f65f0a86f1ca62dcc90b9fa46174dd48f50214e5446bc16a775646c5/numpy-2.3.1-cp311-cp311-musllinux_1_2_x86_64.whl", hash = "sha256:a5ee121b60aa509679b682819c602579e1df14a5b07fe95671c8849aad8f2115", size = 18666994 }, + { url = "https://files.pythonhosted.org/packages/43/a6/482a53e469b32be6500aaf61cfafd1de7a0b0d484babf679209c3298852e/numpy-2.3.1-cp311-cp311-win32.whl", hash = "sha256:a8b740f5579ae4585831b3cf0e3b0425c667274f82a484866d2adf9570539369", size = 6603672 }, + { url = "https://files.pythonhosted.org/packages/6b/fb/bb613f4122c310a13ec67585c70e14b03bfc7ebabd24f4d5138b97371d7c/numpy-2.3.1-cp311-cp311-win_amd64.whl", hash = "sha256:d4580adadc53311b163444f877e0789f1c8861e2698f6b2a4ca852fda154f3ff", size = 13024015 }, + { url = "https://files.pythonhosted.org/packages/51/58/2d842825af9a0c041aca246dc92eb725e1bc5e1c9ac89712625db0c4e11c/numpy-2.3.1-cp311-cp311-win_arm64.whl", hash = "sha256:ec0bdafa906f95adc9a0c6f26a4871fa753f25caaa0e032578a30457bff0af6a", size = 10456989 }, + { url = "https://files.pythonhosted.org/packages/c6/56/71ad5022e2f63cfe0ca93559403d0edef14aea70a841d640bd13cdba578e/numpy-2.3.1-cp312-cp312-macosx_10_13_x86_64.whl", hash = "sha256:2959d8f268f3d8ee402b04a9ec4bb7604555aeacf78b360dc4ec27f1d508177d", size = 20896664 }, + { url = "https://files.pythonhosted.org/packages/25/65/2db52ba049813670f7f987cc5db6dac9be7cd95e923cc6832b3d32d87cef/numpy-2.3.1-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:762e0c0c6b56bdedfef9a8e1d4538556438288c4276901ea008ae44091954e29", size = 14131078 }, + { url = "https://files.pythonhosted.org/packages/57/dd/28fa3c17b0e751047ac928c1e1b6990238faad76e9b147e585b573d9d1bd/numpy-2.3.1-cp312-cp312-macosx_14_0_arm64.whl", hash = "sha256:867ef172a0976aaa1f1d1b63cf2090de8b636a7674607d514505fb7276ab08fc", size = 5112554 }, + { url = "https://files.pythonhosted.org/packages/c9/fc/84ea0cba8e760c4644b708b6819d91784c290288c27aca916115e3311d17/numpy-2.3.1-cp312-cp312-macosx_14_0_x86_64.whl", hash = "sha256:4e602e1b8682c2b833af89ba641ad4176053aaa50f5cacda1a27004352dde943", size = 6646560 }, + { url = "https://files.pythonhosted.org/packages/61/b2/512b0c2ddec985ad1e496b0bd853eeb572315c0f07cd6997473ced8f15e2/numpy-2.3.1-cp312-cp312-manylinux_2_28_aarch64.whl", hash = "sha256:8e333040d069eba1652fb08962ec5b76af7f2c7bce1df7e1418c8055cf776f25", size = 14260638 }, + { url = "https://files.pythonhosted.org/packages/6e/45/c51cb248e679a6c6ab14b7a8e3ead3f4a3fe7425fc7a6f98b3f147bec532/numpy-2.3.1-cp312-cp312-manylinux_2_28_x86_64.whl", hash = "sha256:e7cbf5a5eafd8d230a3ce356d892512185230e4781a361229bd902ff403bc660", size = 16632729 }, + { url = "https://files.pythonhosted.org/packages/e4/ff/feb4be2e5c09a3da161b412019caf47183099cbea1132fd98061808c2df2/numpy-2.3.1-cp312-cp312-musllinux_1_2_aarch64.whl", hash = "sha256:5f1b8f26d1086835f442286c1d9b64bb3974b0b1e41bb105358fd07d20872952", size = 15565330 }, + { url = "https://files.pythonhosted.org/packages/bc/6d/ceafe87587101e9ab0d370e4f6e5f3f3a85b9a697f2318738e5e7e176ce3/numpy-2.3.1-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:ee8340cb48c9b7a5899d1149eece41ca535513a9698098edbade2a8e7a84da77", size = 18361734 }, + { url = "https://files.pythonhosted.org/packages/2b/19/0fb49a3ea088be691f040c9bf1817e4669a339d6e98579f91859b902c636/numpy-2.3.1-cp312-cp312-win32.whl", hash = "sha256:e772dda20a6002ef7061713dc1e2585bc1b534e7909b2030b5a46dae8ff077ab", size = 6320411 }, + { url = "https://files.pythonhosted.org/packages/b1/3e/e28f4c1dd9e042eb57a3eb652f200225e311b608632bc727ae378623d4f8/numpy-2.3.1-cp312-cp312-win_amd64.whl", hash = "sha256:cfecc7822543abdea6de08758091da655ea2210b8ffa1faf116b940693d3df76", size = 12734973 }, + { url = "https://files.pythonhosted.org/packages/04/a8/8a5e9079dc722acf53522b8f8842e79541ea81835e9b5483388701421073/numpy-2.3.1-cp312-cp312-win_arm64.whl", hash = "sha256:7be91b2239af2658653c5bb6f1b8bccafaf08226a258caf78ce44710a0160d30", size = 10191491 }, + { url = "https://files.pythonhosted.org/packages/d4/bd/35ad97006d8abff8631293f8ea6adf07b0108ce6fec68da3c3fcca1197f2/numpy-2.3.1-cp313-cp313-macosx_10_13_x86_64.whl", hash = "sha256:25a1992b0a3fdcdaec9f552ef10d8103186f5397ab45e2d25f8ac51b1a6b97e8", size = 20889381 }, + { url = "https://files.pythonhosted.org/packages/f1/4f/df5923874d8095b6062495b39729178eef4a922119cee32a12ee1bd4664c/numpy-2.3.1-cp313-cp313-macosx_11_0_arm64.whl", hash = "sha256:7dea630156d39b02a63c18f508f85010230409db5b2927ba59c8ba4ab3e8272e", size = 14152726 }, + { url = "https://files.pythonhosted.org/packages/8c/0f/a1f269b125806212a876f7efb049b06c6f8772cf0121139f97774cd95626/numpy-2.3.1-cp313-cp313-macosx_14_0_arm64.whl", hash = "sha256:bada6058dd886061f10ea15f230ccf7dfff40572e99fef440a4a857c8728c9c0", size = 5105145 }, + { url = "https://files.pythonhosted.org/packages/6d/63/a7f7fd5f375b0361682f6ffbf686787e82b7bbd561268e4f30afad2bb3c0/numpy-2.3.1-cp313-cp313-macosx_14_0_x86_64.whl", hash = "sha256:a894f3816eb17b29e4783e5873f92faf55b710c2519e5c351767c51f79d8526d", size = 6639409 }, + { url = "https://files.pythonhosted.org/packages/bf/0d/1854a4121af895aab383f4aa233748f1df4671ef331d898e32426756a8a6/numpy-2.3.1-cp313-cp313-manylinux_2_28_aarch64.whl", hash = "sha256:18703df6c4a4fee55fd3d6e5a253d01c5d33a295409b03fda0c86b3ca2ff41a1", size = 14257630 }, + { url = "https://files.pythonhosted.org/packages/50/30/af1b277b443f2fb08acf1c55ce9d68ee540043f158630d62cef012750f9f/numpy-2.3.1-cp313-cp313-manylinux_2_28_x86_64.whl", hash = "sha256:5902660491bd7a48b2ec16c23ccb9124b8abfd9583c5fdfa123fe6b421e03de1", size = 16627546 }, + { url = "https://files.pythonhosted.org/packages/6e/ec/3b68220c277e463095342d254c61be8144c31208db18d3fd8ef02712bcd6/numpy-2.3.1-cp313-cp313-musllinux_1_2_aarch64.whl", hash = "sha256:36890eb9e9d2081137bd78d29050ba63b8dab95dff7912eadf1185e80074b2a0", size = 15562538 }, + { url = "https://files.pythonhosted.org/packages/77/2b/4014f2bcc4404484021c74d4c5ee8eb3de7e3f7ac75f06672f8dcf85140a/numpy-2.3.1-cp313-cp313-musllinux_1_2_x86_64.whl", hash = "sha256:a780033466159c2270531e2b8ac063704592a0bc62ec4a1b991c7c40705eb0e8", size = 18360327 }, + { url = "https://files.pythonhosted.org/packages/40/8d/2ddd6c9b30fcf920837b8672f6c65590c7d92e43084c25fc65edc22e93ca/numpy-2.3.1-cp313-cp313-win32.whl", hash = "sha256:39bff12c076812595c3a306f22bfe49919c5513aa1e0e70fac756a0be7c2a2b8", size = 6312330 }, + { url = "https://files.pythonhosted.org/packages/dd/c8/beaba449925988d415efccb45bf977ff8327a02f655090627318f6398c7b/numpy-2.3.1-cp313-cp313-win_amd64.whl", hash = "sha256:8d5ee6eec45f08ce507a6570e06f2f879b374a552087a4179ea7838edbcbfa42", size = 12731565 }, + { url = "https://files.pythonhosted.org/packages/0b/c3/5c0c575d7ec78c1126998071f58facfc124006635da75b090805e642c62e/numpy-2.3.1-cp313-cp313-win_arm64.whl", hash = "sha256:0c4d9e0a8368db90f93bd192bfa771ace63137c3488d198ee21dfb8e7771916e", size = 10190262 }, + { url = "https://files.pythonhosted.org/packages/ea/19/a029cd335cf72f79d2644dcfc22d90f09caa86265cbbde3b5702ccef6890/numpy-2.3.1-cp313-cp313t-macosx_10_13_x86_64.whl", hash = "sha256:b0b5397374f32ec0649dd98c652a1798192042e715df918c20672c62fb52d4b8", size = 20987593 }, + { url = "https://files.pythonhosted.org/packages/25/91/8ea8894406209107d9ce19b66314194675d31761fe2cb3c84fe2eeae2f37/numpy-2.3.1-cp313-cp313t-macosx_11_0_arm64.whl", hash = "sha256:c5bdf2015ccfcee8253fb8be695516ac4457c743473a43290fd36eba6a1777eb", size = 14300523 }, + { url = "https://files.pythonhosted.org/packages/a6/7f/06187b0066eefc9e7ce77d5f2ddb4e314a55220ad62dd0bfc9f2c44bac14/numpy-2.3.1-cp313-cp313t-macosx_14_0_arm64.whl", hash = "sha256:d70f20df7f08b90a2062c1f07737dd340adccf2068d0f1b9b3d56e2038979fee", size = 5227993 }, + { url = "https://files.pythonhosted.org/packages/e8/ec/a926c293c605fa75e9cfb09f1e4840098ed46d2edaa6e2152ee35dc01ed3/numpy-2.3.1-cp313-cp313t-macosx_14_0_x86_64.whl", hash = "sha256:2fb86b7e58f9ac50e1e9dd1290154107e47d1eef23a0ae9145ded06ea606f992", size = 6736652 }, + { url = "https://files.pythonhosted.org/packages/e3/62/d68e52fb6fde5586650d4c0ce0b05ff3a48ad4df4ffd1b8866479d1d671d/numpy-2.3.1-cp313-cp313t-manylinux_2_28_aarch64.whl", hash = "sha256:23ab05b2d241f76cb883ce8b9a93a680752fbfcbd51c50eff0b88b979e471d8c", size = 14331561 }, + { url = "https://files.pythonhosted.org/packages/fc/ec/b74d3f2430960044bdad6900d9f5edc2dc0fb8bf5a0be0f65287bf2cbe27/numpy-2.3.1-cp313-cp313t-manylinux_2_28_x86_64.whl", hash = "sha256:ce2ce9e5de4703a673e705183f64fd5da5bf36e7beddcb63a25ee2286e71ca48", size = 16693349 }, + { url = "https://files.pythonhosted.org/packages/0d/15/def96774b9d7eb198ddadfcbd20281b20ebb510580419197e225f5c55c3e/numpy-2.3.1-cp313-cp313t-musllinux_1_2_aarch64.whl", hash = "sha256:c4913079974eeb5c16ccfd2b1f09354b8fed7e0d6f2cab933104a09a6419b1ee", size = 15642053 }, + { url = "https://files.pythonhosted.org/packages/2b/57/c3203974762a759540c6ae71d0ea2341c1fa41d84e4971a8e76d7141678a/numpy-2.3.1-cp313-cp313t-musllinux_1_2_x86_64.whl", hash = "sha256:010ce9b4f00d5c036053ca684c77441f2f2c934fd23bee058b4d6f196efd8280", size = 18434184 }, + { url = "https://files.pythonhosted.org/packages/22/8a/ccdf201457ed8ac6245187850aff4ca56a79edbea4829f4e9f14d46fa9a5/numpy-2.3.1-cp313-cp313t-win32.whl", hash = "sha256:6269b9edfe32912584ec496d91b00b6d34282ca1d07eb10e82dfc780907d6c2e", size = 6440678 }, + { url = "https://files.pythonhosted.org/packages/f1/7e/7f431d8bd8eb7e03d79294aed238b1b0b174b3148570d03a8a8a8f6a0da9/numpy-2.3.1-cp313-cp313t-win_amd64.whl", hash = "sha256:2a809637460e88a113e186e87f228d74ae2852a2e0c44de275263376f17b5bdc", size = 12870697 }, + { url = "https://files.pythonhosted.org/packages/d4/ca/af82bf0fad4c3e573c6930ed743b5308492ff19917c7caaf2f9b6f9e2e98/numpy-2.3.1-cp313-cp313t-win_arm64.whl", hash = "sha256:eccb9a159db9aed60800187bc47a6d3451553f0e1b08b068d8b277ddfbb9b244", size = 10260376 }, + { url = "https://files.pythonhosted.org/packages/e8/34/facc13b9b42ddca30498fc51f7f73c3d0f2be179943a4b4da8686e259740/numpy-2.3.1-pp311-pypy311_pp73-macosx_10_15_x86_64.whl", hash = "sha256:ad506d4b09e684394c42c966ec1527f6ebc25da7f4da4b1b056606ffe446b8a3", size = 21070637 }, + { url = "https://files.pythonhosted.org/packages/65/b6/41b705d9dbae04649b529fc9bd3387664c3281c7cd78b404a4efe73dcc45/numpy-2.3.1-pp311-pypy311_pp73-macosx_14_0_arm64.whl", hash = "sha256:ebb8603d45bc86bbd5edb0d63e52c5fd9e7945d3a503b77e486bd88dde67a19b", size = 5304087 }, + { url = "https://files.pythonhosted.org/packages/7a/b4/fe3ac1902bff7a4934a22d49e1c9d71a623204d654d4cc43c6e8fe337fcb/numpy-2.3.1-pp311-pypy311_pp73-macosx_14_0_x86_64.whl", hash = "sha256:15aa4c392ac396e2ad3d0a2680c0f0dee420f9fed14eef09bdb9450ee6dcb7b7", size = 6817588 }, + { url = "https://files.pythonhosted.org/packages/ae/ee/89bedf69c36ace1ac8f59e97811c1f5031e179a37e4821c3a230bf750142/numpy-2.3.1-pp311-pypy311_pp73-manylinux_2_28_aarch64.whl", hash = "sha256:c6e0bf9d1a2f50d2b65a7cf56db37c095af17b59f6c132396f7c6d5dd76484df", size = 14399010 }, + { url = "https://files.pythonhosted.org/packages/15/08/e00e7070ede29b2b176165eba18d6f9784d5349be3c0c1218338e79c27fd/numpy-2.3.1-pp311-pypy311_pp73-manylinux_2_28_x86_64.whl", hash = "sha256:eabd7e8740d494ce2b4ea0ff05afa1b7b291e978c0ae075487c51e8bd93c0c68", size = 16752042 }, + { url = "https://files.pythonhosted.org/packages/48/6b/1c6b515a83d5564b1698a61efa245727c8feecf308f4091f565988519d20/numpy-2.3.1-pp311-pypy311_pp73-win_amd64.whl", hash = "sha256:e610832418a2bc09d974cc9fecebfa51e9532d6190223bc5ef6a7402ebf3b5cb", size = 12927246 }, +] + +[[package]] +name = "opt-einsum" +version = "3.4.0" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/8c/b9/2ac072041e899a52f20cf9510850ff58295003aa75525e58343591b0cbfb/opt_einsum-3.4.0.tar.gz", hash = "sha256:96ca72f1b886d148241348783498194c577fa30a8faac108586b14f1ba4473ac", size = 63004 } +wheels = [ + { url = "https://files.pythonhosted.org/packages/23/cd/066e86230ae37ed0be70aae89aabf03ca8d9f39c8aea0dec8029455b5540/opt_einsum-3.4.0-py3-none-any.whl", hash = "sha256:69bb92469f86a1565195ece4ac0323943e83477171b91d24c35afe028a90d7cd", size = 71932 }, +] + +[[package]] +name = "optax" +version = "0.2.5" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "absl-py" }, + { name = "chex" }, + { name = "jax" }, + { name = "jaxlib" }, + { name = "numpy", version = "2.2.6", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version < '3.11'" }, + { name = "numpy", version = "2.3.1", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version >= '3.11'" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/c0/75/1e011953c48be502d4d84fa8458e91be7c6f983002511669bddd7b1a065f/optax-0.2.5.tar.gz", hash = "sha256:b2e38c7aea376186deae758ba7a258e6ef760c6f6131e9e11bc561c65386d594", size = 258548 } +wheels = [ + { url = "https://files.pythonhosted.org/packages/b9/33/f86091c706db1a5459f501830241afff2ecab3532725c188ea57be6e54de/optax-0.2.5-py3-none-any.whl", hash = "sha256:966deae936207f268ac8f564d8ed228d645ac1aaddefbbf194096d2299b24ba8", size = 354324 }, +] + +[[package]] +name = "orbax-checkpoint" +version = "0.11.18" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "absl-py" }, + { name = "etils", extra = ["epath", "epy"] }, + { name = "humanize" }, + { name = "jax" }, + { name = "msgpack" }, + { name = "nest-asyncio" }, + { name = "numpy", version = "2.2.6", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version < '3.11'" }, + { name = "numpy", version = "2.3.1", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version >= '3.11'" }, + { name = "protobuf" }, + { name = "pyyaml" }, + { name = "simplejson" }, + { name = "tensorstore" }, + { name = "typing-extensions" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/55/02/3a2d2d862931a96c4208756bfe8de1f9b65723588be757e5074beab33c53/orbax_checkpoint-0.11.18.tar.gz", hash = "sha256:de7c3826550fc5fed1eb362be30e4b83125cb32bb86de951652bb3c4f9337415", size = 340670 } +wheels = [ + { url = "https://files.pythonhosted.org/packages/cd/2d/2fc1b216df08d775b860c20683dd8e8d2c8c2930bf8d2dfbe52ebc2fdf46/orbax_checkpoint-0.11.18-py3-none-any.whl", hash = "sha256:9f2f1ebc0305d75593e5720aeb8a82ee42c68f436ef98840411b2804136f7034", size = 479958 }, +] + +[[package]] +name = "packaging" +version = "25.0" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/a1/d4/1fc4078c65507b51b96ca8f8c3ba19e6a61c8253c72794544580a7b6c24d/packaging-25.0.tar.gz", hash = "sha256:d443872c98d677bf60f6a1f2f8c1cb748e8fe762d2bf9d3148b5599295b0fc4f", size = 165727 } +wheels = [ + { url = "https://files.pythonhosted.org/packages/20/12/38679034af332785aac8774540895e234f4d07f7545804097de4b666afd8/packaging-25.0-py3-none-any.whl", hash = "sha256:29572ef2b1f17581046b3a2227d5c611fb25ec70ca1ba8554b24b0e69331a484", size = 66469 }, +] + +[[package]] +name = "paginate" +version = "0.5.7" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/ec/46/68dde5b6bc00c1296ec6466ab27dddede6aec9af1b99090e1107091b3b84/paginate-0.5.7.tar.gz", hash = "sha256:22bd083ab41e1a8b4f3690544afb2c60c25e5c9a63a30fa2f483f6c60c8e5945", size = 19252 } +wheels = [ + { url = "https://files.pythonhosted.org/packages/90/96/04b8e52da071d28f5e21a805b19cb9390aa17a47462ac87f5e2696b9566d/paginate-0.5.7-py2.py3-none-any.whl", hash = "sha256:b885e2af73abcf01d9559fd5216b57ef722f8c42affbb63942377668e35c7591", size = 13746 }, +] + +[[package]] +name = "pathspec" +version = "0.12.1" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/ca/bc/f35b8446f4531a7cb215605d100cd88b7ac6f44ab3fc94870c120ab3adbf/pathspec-0.12.1.tar.gz", hash = "sha256:a482d51503a1ab33b1c67a6c3813a26953dbdc71c31dacaef9a838c4e29f5712", size = 51043 } +wheels = [ + { url = "https://files.pythonhosted.org/packages/cc/20/ff623b09d963f88bfde16306a54e12ee5ea43e9b597108672ff3a408aad6/pathspec-0.12.1-py3-none-any.whl", hash = "sha256:a0d503e138a4c123b27490a4f7beda6a01c6f288df0e4a8b79c7eb0dc7b4cc08", size = 31191 }, +] + +[[package]] +name = "platformdirs" +version = "4.3.8" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/fe/8b/3c73abc9c759ecd3f1f7ceff6685840859e8070c4d947c93fae71f6a0bf2/platformdirs-4.3.8.tar.gz", hash = "sha256:3d512d96e16bcb959a814c9f348431070822a6496326a4be0911c40b5a74c2bc", size = 21362 } +wheels = [ + { url = "https://files.pythonhosted.org/packages/fe/39/979e8e21520d4e47a0bbe349e2713c0aac6f3d853d0e5b34d76206c439aa/platformdirs-4.3.8-py3-none-any.whl", hash = "sha256:ff7059bb7eb1179e2685604f4aaf157cfd9535242bd23742eadc3c13542139b4", size = 18567 }, +] + +[[package]] +name = "pluggy" +version = "1.6.0" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/f9/e2/3e91f31a7d2b083fe6ef3fa267035b518369d9511ffab804f839851d2779/pluggy-1.6.0.tar.gz", hash = "sha256:7dcc130b76258d33b90f61b658791dede3486c3e6bfb003ee5c9bfb396dd22f3", size = 69412 } +wheels = [ + { url = "https://files.pythonhosted.org/packages/54/20/4d324d65cc6d9205fabedc306948156824eb9f0ee1633355a8f7ec5c66bf/pluggy-1.6.0-py3-none-any.whl", hash = "sha256:e920276dd6813095e9377c0bc5566d94c932c33b27a3e3945d8389c374dd4746", size = 20538 }, +] + +[[package]] +name = "pre-commit" +version = "4.2.0" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "cfgv" }, + { name = "identify" }, + { name = "nodeenv" }, + { name = "pyyaml" }, + { name = "virtualenv" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/08/39/679ca9b26c7bb2999ff122d50faa301e49af82ca9c066ec061cfbc0c6784/pre_commit-4.2.0.tar.gz", hash = "sha256:601283b9757afd87d40c4c4a9b2b5de9637a8ea02eaff7adc2d0fb4e04841146", size = 193424 } +wheels = [ + { url = "https://files.pythonhosted.org/packages/88/74/a88bf1b1efeae488a0c0b7bdf71429c313722d1fc0f377537fbe554e6180/pre_commit-4.2.0-py2.py3-none-any.whl", hash = "sha256:a009ca7205f1eb497d10b845e52c838a98b6cdd2102a6c8e4540e94ee75c58bd", size = 220707 }, +] + +[[package]] +name = "protobuf" +version = "6.31.1" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/52/f3/b9655a711b32c19720253f6f06326faf90580834e2e83f840472d752bc8b/protobuf-6.31.1.tar.gz", hash = "sha256:d8cac4c982f0b957a4dc73a80e2ea24fab08e679c0de9deb835f4a12d69aca9a", size = 441797 } +wheels = [ + { url = "https://files.pythonhosted.org/packages/f3/6f/6ab8e4bf962fd5570d3deaa2d5c38f0a363f57b4501047b5ebeb83ab1125/protobuf-6.31.1-cp310-abi3-win32.whl", hash = "sha256:7fa17d5a29c2e04b7d90e5e32388b8bfd0e7107cd8e616feef7ed3fa6bdab5c9", size = 423603 }, + { url = "https://files.pythonhosted.org/packages/44/3a/b15c4347dd4bf3a1b0ee882f384623e2063bb5cf9fa9d57990a4f7df2fb6/protobuf-6.31.1-cp310-abi3-win_amd64.whl", hash = "sha256:426f59d2964864a1a366254fa703b8632dcec0790d8862d30034d8245e1cd447", size = 435283 }, + { url = "https://files.pythonhosted.org/packages/6a/c9/b9689a2a250264a84e66c46d8862ba788ee7a641cdca39bccf64f59284b7/protobuf-6.31.1-cp39-abi3-macosx_10_9_universal2.whl", hash = "sha256:6f1227473dc43d44ed644425268eb7c2e488ae245d51c6866d19fe158e207402", size = 425604 }, + { url = "https://files.pythonhosted.org/packages/76/a1/7a5a94032c83375e4fe7e7f56e3976ea6ac90c5e85fac8576409e25c39c3/protobuf-6.31.1-cp39-abi3-manylinux2014_aarch64.whl", hash = "sha256:a40fc12b84c154884d7d4c4ebd675d5b3b5283e155f324049ae396b95ddebc39", size = 322115 }, + { url = "https://files.pythonhosted.org/packages/fa/b1/b59d405d64d31999244643d88c45c8241c58f17cc887e73bcb90602327f8/protobuf-6.31.1-cp39-abi3-manylinux2014_x86_64.whl", hash = "sha256:4ee898bf66f7a8b0bd21bce523814e6fbd8c6add948045ce958b73af7e8878c6", size = 321070 }, + { url = "https://files.pythonhosted.org/packages/f7/af/ab3c51ab7507a7325e98ffe691d9495ee3d3aa5f589afad65ec920d39821/protobuf-6.31.1-py3-none-any.whl", hash = "sha256:720a6c7e6b77288b85063569baae8536671b39f15cc22037ec7045658d80489e", size = 168724 }, +] + +[[package]] +name = "pygments" +version = "2.19.2" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/b0/77/a5b8c569bf593b0140bde72ea885a803b82086995367bf2037de0159d924/pygments-2.19.2.tar.gz", hash = "sha256:636cb2477cec7f8952536970bc533bc43743542f70392ae026374600add5b887", size = 4968631 } +wheels = [ + { url = "https://files.pythonhosted.org/packages/c7/21/705964c7812476f378728bdf590ca4b771ec72385c533964653c68e86bdc/pygments-2.19.2-py3-none-any.whl", hash = "sha256:86540386c03d588bb81d44bc3928634ff26449851e99741617ecb9037ee5ec0b", size = 1225217 }, +] + +[[package]] +name = "pymdown-extensions" +version = "10.16" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "markdown" }, + { name = "pyyaml" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/1a/0a/c06b542ac108bfc73200677309cd9188a3a01b127a63f20cadc18d873d88/pymdown_extensions-10.16.tar.gz", hash = "sha256:71dac4fca63fabeffd3eb9038b756161a33ec6e8d230853d3cecf562155ab3de", size = 853197 } +wheels = [ + { url = "https://files.pythonhosted.org/packages/98/d4/10bb14004d3c792811e05e21b5e5dcae805aacb739bd12a0540967b99592/pymdown_extensions-10.16-py3-none-any.whl", hash = "sha256:f5dd064a4db588cb2d95229fc4ee63a1b16cc8b4d0e6145c0899ed8723da1df2", size = 266143 }, +] + +[[package]] +name = "pytest" +version = "8.4.1" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "colorama", marker = "sys_platform == 'win32'" }, + { name = "exceptiongroup", marker = "python_full_version < '3.11'" }, + { name = "iniconfig" }, + { name = "packaging" }, + { name = "pluggy" }, + { name = "pygments" }, + { name = "tomli", marker = "python_full_version < '3.11'" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/08/ba/45911d754e8eba3d5a841a5ce61a65a685ff1798421ac054f85aa8747dfb/pytest-8.4.1.tar.gz", hash = "sha256:7c67fd69174877359ed9371ec3af8a3d2b04741818c51e5e99cc1742251fa93c", size = 1517714 } +wheels = [ + { url = "https://files.pythonhosted.org/packages/29/16/c8a903f4c4dffe7a12843191437d7cd8e32751d5de349d45d3fe69544e87/pytest-8.4.1-py3-none-any.whl", hash = "sha256:539c70ba6fcead8e78eebbf1115e8b589e7565830d7d006a8723f19ac8a0afb7", size = 365474 }, +] + +[[package]] +name = "python-dateutil" +version = "2.9.0.post0" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "six" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/66/c0/0c8b6ad9f17a802ee498c46e004a0eb49bc148f2fd230864601a86dcf6db/python-dateutil-2.9.0.post0.tar.gz", hash = "sha256:37dd54208da7e1cd875388217d5e00ebd4179249f90fb72437e91a35459a0ad3", size = 342432 } +wheels = [ + { url = "https://files.pythonhosted.org/packages/ec/57/56b9bcc3c9c6a792fcbaf139543cee77261f3651ca9da0c93f5c1221264b/python_dateutil-2.9.0.post0-py2.py3-none-any.whl", hash = "sha256:a8b2bc7bffae282281c8140a97d3aa9c14da0b136dfe83f850eea9a5f7470427", size = 229892 }, +] + +[[package]] +name = "pyyaml" +version = "6.0.2" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/54/ed/79a089b6be93607fa5cdaedf301d7dfb23af5f25c398d5ead2525b063e17/pyyaml-6.0.2.tar.gz", hash = "sha256:d584d9ec91ad65861cc08d42e834324ef890a082e591037abe114850ff7bbc3e", size = 130631 } +wheels = [ + { url = "https://files.pythonhosted.org/packages/9b/95/a3fac87cb7158e231b5a6012e438c647e1a87f09f8e0d123acec8ab8bf71/PyYAML-6.0.2-cp310-cp310-macosx_10_9_x86_64.whl", hash = "sha256:0a9a2848a5b7feac301353437eb7d5957887edbf81d56e903999a75a3d743086", size = 184199 }, + { url = "https://files.pythonhosted.org/packages/c7/7a/68bd47624dab8fd4afbfd3c48e3b79efe09098ae941de5b58abcbadff5cb/PyYAML-6.0.2-cp310-cp310-macosx_11_0_arm64.whl", hash = "sha256:29717114e51c84ddfba879543fb232a6ed60086602313ca38cce623c1d62cfbf", size = 171758 }, + { url = "https://files.pythonhosted.org/packages/49/ee/14c54df452143b9ee9f0f29074d7ca5516a36edb0b4cc40c3f280131656f/PyYAML-6.0.2-cp310-cp310-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:8824b5a04a04a047e72eea5cec3bc266db09e35de6bdfe34c9436ac5ee27d237", size = 718463 }, + { url = "https://files.pythonhosted.org/packages/4d/61/de363a97476e766574650d742205be468921a7b532aa2499fcd886b62530/PyYAML-6.0.2-cp310-cp310-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:7c36280e6fb8385e520936c3cb3b8042851904eba0e58d277dca80a5cfed590b", size = 719280 }, + { url = "https://files.pythonhosted.org/packages/6b/4e/1523cb902fd98355e2e9ea5e5eb237cbc5f3ad5f3075fa65087aa0ecb669/PyYAML-6.0.2-cp310-cp310-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:ec031d5d2feb36d1d1a24380e4db6d43695f3748343d99434e6f5f9156aaa2ed", size = 751239 }, + { url = "https://files.pythonhosted.org/packages/b7/33/5504b3a9a4464893c32f118a9cc045190a91637b119a9c881da1cf6b7a72/PyYAML-6.0.2-cp310-cp310-musllinux_1_1_aarch64.whl", hash = "sha256:936d68689298c36b53b29f23c6dbb74de12b4ac12ca6cfe0e047bedceea56180", size = 695802 }, + { url = "https://files.pythonhosted.org/packages/5c/20/8347dcabd41ef3a3cdc4f7b7a2aff3d06598c8779faa189cdbf878b626a4/PyYAML-6.0.2-cp310-cp310-musllinux_1_1_x86_64.whl", hash = "sha256:23502f431948090f597378482b4812b0caae32c22213aecf3b55325e049a6c68", size = 720527 }, + { url = "https://files.pythonhosted.org/packages/be/aa/5afe99233fb360d0ff37377145a949ae258aaab831bde4792b32650a4378/PyYAML-6.0.2-cp310-cp310-win32.whl", hash = "sha256:2e99c6826ffa974fe6e27cdb5ed0021786b03fc98e5ee3c5bfe1fd5015f42b99", size = 144052 }, + { url = "https://files.pythonhosted.org/packages/b5/84/0fa4b06f6d6c958d207620fc60005e241ecedceee58931bb20138e1e5776/PyYAML-6.0.2-cp310-cp310-win_amd64.whl", hash = "sha256:a4d3091415f010369ae4ed1fc6b79def9416358877534caf6a0fdd2146c87a3e", size = 161774 }, + { url = "https://files.pythonhosted.org/packages/f8/aa/7af4e81f7acba21a4c6be026da38fd2b872ca46226673c89a758ebdc4fd2/PyYAML-6.0.2-cp311-cp311-macosx_10_9_x86_64.whl", hash = "sha256:cc1c1159b3d456576af7a3e4d1ba7e6924cb39de8f67111c735f6fc832082774", size = 184612 }, + { url = "https://files.pythonhosted.org/packages/8b/62/b9faa998fd185f65c1371643678e4d58254add437edb764a08c5a98fb986/PyYAML-6.0.2-cp311-cp311-macosx_11_0_arm64.whl", hash = "sha256:1e2120ef853f59c7419231f3bf4e7021f1b936f6ebd222406c3b60212205d2ee", size = 172040 }, + { url = "https://files.pythonhosted.org/packages/ad/0c/c804f5f922a9a6563bab712d8dcc70251e8af811fce4524d57c2c0fd49a4/PyYAML-6.0.2-cp311-cp311-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:5d225db5a45f21e78dd9358e58a98702a0302f2659a3c6cd320564b75b86f47c", size = 736829 }, + { url = "https://files.pythonhosted.org/packages/51/16/6af8d6a6b210c8e54f1406a6b9481febf9c64a3109c541567e35a49aa2e7/PyYAML-6.0.2-cp311-cp311-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:5ac9328ec4831237bec75defaf839f7d4564be1e6b25ac710bd1a96321cc8317", size = 764167 }, + { url = "https://files.pythonhosted.org/packages/75/e4/2c27590dfc9992f73aabbeb9241ae20220bd9452df27483b6e56d3975cc5/PyYAML-6.0.2-cp311-cp311-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:3ad2a3decf9aaba3d29c8f537ac4b243e36bef957511b4766cb0057d32b0be85", size = 762952 }, + { url = "https://files.pythonhosted.org/packages/9b/97/ecc1abf4a823f5ac61941a9c00fe501b02ac3ab0e373c3857f7d4b83e2b6/PyYAML-6.0.2-cp311-cp311-musllinux_1_1_aarch64.whl", hash = "sha256:ff3824dc5261f50c9b0dfb3be22b4567a6f938ccce4587b38952d85fd9e9afe4", size = 735301 }, + { url = "https://files.pythonhosted.org/packages/45/73/0f49dacd6e82c9430e46f4a027baa4ca205e8b0a9dce1397f44edc23559d/PyYAML-6.0.2-cp311-cp311-musllinux_1_1_x86_64.whl", hash = "sha256:797b4f722ffa07cc8d62053e4cff1486fa6dc094105d13fea7b1de7d8bf71c9e", size = 756638 }, + { url = "https://files.pythonhosted.org/packages/22/5f/956f0f9fc65223a58fbc14459bf34b4cc48dec52e00535c79b8db361aabd/PyYAML-6.0.2-cp311-cp311-win32.whl", hash = "sha256:11d8f3dd2b9c1207dcaf2ee0bbbfd5991f571186ec9cc78427ba5bd32afae4b5", size = 143850 }, + { url = "https://files.pythonhosted.org/packages/ed/23/8da0bbe2ab9dcdd11f4f4557ccaf95c10b9811b13ecced089d43ce59c3c8/PyYAML-6.0.2-cp311-cp311-win_amd64.whl", hash = "sha256:e10ce637b18caea04431ce14fabcf5c64a1c61ec9c56b071a4b7ca131ca52d44", size = 161980 }, + { url = "https://files.pythonhosted.org/packages/86/0c/c581167fc46d6d6d7ddcfb8c843a4de25bdd27e4466938109ca68492292c/PyYAML-6.0.2-cp312-cp312-macosx_10_9_x86_64.whl", hash = "sha256:c70c95198c015b85feafc136515252a261a84561b7b1d51e3384e0655ddf25ab", size = 183873 }, + { url = "https://files.pythonhosted.org/packages/a8/0c/38374f5bb272c051e2a69281d71cba6fdb983413e6758b84482905e29a5d/PyYAML-6.0.2-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:ce826d6ef20b1bc864f0a68340c8b3287705cae2f8b4b1d932177dcc76721725", size = 173302 }, + { url = "https://files.pythonhosted.org/packages/c3/93/9916574aa8c00aa06bbac729972eb1071d002b8e158bd0e83a3b9a20a1f7/PyYAML-6.0.2-cp312-cp312-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:1f71ea527786de97d1a0cc0eacd1defc0985dcf6b3f17bb77dcfc8c34bec4dc5", size = 739154 }, + { url = "https://files.pythonhosted.org/packages/95/0f/b8938f1cbd09739c6da569d172531567dbcc9789e0029aa070856f123984/PyYAML-6.0.2-cp312-cp312-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:9b22676e8097e9e22e36d6b7bda33190d0d400f345f23d4065d48f4ca7ae0425", size = 766223 }, + { url = "https://files.pythonhosted.org/packages/b9/2b/614b4752f2e127db5cc206abc23a8c19678e92b23c3db30fc86ab731d3bd/PyYAML-6.0.2-cp312-cp312-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:80bab7bfc629882493af4aa31a4cfa43a4c57c83813253626916b8c7ada83476", size = 767542 }, + { url = "https://files.pythonhosted.org/packages/d4/00/dd137d5bcc7efea1836d6264f049359861cf548469d18da90cd8216cf05f/PyYAML-6.0.2-cp312-cp312-musllinux_1_1_aarch64.whl", hash = "sha256:0833f8694549e586547b576dcfaba4a6b55b9e96098b36cdc7ebefe667dfed48", size = 731164 }, + { url = "https://files.pythonhosted.org/packages/c9/1f/4f998c900485e5c0ef43838363ba4a9723ac0ad73a9dc42068b12aaba4e4/PyYAML-6.0.2-cp312-cp312-musllinux_1_1_x86_64.whl", hash = "sha256:8b9c7197f7cb2738065c481a0461e50ad02f18c78cd75775628afb4d7137fb3b", size = 756611 }, + { url = "https://files.pythonhosted.org/packages/df/d1/f5a275fdb252768b7a11ec63585bc38d0e87c9e05668a139fea92b80634c/PyYAML-6.0.2-cp312-cp312-win32.whl", hash = "sha256:ef6107725bd54b262d6dedcc2af448a266975032bc85ef0172c5f059da6325b4", size = 140591 }, + { url = "https://files.pythonhosted.org/packages/0c/e8/4f648c598b17c3d06e8753d7d13d57542b30d56e6c2dedf9c331ae56312e/PyYAML-6.0.2-cp312-cp312-win_amd64.whl", hash = "sha256:7e7401d0de89a9a855c839bc697c079a4af81cf878373abd7dc625847d25cbd8", size = 156338 }, + { url = "https://files.pythonhosted.org/packages/ef/e3/3af305b830494fa85d95f6d95ef7fa73f2ee1cc8ef5b495c7c3269fb835f/PyYAML-6.0.2-cp313-cp313-macosx_10_13_x86_64.whl", hash = "sha256:efdca5630322a10774e8e98e1af481aad470dd62c3170801852d752aa7a783ba", size = 181309 }, + { url = "https://files.pythonhosted.org/packages/45/9f/3b1c20a0b7a3200524eb0076cc027a970d320bd3a6592873c85c92a08731/PyYAML-6.0.2-cp313-cp313-macosx_11_0_arm64.whl", hash = "sha256:50187695423ffe49e2deacb8cd10510bc361faac997de9efef88badc3bb9e2d1", size = 171679 }, + { url = "https://files.pythonhosted.org/packages/7c/9a/337322f27005c33bcb656c655fa78325b730324c78620e8328ae28b64d0c/PyYAML-6.0.2-cp313-cp313-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:0ffe8360bab4910ef1b9e87fb812d8bc0a308b0d0eef8c8f44e0254ab3b07133", size = 733428 }, + { url = "https://files.pythonhosted.org/packages/a3/69/864fbe19e6c18ea3cc196cbe5d392175b4cf3d5d0ac1403ec3f2d237ebb5/PyYAML-6.0.2-cp313-cp313-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:17e311b6c678207928d649faa7cb0d7b4c26a0ba73d41e99c4fff6b6c3276484", size = 763361 }, + { url = "https://files.pythonhosted.org/packages/04/24/b7721e4845c2f162d26f50521b825fb061bc0a5afcf9a386840f23ea19fa/PyYAML-6.0.2-cp313-cp313-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:70b189594dbe54f75ab3a1acec5f1e3faa7e8cf2f1e08d9b561cb41b845f69d5", size = 759523 }, + { url = "https://files.pythonhosted.org/packages/2b/b2/e3234f59ba06559c6ff63c4e10baea10e5e7df868092bf9ab40e5b9c56b6/PyYAML-6.0.2-cp313-cp313-musllinux_1_1_aarch64.whl", hash = "sha256:41e4e3953a79407c794916fa277a82531dd93aad34e29c2a514c2c0c5fe971cc", size = 726660 }, + { url = "https://files.pythonhosted.org/packages/fe/0f/25911a9f080464c59fab9027482f822b86bf0608957a5fcc6eaac85aa515/PyYAML-6.0.2-cp313-cp313-musllinux_1_1_x86_64.whl", hash = "sha256:68ccc6023a3400877818152ad9a1033e3db8625d899c72eacb5a668902e4d652", size = 751597 }, + { url = "https://files.pythonhosted.org/packages/14/0d/e2c3b43bbce3cf6bd97c840b46088a3031085179e596d4929729d8d68270/PyYAML-6.0.2-cp313-cp313-win32.whl", hash = "sha256:bc2fa7c6b47d6bc618dd7fb02ef6fdedb1090ec036abab80d4681424b84c1183", size = 140527 }, + { url = "https://files.pythonhosted.org/packages/fa/de/02b54f42487e3d3c6efb3f89428677074ca7bf43aae402517bc7cca949f3/PyYAML-6.0.2-cp313-cp313-win_amd64.whl", hash = "sha256:8388ee1976c416731879ac16da0aff3f63b286ffdd57cdeb95f3f2e085687563", size = 156446 }, +] + +[[package]] +name = "pyyaml-env-tag" +version = "1.1" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "pyyaml" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/eb/2e/79c822141bfd05a853236b504869ebc6b70159afc570e1d5a20641782eaa/pyyaml_env_tag-1.1.tar.gz", hash = "sha256:2eb38b75a2d21ee0475d6d97ec19c63287a7e140231e4214969d0eac923cd7ff", size = 5737 } +wheels = [ + { url = "https://files.pythonhosted.org/packages/04/11/432f32f8097b03e3cd5fe57e88efb685d964e2e5178a48ed61e841f7fdce/pyyaml_env_tag-1.1-py3-none-any.whl", hash = "sha256:17109e1a528561e32f026364712fee1264bc2ea6715120891174ed1b980d2e04", size = 4722 }, +] + +[[package]] +name = "requests" +version = "2.32.4" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "certifi" }, + { name = "charset-normalizer" }, + { name = "idna" }, + { name = "urllib3" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/e1/0a/929373653770d8a0d7ea76c37de6e41f11eb07559b103b1c02cafb3f7cf8/requests-2.32.4.tar.gz", hash = "sha256:27d0316682c8a29834d3264820024b62a36942083d52caf2f14c0591336d3422", size = 135258 } +wheels = [ + { url = "https://files.pythonhosted.org/packages/7c/e4/56027c4a6b4ae70ca9de302488c5ca95ad4a39e190093d6c1a8ace08341b/requests-2.32.4-py3-none-any.whl", hash = "sha256:27babd3cda2a6d50b30443204ee89830707d396671944c998b5975b031ac2b2c", size = 64847 }, +] + +[[package]] +name = "rich" +version = "14.0.0" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "markdown-it-py" }, + { name = "pygments" }, + { name = "typing-extensions", marker = "python_full_version < '3.11'" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/a1/53/830aa4c3066a8ab0ae9a9955976fb770fe9c6102117c8ec4ab3ea62d89e8/rich-14.0.0.tar.gz", hash = "sha256:82f1bc23a6a21ebca4ae0c45af9bdbc492ed20231dcb63f297d6d1021a9d5725", size = 224078 } +wheels = [ + { url = "https://files.pythonhosted.org/packages/0d/9b/63f4c7ebc259242c89b3acafdb37b41d1185c07ff0011164674e9076b491/rich-14.0.0-py3-none-any.whl", hash = "sha256:1c9491e1951aac09caffd42f448ee3d04e58923ffe14993f6e83068dc395d7e0", size = 243229 }, +] + +[[package]] +name = "safetensors" +version = "0.5.3" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/71/7e/2d5d6ee7b40c0682315367ec7475693d110f512922d582fef1bd4a63adc3/safetensors-0.5.3.tar.gz", hash = "sha256:b6b0d6ecacec39a4fdd99cc19f4576f5219ce858e6fd8dbe7609df0b8dc56965", size = 67210 } +wheels = [ + { url = "https://files.pythonhosted.org/packages/18/ae/88f6c49dbd0cc4da0e08610019a3c78a7d390879a919411a410a1876d03a/safetensors-0.5.3-cp38-abi3-macosx_10_12_x86_64.whl", hash = "sha256:bd20eb133db8ed15b40110b7c00c6df51655a2998132193de2f75f72d99c7073", size = 436917 }, + { url = "https://files.pythonhosted.org/packages/b8/3b/11f1b4a2f5d2ab7da34ecc062b0bc301f2be024d110a6466726bec8c055c/safetensors-0.5.3-cp38-abi3-macosx_11_0_arm64.whl", hash = "sha256:21d01c14ff6c415c485616b8b0bf961c46b3b343ca59110d38d744e577f9cce7", size = 418419 }, + { url = "https://files.pythonhosted.org/packages/5d/9a/add3e6fef267658075c5a41573c26d42d80c935cdc992384dfae435feaef/safetensors-0.5.3-cp38-abi3-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:11bce6164887cd491ca75c2326a113ba934be596e22b28b1742ce27b1d076467", size = 459493 }, + { url = "https://files.pythonhosted.org/packages/df/5c/bf2cae92222513cc23b3ff85c4a1bb2811a2c3583ac0f8e8d502751de934/safetensors-0.5.3-cp38-abi3-manylinux_2_17_armv7l.manylinux2014_armv7l.whl", hash = "sha256:4a243be3590bc3301c821da7a18d87224ef35cbd3e5f5727e4e0728b8172411e", size = 472400 }, + { url = "https://files.pythonhosted.org/packages/58/11/7456afb740bd45782d0f4c8e8e1bb9e572f1bf82899fb6ace58af47b4282/safetensors-0.5.3-cp38-abi3-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:8bd84b12b1670a6f8e50f01e28156422a2bc07fb16fc4e98bded13039d688a0d", size = 522891 }, + { url = "https://files.pythonhosted.org/packages/57/3d/fe73a9d2ace487e7285f6e157afee2383bd1ddb911b7cb44a55cf812eae3/safetensors-0.5.3-cp38-abi3-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:391ac8cab7c829452175f871fcaf414aa1e292b5448bd02620f675a7f3e7abb9", size = 537694 }, + { url = "https://files.pythonhosted.org/packages/a6/f8/dae3421624fcc87a89d42e1898a798bc7ff72c61f38973a65d60df8f124c/safetensors-0.5.3-cp38-abi3-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:cead1fa41fc54b1e61089fa57452e8834f798cb1dc7a09ba3524f1eb08e0317a", size = 471642 }, + { url = "https://files.pythonhosted.org/packages/ce/20/1fbe16f9b815f6c5a672f5b760951e20e17e43f67f231428f871909a37f6/safetensors-0.5.3-cp38-abi3-manylinux_2_5_i686.manylinux1_i686.whl", hash = "sha256:1077f3e94182d72618357b04b5ced540ceb71c8a813d3319f1aba448e68a770d", size = 502241 }, + { url = "https://files.pythonhosted.org/packages/5f/18/8e108846b506487aa4629fe4116b27db65c3dde922de2c8e0cc1133f3f29/safetensors-0.5.3-cp38-abi3-musllinux_1_2_aarch64.whl", hash = "sha256:799021e78287bac619c7b3f3606730a22da4cda27759ddf55d37c8db7511c74b", size = 638001 }, + { url = "https://files.pythonhosted.org/packages/82/5a/c116111d8291af6c8c8a8b40628fe833b9db97d8141c2a82359d14d9e078/safetensors-0.5.3-cp38-abi3-musllinux_1_2_armv7l.whl", hash = "sha256:df26da01aaac504334644e1b7642fa000bfec820e7cef83aeac4e355e03195ff", size = 734013 }, + { url = "https://files.pythonhosted.org/packages/7d/ff/41fcc4d3b7de837963622e8610d998710705bbde9a8a17221d85e5d0baad/safetensors-0.5.3-cp38-abi3-musllinux_1_2_i686.whl", hash = "sha256:32c3ef2d7af8b9f52ff685ed0bc43913cdcde135089ae322ee576de93eae5135", size = 670687 }, + { url = "https://files.pythonhosted.org/packages/40/ad/2b113098e69c985a3d8fbda4b902778eae4a35b7d5188859b4a63d30c161/safetensors-0.5.3-cp38-abi3-musllinux_1_2_x86_64.whl", hash = "sha256:37f1521be045e56fc2b54c606d4455573e717b2d887c579ee1dbba5f868ece04", size = 643147 }, + { url = "https://files.pythonhosted.org/packages/0a/0c/95aeb51d4246bd9a3242d3d8349c1112b4ee7611a4b40f0c5c93b05f001d/safetensors-0.5.3-cp38-abi3-win32.whl", hash = "sha256:cfc0ec0846dcf6763b0ed3d1846ff36008c6e7290683b61616c4b040f6a54ace", size = 296677 }, + { url = "https://files.pythonhosted.org/packages/69/e2/b011c38e5394c4c18fb5500778a55ec43ad6106126e74723ffaee246f56e/safetensors-0.5.3-cp38-abi3-win_amd64.whl", hash = "sha256:836cbbc320b47e80acd40e44c8682db0e8ad7123209f69b093def21ec7cafd11", size = 308878 }, +] + +[[package]] +name = "scipy" +version = "1.15.3" +source = { registry = "https://pypi.org/simple" } +resolution-markers = [ + "python_full_version < '3.11'", +] +dependencies = [ + { name = "numpy", version = "2.2.6", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version < '3.11'" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/0f/37/6964b830433e654ec7485e45a00fc9a27cf868d622838f6b6d9c5ec0d532/scipy-1.15.3.tar.gz", hash = "sha256:eae3cf522bc7df64b42cad3925c876e1b0b6c35c1337c93e12c0f366f55b0eaf", size = 59419214 } +wheels = [ + { url = "https://files.pythonhosted.org/packages/78/2f/4966032c5f8cc7e6a60f1b2e0ad686293b9474b65246b0c642e3ef3badd0/scipy-1.15.3-cp310-cp310-macosx_10_13_x86_64.whl", hash = "sha256:a345928c86d535060c9c2b25e71e87c39ab2f22fc96e9636bd74d1dbf9de448c", size = 38702770 }, + { url = "https://files.pythonhosted.org/packages/a0/6e/0c3bf90fae0e910c274db43304ebe25a6b391327f3f10b5dcc638c090795/scipy-1.15.3-cp310-cp310-macosx_12_0_arm64.whl", hash = "sha256:ad3432cb0f9ed87477a8d97f03b763fd1d57709f1bbde3c9369b1dff5503b253", size = 30094511 }, + { url = "https://files.pythonhosted.org/packages/ea/b1/4deb37252311c1acff7f101f6453f0440794f51b6eacb1aad4459a134081/scipy-1.15.3-cp310-cp310-macosx_14_0_arm64.whl", hash = "sha256:aef683a9ae6eb00728a542b796f52a5477b78252edede72b8327a886ab63293f", size = 22368151 }, + { url = "https://files.pythonhosted.org/packages/38/7d/f457626e3cd3c29b3a49ca115a304cebb8cc6f31b04678f03b216899d3c6/scipy-1.15.3-cp310-cp310-macosx_14_0_x86_64.whl", hash = "sha256:1c832e1bd78dea67d5c16f786681b28dd695a8cb1fb90af2e27580d3d0967e92", size = 25121732 }, + { url = "https://files.pythonhosted.org/packages/db/0a/92b1de4a7adc7a15dcf5bddc6e191f6f29ee663b30511ce20467ef9b82e4/scipy-1.15.3-cp310-cp310-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:263961f658ce2165bbd7b99fa5135195c3a12d9bef045345016b8b50c315cb82", size = 35547617 }, + { url = "https://files.pythonhosted.org/packages/8e/6d/41991e503e51fc1134502694c5fa7a1671501a17ffa12716a4a9151af3df/scipy-1.15.3-cp310-cp310-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:9e2abc762b0811e09a0d3258abee2d98e0c703eee49464ce0069590846f31d40", size = 37662964 }, + { url = "https://files.pythonhosted.org/packages/25/e1/3df8f83cb15f3500478c889be8fb18700813b95e9e087328230b98d547ff/scipy-1.15.3-cp310-cp310-musllinux_1_2_aarch64.whl", hash = "sha256:ed7284b21a7a0c8f1b6e5977ac05396c0d008b89e05498c8b7e8f4a1423bba0e", size = 37238749 }, + { url = "https://files.pythonhosted.org/packages/93/3e/b3257cf446f2a3533ed7809757039016b74cd6f38271de91682aa844cfc5/scipy-1.15.3-cp310-cp310-musllinux_1_2_x86_64.whl", hash = "sha256:5380741e53df2c566f4d234b100a484b420af85deb39ea35a1cc1be84ff53a5c", size = 40022383 }, + { url = "https://files.pythonhosted.org/packages/d1/84/55bc4881973d3f79b479a5a2e2df61c8c9a04fcb986a213ac9c02cfb659b/scipy-1.15.3-cp310-cp310-win_amd64.whl", hash = "sha256:9d61e97b186a57350f6d6fd72640f9e99d5a4a2b8fbf4b9ee9a841eab327dc13", size = 41259201 }, + { url = "https://files.pythonhosted.org/packages/96/ab/5cc9f80f28f6a7dff646c5756e559823614a42b1939d86dd0ed550470210/scipy-1.15.3-cp311-cp311-macosx_10_13_x86_64.whl", hash = "sha256:993439ce220d25e3696d1b23b233dd010169b62f6456488567e830654ee37a6b", size = 38714255 }, + { url = "https://files.pythonhosted.org/packages/4a/4a/66ba30abe5ad1a3ad15bfb0b59d22174012e8056ff448cb1644deccbfed2/scipy-1.15.3-cp311-cp311-macosx_12_0_arm64.whl", hash = "sha256:34716e281f181a02341ddeaad584205bd2fd3c242063bd3423d61ac259ca7eba", size = 30111035 }, + { url = "https://files.pythonhosted.org/packages/4b/fa/a7e5b95afd80d24313307f03624acc65801846fa75599034f8ceb9e2cbf6/scipy-1.15.3-cp311-cp311-macosx_14_0_arm64.whl", hash = "sha256:3b0334816afb8b91dab859281b1b9786934392aa3d527cd847e41bb6f45bee65", size = 22384499 }, + { url = "https://files.pythonhosted.org/packages/17/99/f3aaddccf3588bb4aea70ba35328c204cadd89517a1612ecfda5b2dd9d7a/scipy-1.15.3-cp311-cp311-macosx_14_0_x86_64.whl", hash = "sha256:6db907c7368e3092e24919b5e31c76998b0ce1684d51a90943cb0ed1b4ffd6c1", size = 25152602 }, + { url = "https://files.pythonhosted.org/packages/56/c5/1032cdb565f146109212153339f9cb8b993701e9fe56b1c97699eee12586/scipy-1.15.3-cp311-cp311-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:721d6b4ef5dc82ca8968c25b111e307083d7ca9091bc38163fb89243e85e3889", size = 35503415 }, + { url = "https://files.pythonhosted.org/packages/bd/37/89f19c8c05505d0601ed5650156e50eb881ae3918786c8fd7262b4ee66d3/scipy-1.15.3-cp311-cp311-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:39cb9c62e471b1bb3750066ecc3a3f3052b37751c7c3dfd0fd7e48900ed52982", size = 37652622 }, + { url = "https://files.pythonhosted.org/packages/7e/31/be59513aa9695519b18e1851bb9e487de66f2d31f835201f1b42f5d4d475/scipy-1.15.3-cp311-cp311-musllinux_1_2_aarch64.whl", hash = "sha256:795c46999bae845966368a3c013e0e00947932d68e235702b5c3f6ea799aa8c9", size = 37244796 }, + { url = "https://files.pythonhosted.org/packages/10/c0/4f5f3eeccc235632aab79b27a74a9130c6c35df358129f7ac8b29f562ac7/scipy-1.15.3-cp311-cp311-musllinux_1_2_x86_64.whl", hash = "sha256:18aaacb735ab38b38db42cb01f6b92a2d0d4b6aabefeb07f02849e47f8fb3594", size = 40047684 }, + { url = "https://files.pythonhosted.org/packages/ab/a7/0ddaf514ce8a8714f6ed243a2b391b41dbb65251affe21ee3077ec45ea9a/scipy-1.15.3-cp311-cp311-win_amd64.whl", hash = "sha256:ae48a786a28412d744c62fd7816a4118ef97e5be0bee968ce8f0a2fba7acf3bb", size = 41246504 }, + { url = "https://files.pythonhosted.org/packages/37/4b/683aa044c4162e10ed7a7ea30527f2cbd92e6999c10a8ed8edb253836e9c/scipy-1.15.3-cp312-cp312-macosx_10_13_x86_64.whl", hash = "sha256:6ac6310fdbfb7aa6612408bd2f07295bcbd3fda00d2d702178434751fe48e019", size = 38766735 }, + { url = "https://files.pythonhosted.org/packages/7b/7e/f30be3d03de07f25dc0ec926d1681fed5c732d759ac8f51079708c79e680/scipy-1.15.3-cp312-cp312-macosx_12_0_arm64.whl", hash = "sha256:185cd3d6d05ca4b44a8f1595af87f9c372bb6acf9c808e99aa3e9aa03bd98cf6", size = 30173284 }, + { url = "https://files.pythonhosted.org/packages/07/9c/0ddb0d0abdabe0d181c1793db51f02cd59e4901da6f9f7848e1f96759f0d/scipy-1.15.3-cp312-cp312-macosx_14_0_arm64.whl", hash = "sha256:05dc6abcd105e1a29f95eada46d4a3f251743cfd7d3ae8ddb4088047f24ea477", size = 22446958 }, + { url = "https://files.pythonhosted.org/packages/af/43/0bce905a965f36c58ff80d8bea33f1f9351b05fad4beaad4eae34699b7a1/scipy-1.15.3-cp312-cp312-macosx_14_0_x86_64.whl", hash = "sha256:06efcba926324df1696931a57a176c80848ccd67ce6ad020c810736bfd58eb1c", size = 25242454 }, + { url = "https://files.pythonhosted.org/packages/56/30/a6f08f84ee5b7b28b4c597aca4cbe545535c39fe911845a96414700b64ba/scipy-1.15.3-cp312-cp312-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:c05045d8b9bfd807ee1b9f38761993297b10b245f012b11b13b91ba8945f7e45", size = 35210199 }, + { url = "https://files.pythonhosted.org/packages/0b/1f/03f52c282437a168ee2c7c14a1a0d0781a9a4a8962d84ac05c06b4c5b555/scipy-1.15.3-cp312-cp312-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:271e3713e645149ea5ea3e97b57fdab61ce61333f97cfae392c28ba786f9bb49", size = 37309455 }, + { url = "https://files.pythonhosted.org/packages/89/b1/fbb53137f42c4bf630b1ffdfc2151a62d1d1b903b249f030d2b1c0280af8/scipy-1.15.3-cp312-cp312-musllinux_1_2_aarch64.whl", hash = "sha256:6cfd56fc1a8e53f6e89ba3a7a7251f7396412d655bca2aa5611c8ec9a6784a1e", size = 36885140 }, + { url = "https://files.pythonhosted.org/packages/2e/2e/025e39e339f5090df1ff266d021892694dbb7e63568edcfe43f892fa381d/scipy-1.15.3-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:0ff17c0bb1cb32952c09217d8d1eed9b53d1463e5f1dd6052c7857f83127d539", size = 39710549 }, + { url = "https://files.pythonhosted.org/packages/e6/eb/3bf6ea8ab7f1503dca3a10df2e4b9c3f6b3316df07f6c0ded94b281c7101/scipy-1.15.3-cp312-cp312-win_amd64.whl", hash = "sha256:52092bc0472cfd17df49ff17e70624345efece4e1a12b23783a1ac59a1b728ed", size = 40966184 }, + { url = "https://files.pythonhosted.org/packages/73/18/ec27848c9baae6e0d6573eda6e01a602e5649ee72c27c3a8aad673ebecfd/scipy-1.15.3-cp313-cp313-macosx_10_13_x86_64.whl", hash = "sha256:2c620736bcc334782e24d173c0fdbb7590a0a436d2fdf39310a8902505008759", size = 38728256 }, + { url = "https://files.pythonhosted.org/packages/74/cd/1aef2184948728b4b6e21267d53b3339762c285a46a274ebb7863c9e4742/scipy-1.15.3-cp313-cp313-macosx_12_0_arm64.whl", hash = "sha256:7e11270a000969409d37ed399585ee530b9ef6aa99d50c019de4cb01e8e54e62", size = 30109540 }, + { url = "https://files.pythonhosted.org/packages/5b/d8/59e452c0a255ec352bd0a833537a3bc1bfb679944c4938ab375b0a6b3a3e/scipy-1.15.3-cp313-cp313-macosx_14_0_arm64.whl", hash = "sha256:8c9ed3ba2c8a2ce098163a9bdb26f891746d02136995df25227a20e71c396ebb", size = 22383115 }, + { url = "https://files.pythonhosted.org/packages/08/f5/456f56bbbfccf696263b47095291040655e3cbaf05d063bdc7c7517f32ac/scipy-1.15.3-cp313-cp313-macosx_14_0_x86_64.whl", hash = "sha256:0bdd905264c0c9cfa74a4772cdb2070171790381a5c4d312c973382fc6eaf730", size = 25163884 }, + { url = "https://files.pythonhosted.org/packages/a2/66/a9618b6a435a0f0c0b8a6d0a2efb32d4ec5a85f023c2b79d39512040355b/scipy-1.15.3-cp313-cp313-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:79167bba085c31f38603e11a267d862957cbb3ce018d8b38f79ac043bc92d825", size = 35174018 }, + { url = "https://files.pythonhosted.org/packages/b5/09/c5b6734a50ad4882432b6bb7c02baf757f5b2f256041da5df242e2d7e6b6/scipy-1.15.3-cp313-cp313-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:c9deabd6d547aee2c9a81dee6cc96c6d7e9a9b1953f74850c179f91fdc729cb7", size = 37269716 }, + { url = "https://files.pythonhosted.org/packages/77/0a/eac00ff741f23bcabd352731ed9b8995a0a60ef57f5fd788d611d43d69a1/scipy-1.15.3-cp313-cp313-musllinux_1_2_aarch64.whl", hash = "sha256:dde4fc32993071ac0c7dd2d82569e544f0bdaff66269cb475e0f369adad13f11", size = 36872342 }, + { url = "https://files.pythonhosted.org/packages/fe/54/4379be86dd74b6ad81551689107360d9a3e18f24d20767a2d5b9253a3f0a/scipy-1.15.3-cp313-cp313-musllinux_1_2_x86_64.whl", hash = "sha256:f77f853d584e72e874d87357ad70f44b437331507d1c311457bed8ed2b956126", size = 39670869 }, + { url = "https://files.pythonhosted.org/packages/87/2e/892ad2862ba54f084ffe8cc4a22667eaf9c2bcec6d2bff1d15713c6c0703/scipy-1.15.3-cp313-cp313-win_amd64.whl", hash = "sha256:b90ab29d0c37ec9bf55424c064312930ca5f4bde15ee8619ee44e69319aab163", size = 40988851 }, + { url = "https://files.pythonhosted.org/packages/1b/e9/7a879c137f7e55b30d75d90ce3eb468197646bc7b443ac036ae3fe109055/scipy-1.15.3-cp313-cp313t-macosx_10_13_x86_64.whl", hash = "sha256:3ac07623267feb3ae308487c260ac684b32ea35fd81e12845039952f558047b8", size = 38863011 }, + { url = "https://files.pythonhosted.org/packages/51/d1/226a806bbd69f62ce5ef5f3ffadc35286e9fbc802f606a07eb83bf2359de/scipy-1.15.3-cp313-cp313t-macosx_12_0_arm64.whl", hash = "sha256:6487aa99c2a3d509a5227d9a5e889ff05830a06b2ce08ec30df6d79db5fcd5c5", size = 30266407 }, + { url = "https://files.pythonhosted.org/packages/e5/9b/f32d1d6093ab9eeabbd839b0f7619c62e46cc4b7b6dbf05b6e615bbd4400/scipy-1.15.3-cp313-cp313t-macosx_14_0_arm64.whl", hash = "sha256:50f9e62461c95d933d5c5ef4a1f2ebf9a2b4e83b0db374cb3f1de104d935922e", size = 22540030 }, + { url = "https://files.pythonhosted.org/packages/e7/29/c278f699b095c1a884f29fda126340fcc201461ee8bfea5c8bdb1c7c958b/scipy-1.15.3-cp313-cp313t-macosx_14_0_x86_64.whl", hash = "sha256:14ed70039d182f411ffc74789a16df3835e05dc469b898233a245cdfd7f162cb", size = 25218709 }, + { url = "https://files.pythonhosted.org/packages/24/18/9e5374b617aba742a990581373cd6b68a2945d65cc588482749ef2e64467/scipy-1.15.3-cp313-cp313t-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:0a769105537aa07a69468a0eefcd121be52006db61cdd8cac8a0e68980bbb723", size = 34809045 }, + { url = "https://files.pythonhosted.org/packages/e1/fe/9c4361e7ba2927074360856db6135ef4904d505e9b3afbbcb073c4008328/scipy-1.15.3-cp313-cp313t-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:9db984639887e3dffb3928d118145ffe40eff2fa40cb241a306ec57c219ebbbb", size = 36703062 }, + { url = "https://files.pythonhosted.org/packages/b7/8e/038ccfe29d272b30086b25a4960f757f97122cb2ec42e62b460d02fe98e9/scipy-1.15.3-cp313-cp313t-musllinux_1_2_aarch64.whl", hash = "sha256:40e54d5c7e7ebf1aa596c374c49fa3135f04648a0caabcb66c52884b943f02b4", size = 36393132 }, + { url = "https://files.pythonhosted.org/packages/10/7e/5c12285452970be5bdbe8352c619250b97ebf7917d7a9a9e96b8a8140f17/scipy-1.15.3-cp313-cp313t-musllinux_1_2_x86_64.whl", hash = "sha256:5e721fed53187e71d0ccf382b6bf977644c533e506c4d33c3fb24de89f5c3ed5", size = 38979503 }, + { url = "https://files.pythonhosted.org/packages/81/06/0a5e5349474e1cbc5757975b21bd4fad0e72ebf138c5592f191646154e06/scipy-1.15.3-cp313-cp313t-win_amd64.whl", hash = "sha256:76ad1fb5f8752eabf0fa02e4cc0336b4e8f021e2d5f061ed37d6d264db35e3ca", size = 40308097 }, +] + +[[package]] +name = "scipy" +version = "1.16.0" +source = { registry = "https://pypi.org/simple" } +resolution-markers = [ + "python_full_version >= '3.13'", + "python_full_version == '3.12.*'", + "python_full_version == '3.11.*'", +] +dependencies = [ + { name = "numpy", version = "2.3.1", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version >= '3.11'" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/81/18/b06a83f0c5ee8cddbde5e3f3d0bb9b702abfa5136ef6d4620ff67df7eee5/scipy-1.16.0.tar.gz", hash = "sha256:b5ef54021e832869c8cfb03bc3bf20366cbcd426e02a58e8a58d7584dfbb8f62", size = 30581216 } +wheels = [ + { url = "https://files.pythonhosted.org/packages/d9/f8/53fc4884df6b88afd5f5f00240bdc49fee2999c7eff3acf5953eb15bc6f8/scipy-1.16.0-cp311-cp311-macosx_10_14_x86_64.whl", hash = "sha256:deec06d831b8f6b5fb0b652433be6a09db29e996368ce5911faf673e78d20085", size = 36447362 }, + { url = "https://files.pythonhosted.org/packages/c9/25/fad8aa228fa828705142a275fc593d701b1817c98361a2d6b526167d07bc/scipy-1.16.0-cp311-cp311-macosx_12_0_arm64.whl", hash = "sha256:d30c0fe579bb901c61ab4bb7f3eeb7281f0d4c4a7b52dbf563c89da4fd2949be", size = 28547120 }, + { url = "https://files.pythonhosted.org/packages/8d/be/d324ddf6b89fd1c32fecc307f04d095ce84abb52d2e88fab29d0cd8dc7a8/scipy-1.16.0-cp311-cp311-macosx_14_0_arm64.whl", hash = "sha256:b2243561b45257f7391d0f49972fca90d46b79b8dbcb9b2cb0f9df928d370ad4", size = 20818922 }, + { url = "https://files.pythonhosted.org/packages/cd/e0/cf3f39e399ac83fd0f3ba81ccc5438baba7cfe02176be0da55ff3396f126/scipy-1.16.0-cp311-cp311-macosx_14_0_x86_64.whl", hash = "sha256:e6d7dfc148135e9712d87c5f7e4f2ddc1304d1582cb3a7d698bbadedb61c7afd", size = 23409695 }, + { url = "https://files.pythonhosted.org/packages/5b/61/d92714489c511d3ffd6830ac0eb7f74f243679119eed8b9048e56b9525a1/scipy-1.16.0-cp311-cp311-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:90452f6a9f3fe5a2cf3748e7be14f9cc7d9b124dce19667b54f5b429d680d539", size = 33444586 }, + { url = "https://files.pythonhosted.org/packages/af/2c/40108915fd340c830aee332bb85a9160f99e90893e58008b659b9f3dddc0/scipy-1.16.0-cp311-cp311-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:a2f0bf2f58031c8701a8b601df41701d2a7be17c7ffac0a4816aeba89c4cdac8", size = 35284126 }, + { url = "https://files.pythonhosted.org/packages/d3/30/e9eb0ad3d0858df35d6c703cba0a7e16a18a56a9e6b211d861fc6f261c5f/scipy-1.16.0-cp311-cp311-musllinux_1_2_aarch64.whl", hash = "sha256:6c4abb4c11fc0b857474241b812ce69ffa6464b4bd8f4ecb786cf240367a36a7", size = 35608257 }, + { url = "https://files.pythonhosted.org/packages/c8/ff/950ee3e0d612b375110d8cda211c1f787764b4c75e418a4b71f4a5b1e07f/scipy-1.16.0-cp311-cp311-musllinux_1_2_x86_64.whl", hash = "sha256:b370f8f6ac6ef99815b0d5c9f02e7ade77b33007d74802efc8316c8db98fd11e", size = 38040541 }, + { url = "https://files.pythonhosted.org/packages/8b/c9/750d34788288d64ffbc94fdb4562f40f609d3f5ef27ab4f3a4ad00c9033e/scipy-1.16.0-cp311-cp311-win_amd64.whl", hash = "sha256:a16ba90847249bedce8aa404a83fb8334b825ec4a8e742ce6012a7a5e639f95c", size = 38570814 }, + { url = "https://files.pythonhosted.org/packages/01/c0/c943bc8d2bbd28123ad0f4f1eef62525fa1723e84d136b32965dcb6bad3a/scipy-1.16.0-cp312-cp312-macosx_10_14_x86_64.whl", hash = "sha256:7eb6bd33cef4afb9fa5f1fb25df8feeb1e52d94f21a44f1d17805b41b1da3180", size = 36459071 }, + { url = "https://files.pythonhosted.org/packages/99/0d/270e2e9f1a4db6ffbf84c9a0b648499842046e4e0d9b2275d150711b3aba/scipy-1.16.0-cp312-cp312-macosx_12_0_arm64.whl", hash = "sha256:1dbc8fdba23e4d80394ddfab7a56808e3e6489176d559c6c71935b11a2d59db1", size = 28490500 }, + { url = "https://files.pythonhosted.org/packages/1c/22/01d7ddb07cff937d4326198ec8d10831367a708c3da72dfd9b7ceaf13028/scipy-1.16.0-cp312-cp312-macosx_14_0_arm64.whl", hash = "sha256:7dcf42c380e1e3737b343dec21095c9a9ad3f9cbe06f9c05830b44b1786c9e90", size = 20762345 }, + { url = "https://files.pythonhosted.org/packages/34/7f/87fd69856569ccdd2a5873fe5d7b5bbf2ad9289d7311d6a3605ebde3a94b/scipy-1.16.0-cp312-cp312-macosx_14_0_x86_64.whl", hash = "sha256:26ec28675f4a9d41587266084c626b02899db373717d9312fa96ab17ca1ae94d", size = 23418563 }, + { url = "https://files.pythonhosted.org/packages/f6/f1/e4f4324fef7f54160ab749efbab6a4bf43678a9eb2e9817ed71a0a2fd8de/scipy-1.16.0-cp312-cp312-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:952358b7e58bd3197cfbd2f2f2ba829f258404bdf5db59514b515a8fe7a36c52", size = 33203951 }, + { url = "https://files.pythonhosted.org/packages/6d/f0/b6ac354a956384fd8abee2debbb624648125b298f2c4a7b4f0d6248048a5/scipy-1.16.0-cp312-cp312-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:03931b4e870c6fef5b5c0970d52c9f6ddd8c8d3e934a98f09308377eba6f3824", size = 35070225 }, + { url = "https://files.pythonhosted.org/packages/e5/73/5cbe4a3fd4bc3e2d67ffad02c88b83edc88f381b73ab982f48f3df1a7790/scipy-1.16.0-cp312-cp312-musllinux_1_2_aarch64.whl", hash = "sha256:512c4f4f85912767c351a0306824ccca6fd91307a9f4318efe8fdbd9d30562ef", size = 35389070 }, + { url = "https://files.pythonhosted.org/packages/86/e8/a60da80ab9ed68b31ea5a9c6dfd3c2f199347429f229bf7f939a90d96383/scipy-1.16.0-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:e69f798847e9add03d512eaf5081a9a5c9a98757d12e52e6186ed9681247a1ac", size = 37825287 }, + { url = "https://files.pythonhosted.org/packages/ea/b5/29fece1a74c6a94247f8a6fb93f5b28b533338e9c34fdcc9cfe7a939a767/scipy-1.16.0-cp312-cp312-win_amd64.whl", hash = "sha256:adf9b1999323ba335adc5d1dc7add4781cb5a4b0ef1e98b79768c05c796c4e49", size = 38431929 }, + { url = "https://files.pythonhosted.org/packages/46/95/0746417bc24be0c2a7b7563946d61f670a3b491b76adede420e9d173841f/scipy-1.16.0-cp313-cp313-macosx_10_14_x86_64.whl", hash = "sha256:e9f414cbe9ca289a73e0cc92e33a6a791469b6619c240aa32ee18abdce8ab451", size = 36418162 }, + { url = "https://files.pythonhosted.org/packages/19/5a/914355a74481b8e4bbccf67259bbde171348a3f160b67b4945fbc5f5c1e5/scipy-1.16.0-cp313-cp313-macosx_12_0_arm64.whl", hash = "sha256:bbba55fb97ba3cdef9b1ee973f06b09d518c0c7c66a009c729c7d1592be1935e", size = 28465985 }, + { url = "https://files.pythonhosted.org/packages/58/46/63477fc1246063855969cbefdcee8c648ba4b17f67370bd542ba56368d0b/scipy-1.16.0-cp313-cp313-macosx_14_0_arm64.whl", hash = "sha256:58e0d4354eacb6004e7aa1cd350e5514bd0270acaa8d5b36c0627bb3bb486974", size = 20737961 }, + { url = "https://files.pythonhosted.org/packages/93/86/0fbb5588b73555e40f9d3d6dde24ee6fac7d8e301a27f6f0cab9d8f66ff2/scipy-1.16.0-cp313-cp313-macosx_14_0_x86_64.whl", hash = "sha256:75b2094ec975c80efc273567436e16bb794660509c12c6a31eb5c195cbf4b6dc", size = 23377941 }, + { url = "https://files.pythonhosted.org/packages/ca/80/a561f2bf4c2da89fa631b3cbf31d120e21ea95db71fd9ec00cb0247c7a93/scipy-1.16.0-cp313-cp313-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:6b65d232157a380fdd11a560e7e21cde34fdb69d65c09cb87f6cc024ee376351", size = 33196703 }, + { url = "https://files.pythonhosted.org/packages/11/6b/3443abcd0707d52e48eb315e33cc669a95e29fc102229919646f5a501171/scipy-1.16.0-cp313-cp313-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:1d8747f7736accd39289943f7fe53a8333be7f15a82eea08e4afe47d79568c32", size = 35083410 }, + { url = "https://files.pythonhosted.org/packages/20/ab/eb0fc00e1e48961f1bd69b7ad7e7266896fe5bad4ead91b5fc6b3561bba4/scipy-1.16.0-cp313-cp313-musllinux_1_2_aarch64.whl", hash = "sha256:eb9f147a1b8529bb7fec2a85cf4cf42bdfadf9e83535c309a11fdae598c88e8b", size = 35387829 }, + { url = "https://files.pythonhosted.org/packages/57/9e/d6fc64e41fad5d481c029ee5a49eefc17f0b8071d636a02ceee44d4a0de2/scipy-1.16.0-cp313-cp313-musllinux_1_2_x86_64.whl", hash = "sha256:d2b83c37edbfa837a8923d19c749c1935ad3d41cf196006a24ed44dba2ec4358", size = 37841356 }, + { url = "https://files.pythonhosted.org/packages/7c/a7/4c94bbe91f12126b8bf6709b2471900577b7373a4fd1f431f28ba6f81115/scipy-1.16.0-cp313-cp313-win_amd64.whl", hash = "sha256:79a3c13d43c95aa80b87328a46031cf52508cf5f4df2767602c984ed1d3c6bbe", size = 38403710 }, + { url = "https://files.pythonhosted.org/packages/47/20/965da8497f6226e8fa90ad3447b82ed0e28d942532e92dd8b91b43f100d4/scipy-1.16.0-cp313-cp313t-macosx_10_14_x86_64.whl", hash = "sha256:f91b87e1689f0370690e8470916fe1b2308e5b2061317ff76977c8f836452a47", size = 36813833 }, + { url = "https://files.pythonhosted.org/packages/28/f4/197580c3dac2d234e948806e164601c2df6f0078ed9f5ad4a62685b7c331/scipy-1.16.0-cp313-cp313t-macosx_12_0_arm64.whl", hash = "sha256:88a6ca658fb94640079e7a50b2ad3b67e33ef0f40e70bdb7dc22017dae73ac08", size = 28974431 }, + { url = "https://files.pythonhosted.org/packages/8a/fc/e18b8550048d9224426e76906694c60028dbdb65d28b1372b5503914b89d/scipy-1.16.0-cp313-cp313t-macosx_14_0_arm64.whl", hash = "sha256:ae902626972f1bd7e4e86f58fd72322d7f4ec7b0cfc17b15d4b7006efc385176", size = 21246454 }, + { url = "https://files.pythonhosted.org/packages/8c/48/07b97d167e0d6a324bfd7484cd0c209cc27338b67e5deadae578cf48e809/scipy-1.16.0-cp313-cp313t-macosx_14_0_x86_64.whl", hash = "sha256:8cb824c1fc75ef29893bc32b3ddd7b11cf9ab13c1127fe26413a05953b8c32ed", size = 23772979 }, + { url = "https://files.pythonhosted.org/packages/4c/4f/9efbd3f70baf9582edf271db3002b7882c875ddd37dc97f0f675ad68679f/scipy-1.16.0-cp313-cp313t-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:de2db7250ff6514366a9709c2cba35cb6d08498e961cba20d7cff98a7ee88938", size = 33341972 }, + { url = "https://files.pythonhosted.org/packages/3f/dc/9e496a3c5dbe24e76ee24525155ab7f659c20180bab058ef2c5fa7d9119c/scipy-1.16.0-cp313-cp313t-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:e85800274edf4db8dd2e4e93034f92d1b05c9421220e7ded9988b16976f849c1", size = 35185476 }, + { url = "https://files.pythonhosted.org/packages/ce/b3/21001cff985a122ba434c33f2c9d7d1dc3b669827e94f4fc4e1fe8b9dfd8/scipy-1.16.0-cp313-cp313t-musllinux_1_2_aarch64.whl", hash = "sha256:4f720300a3024c237ace1cb11f9a84c38beb19616ba7c4cdcd771047a10a1706", size = 35570990 }, + { url = "https://files.pythonhosted.org/packages/e5/d3/7ba42647d6709251cdf97043d0c107e0317e152fa2f76873b656b509ff55/scipy-1.16.0-cp313-cp313t-musllinux_1_2_x86_64.whl", hash = "sha256:aad603e9339ddb676409b104c48a027e9916ce0d2838830691f39552b38a352e", size = 37950262 }, + { url = "https://files.pythonhosted.org/packages/eb/c4/231cac7a8385394ebbbb4f1ca662203e9d8c332825ab4f36ffc3ead09a42/scipy-1.16.0-cp313-cp313t-win_amd64.whl", hash = "sha256:f56296fefca67ba605fd74d12f7bd23636267731a72cb3947963e76b8c0a25db", size = 38515076 }, +] + +[[package]] +name = "setuptools" +version = "80.9.0" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/18/5d/3bf57dcd21979b887f014ea83c24ae194cfcd12b9e0fda66b957c69d1fca/setuptools-80.9.0.tar.gz", hash = "sha256:f36b47402ecde768dbfafc46e8e4207b4360c654f1f3bb84475f0a28628fb19c", size = 1319958 } +wheels = [ + { url = "https://files.pythonhosted.org/packages/a3/dc/17031897dae0efacfea57dfd3a82fdd2a2aeb58e0ff71b77b87e44edc772/setuptools-80.9.0-py3-none-any.whl", hash = "sha256:062d34222ad13e0cc312a4c02d73f059e86a4acbfbdea8f8f76b28c99f306922", size = 1201486 }, +] + +[[package]] +name = "simplejson" +version = "3.20.1" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/af/92/51b417685abd96b31308b61b9acce7ec50d8e1de8fbc39a7fd4962c60689/simplejson-3.20.1.tar.gz", hash = "sha256:e64139b4ec4f1f24c142ff7dcafe55a22b811a74d86d66560c8815687143037d", size = 85591 } +wheels = [ + { url = "https://files.pythonhosted.org/packages/25/c4/627214fb418cd4a17fb0230ff0b6c3bb4a85cbb48dd69c85dcc3b85df828/simplejson-3.20.1-cp310-cp310-macosx_10_9_universal2.whl", hash = "sha256:e580aa65d5f6c3bf41b9b4afe74be5d5ddba9576701c107c772d936ea2b5043a", size = 93790 }, + { url = "https://files.pythonhosted.org/packages/15/ca/56a6a2a33cbcf330c4d71af3f827c47e4e0ba791e78f2642f3d1ab02ff31/simplejson-3.20.1-cp310-cp310-macosx_10_9_x86_64.whl", hash = "sha256:4a586ce4f78cec11f22fe55c5bee0f067e803aab9bad3441afe2181693b5ebb5", size = 75707 }, + { url = "https://files.pythonhosted.org/packages/a9/c8/3d92b67e03a3b6207d97202669f9454ed700b35ade9bd4428265a078fb6c/simplejson-3.20.1-cp310-cp310-macosx_11_0_arm64.whl", hash = "sha256:74a1608f9e6e8c27a4008d70a54270868306d80ed48c9df7872f9f4b8ac87808", size = 75700 }, + { url = "https://files.pythonhosted.org/packages/74/30/20001219d6fdca4aaa3974c96dfb6955a766b4e2cc950505a5b51fd050b0/simplejson-3.20.1-cp310-cp310-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:03db8cb64154189a92a7786209f24e391644f3a3fa335658be2df2af1960b8d8", size = 138672 }, + { url = "https://files.pythonhosted.org/packages/21/47/50157810876c2a7ebbd6e6346ec25eda841fe061fecaa02538a7742a3d2a/simplejson-3.20.1-cp310-cp310-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:eea7e2b7d858f6fdfbf0fe3cb846d6bd8a45446865bc09960e51f3d473c2271b", size = 146616 }, + { url = "https://files.pythonhosted.org/packages/95/60/8c97cdc93096437b0aca2745aca63c880fe2315fd7f6a6ce6edbb344a2ae/simplejson-3.20.1-cp310-cp310-manylinux_2_5_i686.manylinux1_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:e66712b17d8425bb7ff8968d4c7c7fd5a2dd7bd63728b28356223c000dd2f91f", size = 134344 }, + { url = "https://files.pythonhosted.org/packages/bb/9e/da184f0e9bb3a5d7ffcde713bd41b4fe46cca56b6f24d9bd155fac56805a/simplejson-3.20.1-cp310-cp310-manylinux_2_5_x86_64.manylinux1_x86_64.manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:a2cc4f6486f9f515b62f5831ff1888886619b84fc837de68f26d919ba7bbdcbc", size = 138017 }, + { url = "https://files.pythonhosted.org/packages/31/db/00d1a8d9b036db98f678c8a3c69ed17d2894d1768d7a00576e787ad3e546/simplejson-3.20.1-cp310-cp310-musllinux_1_2_aarch64.whl", hash = "sha256:a3c2df555ee4016148fa192e2b9cd9e60bc1d40769366134882685e90aee2a1e", size = 140118 }, + { url = "https://files.pythonhosted.org/packages/52/21/57fc47eab8c1c73390b933a5ba9271f08e3e1ec83162c580357f28f5b97c/simplejson-3.20.1-cp310-cp310-musllinux_1_2_i686.whl", hash = "sha256:78520f04b7548a5e476b5396c0847e066f1e0a4c0c5e920da1ad65e95f410b11", size = 140314 }, + { url = "https://files.pythonhosted.org/packages/ad/cc/7cfd78d1e0fa5e57350b98cfe77353b6dfa13dce21afa4060e1019223852/simplejson-3.20.1-cp310-cp310-musllinux_1_2_ppc64le.whl", hash = "sha256:f4bd49ecde87b0fe9f55cc971449a32832bca9910821f7072bbfae1155eaa007", size = 148544 }, + { url = "https://files.pythonhosted.org/packages/63/26/1c894a1c2bd95dc8be0cf5a2fa73b0d173105b6ca18c90cb981ff10443d0/simplejson-3.20.1-cp310-cp310-musllinux_1_2_x86_64.whl", hash = "sha256:7eaae2b88eb5da53caaffdfa50e2e12022553949b88c0df4f9a9663609373f72", size = 141172 }, + { url = "https://files.pythonhosted.org/packages/93/27/0717dccc10cd9988dbf1314def52ab32678a95a95328bb37cafacf499400/simplejson-3.20.1-cp310-cp310-win32.whl", hash = "sha256:e836fb88902799eac8debc2b642300748f4860a197fa3d9ea502112b6bb8e142", size = 74181 }, + { url = "https://files.pythonhosted.org/packages/5f/af/593f896573f306519332d4287b1ab8b7b888c239bbd5159f7054d7055c2d/simplejson-3.20.1-cp310-cp310-win_amd64.whl", hash = "sha256:b122a19b552b212fc3b5b96fc5ce92333d4a9ac0a800803e1f17ebb16dac4be5", size = 75738 }, + { url = "https://files.pythonhosted.org/packages/76/59/74bc90d1c051bc2432c96b34bd4e8036875ab58b4fcbe4d6a5a76985f853/simplejson-3.20.1-cp311-cp311-macosx_10_9_universal2.whl", hash = "sha256:325b8c107253d3217e89d7b50c71015b5b31e2433e6c5bf38967b2f80630a8ca", size = 92132 }, + { url = "https://files.pythonhosted.org/packages/71/c7/1970916e0c51794fff89f76da2f632aaf0b259b87753c88a8c409623d3e1/simplejson-3.20.1-cp311-cp311-macosx_10_9_x86_64.whl", hash = "sha256:88a7baa8211089b9e58d78fbc1b0b322103f3f3d459ff16f03a36cece0d0fcf0", size = 74956 }, + { url = "https://files.pythonhosted.org/packages/c8/0d/98cc5909180463f1d75fac7180de62d4cdb4e82c4fef276b9e591979372c/simplejson-3.20.1-cp311-cp311-macosx_11_0_arm64.whl", hash = "sha256:299b1007b8101d50d95bc0db1bf5c38dc372e85b504cf77f596462083ee77e3f", size = 74772 }, + { url = "https://files.pythonhosted.org/packages/e1/94/a30a5211a90d67725a3e8fcc1c788189f2ae2ed2b96b63ed15d0b7f5d6bb/simplejson-3.20.1-cp311-cp311-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:03ec618ed65caab48e81e3ed29586236a8e57daef792f1f3bb59504a7e98cd10", size = 143575 }, + { url = "https://files.pythonhosted.org/packages/ee/08/cdb6821f1058eb5db46d252de69ff7e6c53f05f1bae6368fe20d5b51d37e/simplejson-3.20.1-cp311-cp311-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:cd2cdead1d3197f0ff43373cf4730213420523ba48697743e135e26f3d179f38", size = 153241 }, + { url = "https://files.pythonhosted.org/packages/4c/2d/ca3caeea0bdc5efc5503d5f57a2dfb56804898fb196dfada121323ee0ccb/simplejson-3.20.1-cp311-cp311-manylinux_2_5_i686.manylinux1_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:3466d2839fdc83e1af42e07b90bc8ff361c4e8796cd66722a40ba14e458faddd", size = 141500 }, + { url = "https://files.pythonhosted.org/packages/e1/33/d3e0779d5c58245e7370c98eb969275af6b7a4a5aec3b97cbf85f09ad328/simplejson-3.20.1-cp311-cp311-manylinux_2_5_x86_64.manylinux1_x86_64.manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:d492ed8e92f3a9f9be829205f44b1d0a89af6582f0cf43e0d129fa477b93fe0c", size = 144757 }, + { url = "https://files.pythonhosted.org/packages/54/53/2d93128bb55861b2fa36c5944f38da51a0bc6d83e513afc6f7838440dd15/simplejson-3.20.1-cp311-cp311-musllinux_1_2_aarch64.whl", hash = "sha256:f924b485537b640dc69434565463fd6fc0c68c65a8c6e01a823dd26c9983cf79", size = 144409 }, + { url = "https://files.pythonhosted.org/packages/99/4c/dac310a98f897ad3435b4bdc836d92e78f09e38c5dbf28211ed21dc59fa2/simplejson-3.20.1-cp311-cp311-musllinux_1_2_i686.whl", hash = "sha256:9e8eacf6a3491bf76ea91a8d46726368a6be0eb94993f60b8583550baae9439e", size = 146082 }, + { url = "https://files.pythonhosted.org/packages/ee/22/d7ba958cfed39827335b82656b1c46f89678faecda9a7677b47e87b48ee6/simplejson-3.20.1-cp311-cp311-musllinux_1_2_ppc64le.whl", hash = "sha256:d34d04bf90b4cea7c22d8b19091633908f14a096caa301b24c2f3d85b5068fb8", size = 154339 }, + { url = "https://files.pythonhosted.org/packages/b8/c8/b072b741129406a7086a0799c6f5d13096231bf35fdd87a0cffa789687fc/simplejson-3.20.1-cp311-cp311-musllinux_1_2_x86_64.whl", hash = "sha256:69dd28d4ce38390ea4aaf212902712c0fd1093dc4c1ff67e09687c3c3e15a749", size = 147915 }, + { url = "https://files.pythonhosted.org/packages/6c/46/8347e61e9cf3db5342a42f7fd30a81b4f5cf85977f916852d7674a540907/simplejson-3.20.1-cp311-cp311-win32.whl", hash = "sha256:dfe7a9da5fd2a3499436cd350f31539e0a6ded5da6b5b3d422df016444d65e43", size = 73972 }, + { url = "https://files.pythonhosted.org/packages/01/85/b52f24859237b4e9d523d5655796d911ba3d46e242eb1959c45b6af5aedd/simplejson-3.20.1-cp311-cp311-win_amd64.whl", hash = "sha256:896a6c04d7861d507d800da7642479c3547060bf97419d9ef73d98ced8258766", size = 75595 }, + { url = "https://files.pythonhosted.org/packages/8d/eb/34c16a1ac9ba265d024dc977ad84e1659d931c0a700967c3e59a98ed7514/simplejson-3.20.1-cp312-cp312-macosx_10_9_universal2.whl", hash = "sha256:f31c4a3a7ab18467ee73a27f3e59158255d1520f3aad74315edde7a940f1be23", size = 93100 }, + { url = "https://files.pythonhosted.org/packages/41/fc/2c2c007d135894971e6814e7c0806936e5bade28f8db4dd7e2a58b50debd/simplejson-3.20.1-cp312-cp312-macosx_10_9_x86_64.whl", hash = "sha256:884e6183d16b725e113b83a6fc0230152ab6627d4d36cb05c89c2c5bccfa7bc6", size = 75464 }, + { url = "https://files.pythonhosted.org/packages/0f/05/2b5ecb33b776c34bb5cace5de5d7669f9b60e3ca13c113037b2ca86edfbd/simplejson-3.20.1-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:03d7a426e416fe0d3337115f04164cd9427eb4256e843a6b8751cacf70abc832", size = 75112 }, + { url = "https://files.pythonhosted.org/packages/fe/36/1f3609a2792f06cd4b71030485f78e91eb09cfd57bebf3116bf2980a8bac/simplejson-3.20.1-cp312-cp312-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:000602141d0bddfcff60ea6a6e97d5e10c9db6b17fd2d6c66199fa481b6214bb", size = 150182 }, + { url = "https://files.pythonhosted.org/packages/2f/b0/053fbda38b8b602a77a4f7829def1b4f316cd8deb5440a6d3ee90790d2a4/simplejson-3.20.1-cp312-cp312-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:af8377a8af78226e82e3a4349efdde59ffa421ae88be67e18cef915e4023a595", size = 158363 }, + { url = "https://files.pythonhosted.org/packages/d1/4b/2eb84ae867539a80822e92f9be4a7200dffba609275faf99b24141839110/simplejson-3.20.1-cp312-cp312-manylinux_2_5_i686.manylinux1_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:15c7de4c88ab2fbcb8781a3b982ef883696736134e20b1210bca43fb42ff1acf", size = 148415 }, + { url = "https://files.pythonhosted.org/packages/e0/bd/400b0bd372a5666addf2540c7358bfc3841b9ce5cdbc5cc4ad2f61627ad8/simplejson-3.20.1-cp312-cp312-manylinux_2_5_x86_64.manylinux1_x86_64.manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:455a882ff3f97d810709f7b620007d4e0aca8da71d06fc5c18ba11daf1c4df49", size = 152213 }, + { url = "https://files.pythonhosted.org/packages/50/12/143f447bf6a827ee9472693768dc1a5eb96154f8feb140a88ce6973a3cfa/simplejson-3.20.1-cp312-cp312-musllinux_1_2_aarch64.whl", hash = "sha256:fc0f523ce923e7f38eb67804bc80e0a028c76d7868500aa3f59225574b5d0453", size = 150048 }, + { url = "https://files.pythonhosted.org/packages/5e/ea/dd9b3e8e8ed710a66f24a22c16a907c9b539b6f5f45fd8586bd5c231444e/simplejson-3.20.1-cp312-cp312-musllinux_1_2_i686.whl", hash = "sha256:76461ec929282dde4a08061071a47281ad939d0202dc4e63cdd135844e162fbc", size = 151668 }, + { url = "https://files.pythonhosted.org/packages/99/af/ee52a8045426a0c5b89d755a5a70cc821815ef3c333b56fbcad33c4435c0/simplejson-3.20.1-cp312-cp312-musllinux_1_2_ppc64le.whl", hash = "sha256:ab19c2da8c043607bde4d4ef3a6b633e668a7d2e3d56f40a476a74c5ea71949f", size = 158840 }, + { url = "https://files.pythonhosted.org/packages/68/db/ab32869acea6b5de7d75fa0dac07a112ded795d41eaa7e66c7813b17be95/simplejson-3.20.1-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:b2578bedaedf6294415197b267d4ef678fea336dd78ee2a6d2f4b028e9d07be3", size = 154212 }, + { url = "https://files.pythonhosted.org/packages/fa/7a/e3132d454977d75a3bf9a6d541d730f76462ebf42a96fea2621498166f41/simplejson-3.20.1-cp312-cp312-win32.whl", hash = "sha256:339f407373325a36b7fd744b688ba5bae0666b5d340ec6d98aebc3014bf3d8ea", size = 74101 }, + { url = "https://files.pythonhosted.org/packages/bc/5d/4e243e937fa3560107c69f6f7c2eed8589163f5ed14324e864871daa2dd9/simplejson-3.20.1-cp312-cp312-win_amd64.whl", hash = "sha256:627d4486a1ea7edf1f66bb044ace1ce6b4c1698acd1b05353c97ba4864ea2e17", size = 75736 }, + { url = "https://files.pythonhosted.org/packages/c4/03/0f453a27877cb5a5fff16a975925f4119102cc8552f52536b9a98ef0431e/simplejson-3.20.1-cp313-cp313-macosx_10_13_universal2.whl", hash = "sha256:71e849e7ceb2178344998cbe5ade101f1b329460243c79c27fbfc51c0447a7c3", size = 93109 }, + { url = "https://files.pythonhosted.org/packages/74/1f/a729f4026850cabeaff23e134646c3f455e86925d2533463420635ae54de/simplejson-3.20.1-cp313-cp313-macosx_10_13_x86_64.whl", hash = "sha256:b63fdbab29dc3868d6f009a59797cefaba315fd43cd32ddd998ee1da28e50e29", size = 75475 }, + { url = "https://files.pythonhosted.org/packages/e2/14/50a2713fee8ff1f8d655b1a14f4a0f1c0c7246768a1b3b3d12964a4ed5aa/simplejson-3.20.1-cp313-cp313-macosx_11_0_arm64.whl", hash = "sha256:1190f9a3ce644fd50ec277ac4a98c0517f532cfebdcc4bd975c0979a9f05e1fb", size = 75112 }, + { url = "https://files.pythonhosted.org/packages/45/86/ea9835abb646755140e2d482edc9bc1e91997ed19a59fd77ae4c6a0facea/simplejson-3.20.1-cp313-cp313-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:c1336ba7bcb722ad487cd265701ff0583c0bb6de638364ca947bb84ecc0015d1", size = 150245 }, + { url = "https://files.pythonhosted.org/packages/12/b4/53084809faede45da829fe571c65fbda8479d2a5b9c633f46b74124d56f5/simplejson-3.20.1-cp313-cp313-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:e975aac6a5acd8b510eba58d5591e10a03e3d16c1cf8a8624ca177491f7230f0", size = 158465 }, + { url = "https://files.pythonhosted.org/packages/a9/7d/d56579468d1660b3841e1f21c14490d103e33cf911886b22652d6e9683ec/simplejson-3.20.1-cp313-cp313-manylinux_2_5_i686.manylinux1_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:6a6dd11ee282937ad749da6f3b8d87952ad585b26e5edfa10da3ae2536c73078", size = 148514 }, + { url = "https://files.pythonhosted.org/packages/19/e3/874b1cca3d3897b486d3afdccc475eb3a09815bf1015b01cf7fcb52a55f0/simplejson-3.20.1-cp313-cp313-manylinux_2_5_x86_64.manylinux1_x86_64.manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:ab980fcc446ab87ea0879edad41a5c28f2d86020014eb035cf5161e8de4474c6", size = 152262 }, + { url = "https://files.pythonhosted.org/packages/32/84/f0fdb3625292d945c2bd13a814584603aebdb38cfbe5fe9be6b46fe598c4/simplejson-3.20.1-cp313-cp313-musllinux_1_2_aarch64.whl", hash = "sha256:f5aee2a4cb6b146bd17333ac623610f069f34e8f31d2f4f0c1a2186e50c594f0", size = 150164 }, + { url = "https://files.pythonhosted.org/packages/95/51/6d625247224f01eaaeabace9aec75ac5603a42f8ebcce02c486fbda8b428/simplejson-3.20.1-cp313-cp313-musllinux_1_2_i686.whl", hash = "sha256:652d8eecbb9a3b6461b21ec7cf11fd0acbab144e45e600c817ecf18e4580b99e", size = 151795 }, + { url = "https://files.pythonhosted.org/packages/7f/d9/bb921df6b35be8412f519e58e86d1060fddf3ad401b783e4862e0a74c4c1/simplejson-3.20.1-cp313-cp313-musllinux_1_2_ppc64le.whl", hash = "sha256:8c09948f1a486a89251ee3a67c9f8c969b379f6ffff1a6064b41fea3bce0a112", size = 159027 }, + { url = "https://files.pythonhosted.org/packages/03/c5/5950605e4ad023a6621cf4c931b29fd3d2a9c1f36be937230bfc83d7271d/simplejson-3.20.1-cp313-cp313-musllinux_1_2_x86_64.whl", hash = "sha256:cbbd7b215ad4fc6f058b5dd4c26ee5c59f72e031dfda3ac183d7968a99e4ca3a", size = 154380 }, + { url = "https://files.pythonhosted.org/packages/66/ad/b74149557c5ec1e4e4d55758bda426f5d2ec0123cd01a53ae63b8de51fa3/simplejson-3.20.1-cp313-cp313-win32.whl", hash = "sha256:ae81e482476eaa088ef9d0120ae5345de924f23962c0c1e20abbdff597631f87", size = 74102 }, + { url = "https://files.pythonhosted.org/packages/db/a9/25282fdd24493e1022f30b7f5cdf804255c007218b2bfaa655bd7ad34b2d/simplejson-3.20.1-cp313-cp313-win_amd64.whl", hash = "sha256:1b9fd15853b90aec3b1739f4471efbf1ac05066a2c7041bf8db821bb73cd2ddc", size = 75736 }, + { url = "https://files.pythonhosted.org/packages/4b/30/00f02a0a921556dd5a6db1ef2926a1bc7a8bbbfb1c49cfed68a275b8ab2b/simplejson-3.20.1-py3-none-any.whl", hash = "sha256:8a6c1bbac39fa4a79f83cbf1df6ccd8ff7069582a9fd8db1e52cea073bc2c697", size = 57121 }, +] + +[[package]] +name = "six" +version = "1.17.0" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/94/e7/b2c673351809dca68a0e064b6af791aa332cf192da575fd474ed7d6f16a2/six-1.17.0.tar.gz", hash = "sha256:ff70335d468e7eb6ec65b95b99d3a2836546063f63acc5171de367e834932a81", size = 34031 } +wheels = [ + { url = "https://files.pythonhosted.org/packages/b7/ce/149a00dd41f10bc29e5921b496af8b574d8413afcd5e30dfa0ed46c2cc5e/six-1.17.0-py2.py3-none-any.whl", hash = "sha256:4721f391ed90541fddacab5acf947aa0d3dc7d27b2e1e8eda2be8970586c3274", size = 11050 }, +] + +[[package]] +name = "super-collections" +version = "0.5.3" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "hjson" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/b8/05/d1b50919a0d206d77255217d96dea9ab34bd1eb965a21559380c48f9517e/super_collections-0.5.3.tar.gz", hash = "sha256:94c1ec96c0a0d5e8e7d389ed8cde6882ac246940507c5e6b86e91945c2968d46", size = 10178 } +wheels = [ + { url = "https://files.pythonhosted.org/packages/07/6d/58de58c521e7fb79bceb4da90d55250070bb4adfa3c870b82519a561c79d/super_collections-0.5.3-py3-none-any.whl", hash = "sha256:907d35b25dc4070910e8254bf2f5c928348af1cf8a1f1e8259e06c666e902cff", size = 8436 }, +] + +[[package]] +name = "tensorstore" +version = "0.1.76" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "ml-dtypes" }, + { name = "numpy", version = "2.2.6", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version < '3.11'" }, + { name = "numpy", version = "2.3.1", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version >= '3.11'" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/ff/ae/947a9f232de7319b664ed8d278e9e0363e9294da73fd422c687ac4eb070e/tensorstore-0.1.76.tar.gz", hash = "sha256:ed0d565e7a038a84b1b5b5d9f7397caec200b53941d8889f44b7f63dd6abffe7", size = 6869230 } +wheels = [ + { url = "https://files.pythonhosted.org/packages/ca/66/6da79c349c3576836efec0195851bb71fed307dd9855de0692bf3e4df6cb/tensorstore-0.1.76-cp310-cp310-macosx_10_14_x86_64.whl", hash = "sha256:97e9eeab539369b99828c07e1d7da93062da91b65503dafe06d941208b0869d3", size = 15674263 }, + { url = "https://files.pythonhosted.org/packages/24/e7/014f188a5bd2087cdf0df154ee756ca95bae62ba76765f8f180e9dbc4e78/tensorstore-0.1.76-cp310-cp310-macosx_11_0_arm64.whl", hash = "sha256:a9c6f207a0b5f5138f7844307e5cb96587a73e9ba7b5edb6429524cca985e2c3", size = 13601077 }, + { url = "https://files.pythonhosted.org/packages/48/63/38410a20016c6c0b28d9970bcb63762f4df4b62a53eeddb27044deeb4792/tensorstore-0.1.76-cp310-cp310-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:05aae734cfaf5c1356b6f2c56226526607361c6e9aa6751df395dda53c3783b1", size = 17545411 }, + { url = "https://files.pythonhosted.org/packages/ca/83/17fb39326adfee5d7048093ee248b3aa69c47031e62832825e29da81d0b7/tensorstore-0.1.76-cp310-cp310-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:7574f837d8bfccf374795100be23f155eff3040f8b0f2010b1a0b2e1d4d6f791", size = 18923422 }, + { url = "https://files.pythonhosted.org/packages/7a/a1/8932f2871e1f390e29f587c3295f3f00113d1a32a05b0723ef06f0134630/tensorstore-0.1.76-cp310-cp310-win_amd64.whl", hash = "sha256:9c964c7538805867894f6ba4a03dfa57e434b73d0c563d93fcbf6245eb67cc2c", size = 12609199 }, + { url = "https://files.pythonhosted.org/packages/9b/9e/b3d691d14122064e16a3a47c14ce3b1178d749e59b3afec91a8656125c29/tensorstore-0.1.76-cp311-cp311-macosx_10_14_x86_64.whl", hash = "sha256:1c882dcf30049952cb6b183c70bd1922815cdbceca8d4115a7fbeb3b5513f9e4", size = 15675667 }, + { url = "https://files.pythonhosted.org/packages/0c/bb/16d97d8b31912f27019115eb23b7feb0b83bf520858b97aec64064653329/tensorstore-0.1.76-cp311-cp311-macosx_11_0_arm64.whl", hash = "sha256:262b856b21626688cefd11913737a94800b1ba3061d56d70babc439ef69587bc", size = 13602503 }, + { url = "https://files.pythonhosted.org/packages/f7/5a/4b675941a73bc46959f24b3f5a68c246422278022a0e121f9c3f226a7a2b/tensorstore-0.1.76-cp311-cp311-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:daf1c7fb71cd07bfdf37ae4f297c0a6895b011562f4050f5c8f52f5753cc24cc", size = 17548043 }, + { url = "https://files.pythonhosted.org/packages/96/b9/8e306cbccb12ce4c241ac69fb98a4fc1bad5fc0311112f579bc24bee9c42/tensorstore-0.1.76-cp311-cp311-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:b24f21bbd4830822422e984bc023a37ce7db08be02138c01c96870e62d041e7f", size = 18925296 }, + { url = "https://files.pythonhosted.org/packages/9c/48/b542e9a4fa6f82b00e9a7c41c30003c195178fa78f835ea205b346a45baf/tensorstore-0.1.76-cp311-cp311-win_amd64.whl", hash = "sha256:36ba59d99d8279802793405fb8615803ea0e136ad439e6fe0ab3c3d7df22179d", size = 12609617 }, + { url = "https://files.pythonhosted.org/packages/09/37/f2254b4ae1dabd95e258fa3eb4783ac4db4261bb8c90ff9bfe15549d1238/tensorstore-0.1.76-cp312-cp312-macosx_10_14_x86_64.whl", hash = "sha256:b68450983ccad9e7774e81b2fa37daef1b72c774fd939d9eb4065d6aa70e666a", size = 15712650 }, + { url = "https://files.pythonhosted.org/packages/93/3c/1cae56cbbe9610ff48cb2d7c0921a4d4c333a0540918e3b2db08b521c5f6/tensorstore-0.1.76-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:6b7a3856f884279e40f90bad87d0da70869879e124835e650c6b16c80f64fbc4", size = 13624138 }, + { url = "https://files.pythonhosted.org/packages/ba/d2/b92d34a896f608a59dc76c290d4ec9f7d0264a02e4d74864987a6adbd3c9/tensorstore-0.1.76-cp312-cp312-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:8709a98ae0b453eb23525c07372c2be1f6bbd978bba53319f26a1f2a83a77c2a", size = 17538270 }, + { url = "https://files.pythonhosted.org/packages/21/66/142b803541552b02a2fa033b1f48bcb50e1d2df6ac10131aab1857c5141d/tensorstore-0.1.76-cp312-cp312-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:267edea8f1596f2bd67017ff97b7b350bf3f95ff84947a8babadc5e17ca53663", size = 18910782 }, + { url = "https://files.pythonhosted.org/packages/5a/3e/c264cf1435c04fb998a1f30dd1f066deb370b841412f89e1cb36d37ee4fc/tensorstore-0.1.76-cp312-cp312-win_amd64.whl", hash = "sha256:f66ac63d0c63c3336ac4dc61f1f97b6afe8b512e586ddfdbc91f19175787f321", size = 12611059 }, + { url = "https://files.pythonhosted.org/packages/5f/66/1e3b819e1de98b048dad7843f3a814c5e739ead57f511dafb6aa0748f04a/tensorstore-0.1.76-cp313-cp313-macosx_10_14_x86_64.whl", hash = "sha256:a471994b156daa3cadb0e4968e29202fa2e8c7ddcd28d825499bb5637caa0983", size = 15713110 }, + { url = "https://files.pythonhosted.org/packages/58/d3/226344e8822c5e02af929c89bd61964e08980253cda15286a201850eb3b1/tensorstore-0.1.76-cp313-cp313-macosx_11_0_arm64.whl", hash = "sha256:98175dc64935b49467cb7664a431b9a06e9df9b5cab94f9a1fdb24a30b2d69d3", size = 13624514 }, + { url = "https://files.pythonhosted.org/packages/94/9f/2b267c520dbbcf0a5ebc7a3c0a6cf852a445e22c8ea8b0f7450bf6b98783/tensorstore-0.1.76-cp313-cp313-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:c9e30577f1197ea3573102912482dced95e4c6ff72087ffeb99b5d8b496bf81a", size = 17539304 }, + { url = "https://files.pythonhosted.org/packages/1d/9a/9dcc01c8f87047b09602ea16379233b8a308d1d83d5432bf8bc89163ca3e/tensorstore-0.1.76-cp313-cp313-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:20782f833bfa3c59dd3787f657388054c54ee0ab48dad181b360e3e5e81e4c4b", size = 18911982 }, + { url = "https://files.pythonhosted.org/packages/10/45/43d387027b3eac9f09de8bb736b1b432de287fbd807716877fe5fbaeee56/tensorstore-0.1.76-cp313-cp313-win_amd64.whl", hash = "sha256:e84fc11b36fcd55cfd1c5dfc60de9d54d7d95c3de074f4d854914067e82a6740", size = 12610851 }, +] + +[[package]] +name = "termcolor" +version = "3.1.0" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/ca/6c/3d75c196ac07ac8749600b60b03f4f6094d54e132c4d94ebac6ee0e0add0/termcolor-3.1.0.tar.gz", hash = "sha256:6a6dd7fbee581909eeec6a756cff1d7f7c376063b14e4a298dc4980309e55970", size = 14324 } +wheels = [ + { url = "https://files.pythonhosted.org/packages/4f/bd/de8d508070629b6d84a30d01d57e4a65c69aa7f5abe7560b8fad3b50ea59/termcolor-3.1.0-py3-none-any.whl", hash = "sha256:591dd26b5c2ce03b9e43f391264626557873ce1d379019786f99b0c2bee140aa", size = 7684 }, +] + +[[package]] +name = "tomli" +version = "2.2.1" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/18/87/302344fed471e44a87289cf4967697d07e532f2421fdaf868a303cbae4ff/tomli-2.2.1.tar.gz", hash = "sha256:cd45e1dc79c835ce60f7404ec8119f2eb06d38b1deba146f07ced3bbc44505ff", size = 17175 } +wheels = [ + { url = "https://files.pythonhosted.org/packages/43/ca/75707e6efa2b37c77dadb324ae7d9571cb424e61ea73fad7c56c2d14527f/tomli-2.2.1-cp311-cp311-macosx_10_9_x86_64.whl", hash = "sha256:678e4fa69e4575eb77d103de3df8a895e1591b48e740211bd1067378c69e8249", size = 131077 }, + { url = "https://files.pythonhosted.org/packages/c7/16/51ae563a8615d472fdbffc43a3f3d46588c264ac4f024f63f01283becfbb/tomli-2.2.1-cp311-cp311-macosx_11_0_arm64.whl", hash = "sha256:023aa114dd824ade0100497eb2318602af309e5a55595f76b626d6d9f3b7b0a6", size = 123429 }, + { url = "https://files.pythonhosted.org/packages/f1/dd/4f6cd1e7b160041db83c694abc78e100473c15d54620083dbd5aae7b990e/tomli-2.2.1-cp311-cp311-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:ece47d672db52ac607a3d9599a9d48dcb2f2f735c6c2d1f34130085bb12b112a", size = 226067 }, + { url = "https://files.pythonhosted.org/packages/a9/6b/c54ede5dc70d648cc6361eaf429304b02f2871a345bbdd51e993d6cdf550/tomli-2.2.1-cp311-cp311-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:6972ca9c9cc9f0acaa56a8ca1ff51e7af152a9f87fb64623e31d5c83700080ee", size = 236030 }, + { url = "https://files.pythonhosted.org/packages/1f/47/999514fa49cfaf7a92c805a86c3c43f4215621855d151b61c602abb38091/tomli-2.2.1-cp311-cp311-manylinux_2_5_i686.manylinux1_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:c954d2250168d28797dd4e3ac5cf812a406cd5a92674ee4c8f123c889786aa8e", size = 240898 }, + { url = "https://files.pythonhosted.org/packages/73/41/0a01279a7ae09ee1573b423318e7934674ce06eb33f50936655071d81a24/tomli-2.2.1-cp311-cp311-musllinux_1_2_aarch64.whl", hash = "sha256:8dd28b3e155b80f4d54beb40a441d366adcfe740969820caf156c019fb5c7ec4", size = 229894 }, + { url = "https://files.pythonhosted.org/packages/55/18/5d8bc5b0a0362311ce4d18830a5d28943667599a60d20118074ea1b01bb7/tomli-2.2.1-cp311-cp311-musllinux_1_2_i686.whl", hash = "sha256:e59e304978767a54663af13c07b3d1af22ddee3bb2fb0618ca1593e4f593a106", size = 245319 }, + { url = "https://files.pythonhosted.org/packages/92/a3/7ade0576d17f3cdf5ff44d61390d4b3febb8a9fc2b480c75c47ea048c646/tomli-2.2.1-cp311-cp311-musllinux_1_2_x86_64.whl", hash = "sha256:33580bccab0338d00994d7f16f4c4ec25b776af3ffaac1ed74e0b3fc95e885a8", size = 238273 }, + { url = "https://files.pythonhosted.org/packages/72/6f/fa64ef058ac1446a1e51110c375339b3ec6be245af9d14c87c4a6412dd32/tomli-2.2.1-cp311-cp311-win32.whl", hash = "sha256:465af0e0875402f1d226519c9904f37254b3045fc5084697cefb9bdde1ff99ff", size = 98310 }, + { url = "https://files.pythonhosted.org/packages/6a/1c/4a2dcde4a51b81be3530565e92eda625d94dafb46dbeb15069df4caffc34/tomli-2.2.1-cp311-cp311-win_amd64.whl", hash = "sha256:2d0f2fdd22b02c6d81637a3c95f8cd77f995846af7414c5c4b8d0545afa1bc4b", size = 108309 }, + { url = "https://files.pythonhosted.org/packages/52/e1/f8af4c2fcde17500422858155aeb0d7e93477a0d59a98e56cbfe75070fd0/tomli-2.2.1-cp312-cp312-macosx_10_13_x86_64.whl", hash = "sha256:4a8f6e44de52d5e6c657c9fe83b562f5f4256d8ebbfe4ff922c495620a7f6cea", size = 132762 }, + { url = "https://files.pythonhosted.org/packages/03/b8/152c68bb84fc00396b83e7bbddd5ec0bd3dd409db4195e2a9b3e398ad2e3/tomli-2.2.1-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:8d57ca8095a641b8237d5b079147646153d22552f1c637fd3ba7f4b0b29167a8", size = 123453 }, + { url = "https://files.pythonhosted.org/packages/c8/d6/fc9267af9166f79ac528ff7e8c55c8181ded34eb4b0e93daa767b8841573/tomli-2.2.1-cp312-cp312-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:4e340144ad7ae1533cb897d406382b4b6fede8890a03738ff1683af800d54192", size = 233486 }, + { url = "https://files.pythonhosted.org/packages/5c/51/51c3f2884d7bab89af25f678447ea7d297b53b5a3b5730a7cb2ef6069f07/tomli-2.2.1-cp312-cp312-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:db2b95f9de79181805df90bedc5a5ab4c165e6ec3fe99f970d0e302f384ad222", size = 242349 }, + { url = "https://files.pythonhosted.org/packages/ab/df/bfa89627d13a5cc22402e441e8a931ef2108403db390ff3345c05253935e/tomli-2.2.1-cp312-cp312-manylinux_2_5_i686.manylinux1_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:40741994320b232529c802f8bc86da4e1aa9f413db394617b9a256ae0f9a7f77", size = 252159 }, + { url = "https://files.pythonhosted.org/packages/9e/6e/fa2b916dced65763a5168c6ccb91066f7639bdc88b48adda990db10c8c0b/tomli-2.2.1-cp312-cp312-musllinux_1_2_aarch64.whl", hash = "sha256:400e720fe168c0f8521520190686ef8ef033fb19fc493da09779e592861b78c6", size = 237243 }, + { url = "https://files.pythonhosted.org/packages/b4/04/885d3b1f650e1153cbb93a6a9782c58a972b94ea4483ae4ac5cedd5e4a09/tomli-2.2.1-cp312-cp312-musllinux_1_2_i686.whl", hash = "sha256:02abe224de6ae62c19f090f68da4e27b10af2b93213d36cf44e6e1c5abd19fdd", size = 259645 }, + { url = "https://files.pythonhosted.org/packages/9c/de/6b432d66e986e501586da298e28ebeefd3edc2c780f3ad73d22566034239/tomli-2.2.1-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:b82ebccc8c8a36f2094e969560a1b836758481f3dc360ce9a3277c65f374285e", size = 244584 }, + { url = "https://files.pythonhosted.org/packages/1c/9a/47c0449b98e6e7d1be6cbac02f93dd79003234ddc4aaab6ba07a9a7482e2/tomli-2.2.1-cp312-cp312-win32.whl", hash = "sha256:889f80ef92701b9dbb224e49ec87c645ce5df3fa2cc548664eb8a25e03127a98", size = 98875 }, + { url = "https://files.pythonhosted.org/packages/ef/60/9b9638f081c6f1261e2688bd487625cd1e660d0a85bd469e91d8db969734/tomli-2.2.1-cp312-cp312-win_amd64.whl", hash = "sha256:7fc04e92e1d624a4a63c76474610238576942d6b8950a2d7f908a340494e67e4", size = 109418 }, + { url = "https://files.pythonhosted.org/packages/04/90/2ee5f2e0362cb8a0b6499dc44f4d7d48f8fff06d28ba46e6f1eaa61a1388/tomli-2.2.1-cp313-cp313-macosx_10_13_x86_64.whl", hash = "sha256:f4039b9cbc3048b2416cc57ab3bda989a6fcf9b36cf8937f01a6e731b64f80d7", size = 132708 }, + { url = "https://files.pythonhosted.org/packages/c0/ec/46b4108816de6b385141f082ba99e315501ccd0a2ea23db4a100dd3990ea/tomli-2.2.1-cp313-cp313-macosx_11_0_arm64.whl", hash = "sha256:286f0ca2ffeeb5b9bd4fcc8d6c330534323ec51b2f52da063b11c502da16f30c", size = 123582 }, + { url = "https://files.pythonhosted.org/packages/a0/bd/b470466d0137b37b68d24556c38a0cc819e8febe392d5b199dcd7f578365/tomli-2.2.1-cp313-cp313-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:a92ef1a44547e894e2a17d24e7557a5e85a9e1d0048b0b5e7541f76c5032cb13", size = 232543 }, + { url = "https://files.pythonhosted.org/packages/d9/e5/82e80ff3b751373f7cead2815bcbe2d51c895b3c990686741a8e56ec42ab/tomli-2.2.1-cp313-cp313-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:9316dc65bed1684c9a98ee68759ceaed29d229e985297003e494aa825ebb0281", size = 241691 }, + { url = "https://files.pythonhosted.org/packages/05/7e/2a110bc2713557d6a1bfb06af23dd01e7dde52b6ee7dadc589868f9abfac/tomli-2.2.1-cp313-cp313-manylinux_2_5_i686.manylinux1_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:e85e99945e688e32d5a35c1ff38ed0b3f41f43fad8df0bdf79f72b2ba7bc5272", size = 251170 }, + { url = "https://files.pythonhosted.org/packages/64/7b/22d713946efe00e0adbcdfd6d1aa119ae03fd0b60ebed51ebb3fa9f5a2e5/tomli-2.2.1-cp313-cp313-musllinux_1_2_aarch64.whl", hash = "sha256:ac065718db92ca818f8d6141b5f66369833d4a80a9d74435a268c52bdfa73140", size = 236530 }, + { url = "https://files.pythonhosted.org/packages/38/31/3a76f67da4b0cf37b742ca76beaf819dca0ebef26d78fc794a576e08accf/tomli-2.2.1-cp313-cp313-musllinux_1_2_i686.whl", hash = "sha256:d920f33822747519673ee656a4b6ac33e382eca9d331c87770faa3eef562aeb2", size = 258666 }, + { url = "https://files.pythonhosted.org/packages/07/10/5af1293da642aded87e8a988753945d0cf7e00a9452d3911dd3bb354c9e2/tomli-2.2.1-cp313-cp313-musllinux_1_2_x86_64.whl", hash = "sha256:a198f10c4d1b1375d7687bc25294306e551bf1abfa4eace6650070a5c1ae2744", size = 243954 }, + { url = "https://files.pythonhosted.org/packages/5b/b9/1ed31d167be802da0fc95020d04cd27b7d7065cc6fbefdd2f9186f60d7bd/tomli-2.2.1-cp313-cp313-win32.whl", hash = "sha256:d3f5614314d758649ab2ab3a62d4f2004c825922f9e370b29416484086b264ec", size = 98724 }, + { url = "https://files.pythonhosted.org/packages/c7/32/b0963458706accd9afcfeb867c0f9175a741bf7b19cd424230714d722198/tomli-2.2.1-cp313-cp313-win_amd64.whl", hash = "sha256:a38aa0308e754b0e3c67e344754dff64999ff9b513e691d0e786265c93583c69", size = 109383 }, + { url = "https://files.pythonhosted.org/packages/6e/c2/61d3e0f47e2b74ef40a68b9e6ad5984f6241a942f7cd3bbfbdbd03861ea9/tomli-2.2.1-py3-none-any.whl", hash = "sha256:cb55c73c5f4408779d0cf3eef9f762b9c9f147a77de7b258bef0a5628adc85cc", size = 14257 }, +] + +[[package]] +name = "toolz" +version = "1.0.0" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/8a/0b/d80dfa675bf592f636d1ea0b835eab4ec8df6e9415d8cfd766df54456123/toolz-1.0.0.tar.gz", hash = "sha256:2c86e3d9a04798ac556793bced838816296a2f085017664e4995cb40a1047a02", size = 66790 } +wheels = [ + { url = "https://files.pythonhosted.org/packages/03/98/eb27cc78ad3af8e302c9d8ff4977f5026676e130d28dd7578132a457170c/toolz-1.0.0-py3-none-any.whl", hash = "sha256:292c8f1c4e7516bf9086f8850935c799a874039c8bcf959d47b600e4c44a6236", size = 56383 }, +] + +[[package]] +name = "treescope" +version = "0.1.9" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "numpy", version = "2.2.6", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version < '3.11'" }, + { name = "numpy", version = "2.3.1", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version >= '3.11'" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/26/27/80ad254da167e0055d5679aefd224ab08844a4cd55aeee7ef72c999d5fc6/treescope-0.1.9.tar.gz", hash = "sha256:ba6cdbdc9c5b52691d5f3bb4c5d5c7daa5627119acac8640b46d37e6aabe63a6", size = 544385 } +wheels = [ + { url = "https://files.pythonhosted.org/packages/e4/09/b7e7bc5f21313d227e4fb98d2037646457ec06746327c5dd8ffed75e41e1/treescope-0.1.9-py3-none-any.whl", hash = "sha256:68677013a9f0228212fccf835f3fb037be07ae8b4c5f6f58eefab11198f83cf7", size = 182162 }, +] + +[[package]] +name = "typing-extensions" +version = "4.14.1" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/98/5a/da40306b885cc8c09109dc2e1abd358d5684b1425678151cdaed4731c822/typing_extensions-4.14.1.tar.gz", hash = "sha256:38b39f4aeeab64884ce9f74c94263ef78f3c22467c8724005483154c26648d36", size = 107673 } +wheels = [ + { url = "https://files.pythonhosted.org/packages/b5/00/d631e67a838026495268c2f6884f3711a15a9a2a96cd244fdaea53b823fb/typing_extensions-4.14.1-py3-none-any.whl", hash = "sha256:d1e1e3b58374dc93031d6eda2420a48ea44a36c2b4766a4fdeb3710755731d76", size = 43906 }, +] + +[[package]] +name = "urllib3" +version = "2.5.0" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/15/22/9ee70a2574a4f4599c47dd506532914ce044817c7752a79b6a51286319bc/urllib3-2.5.0.tar.gz", hash = "sha256:3fc47733c7e419d4bc3f6b3dc2b4f890bb743906a30d56ba4a5bfa4bbff92760", size = 393185 } +wheels = [ + { url = "https://files.pythonhosted.org/packages/a7/c2/fe1e52489ae3122415c51f387e221dd0773709bad6c6cdaa599e8a2c5185/urllib3-2.5.0-py3-none-any.whl", hash = "sha256:e6b01673c0fa6a13e374b50871808eb3bf7046c4b125b216f6bf1cc604cff0dc", size = 129795 }, +] + +[[package]] +name = "virtualenv" +version = "20.31.2" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "distlib" }, + { name = "filelock" }, + { name = "platformdirs" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/56/2c/444f465fb2c65f40c3a104fd0c495184c4f2336d65baf398e3c75d72ea94/virtualenv-20.31.2.tar.gz", hash = "sha256:e10c0a9d02835e592521be48b332b6caee6887f332c111aa79a09b9e79efc2af", size = 6076316 } +wheels = [ + { url = "https://files.pythonhosted.org/packages/f3/40/b1c265d4b2b62b58576588510fc4d1fe60a86319c8de99fd8e9fec617d2c/virtualenv-20.31.2-py3-none-any.whl", hash = "sha256:36efd0d9650ee985f0cad72065001e66d49a6f24eb44d98980f630686243cf11", size = 6057982 }, +] + +[[package]] +name = "wadler-lindig" +version = "0.1.7" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/1e/67/cbae4bf7683a64755c2c1778c418fea96d00e34395bb91743f08bd951571/wadler_lindig-0.1.7.tar.gz", hash = "sha256:81d14d3fe77d441acf3ebd7f4aefac20c74128bf460e84b512806dccf7b2cd55", size = 15842 } +wheels = [ + { url = "https://files.pythonhosted.org/packages/8d/96/04e7b441807b26b794da5b11e59ed7f83b2cf8af202bd7eba8ad2fa6046e/wadler_lindig-0.1.7-py3-none-any.whl", hash = "sha256:e3ec83835570fd0a9509f969162aeb9c65618f998b1f42918cfc8d45122fe953", size = 20516 }, +] + +[[package]] +name = "watchdog" +version = "6.0.0" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/db/7d/7f3d619e951c88ed75c6037b246ddcf2d322812ee8ea189be89511721d54/watchdog-6.0.0.tar.gz", hash = "sha256:9ddf7c82fda3ae8e24decda1338ede66e1c99883db93711d8fb941eaa2d8c282", size = 131220 } +wheels = [ + { url = "https://files.pythonhosted.org/packages/0c/56/90994d789c61df619bfc5ce2ecdabd5eeff564e1eb47512bd01b5e019569/watchdog-6.0.0-cp310-cp310-macosx_10_9_universal2.whl", hash = "sha256:d1cdb490583ebd691c012b3d6dae011000fe42edb7a82ece80965b42abd61f26", size = 96390 }, + { url = "https://files.pythonhosted.org/packages/55/46/9a67ee697342ddf3c6daa97e3a587a56d6c4052f881ed926a849fcf7371c/watchdog-6.0.0-cp310-cp310-macosx_10_9_x86_64.whl", hash = "sha256:bc64ab3bdb6a04d69d4023b29422170b74681784ffb9463ed4870cf2f3e66112", size = 88389 }, + { url = "https://files.pythonhosted.org/packages/44/65/91b0985747c52064d8701e1075eb96f8c40a79df889e59a399453adfb882/watchdog-6.0.0-cp310-cp310-macosx_11_0_arm64.whl", hash = "sha256:c897ac1b55c5a1461e16dae288d22bb2e412ba9807df8397a635d88f671d36c3", size = 89020 }, + { url = "https://files.pythonhosted.org/packages/e0/24/d9be5cd6642a6aa68352ded4b4b10fb0d7889cb7f45814fb92cecd35f101/watchdog-6.0.0-cp311-cp311-macosx_10_9_universal2.whl", hash = "sha256:6eb11feb5a0d452ee41f824e271ca311a09e250441c262ca2fd7ebcf2461a06c", size = 96393 }, + { url = "https://files.pythonhosted.org/packages/63/7a/6013b0d8dbc56adca7fdd4f0beed381c59f6752341b12fa0886fa7afc78b/watchdog-6.0.0-cp311-cp311-macosx_10_9_x86_64.whl", hash = "sha256:ef810fbf7b781a5a593894e4f439773830bdecb885e6880d957d5b9382a960d2", size = 88392 }, + { url = "https://files.pythonhosted.org/packages/d1/40/b75381494851556de56281e053700e46bff5b37bf4c7267e858640af5a7f/watchdog-6.0.0-cp311-cp311-macosx_11_0_arm64.whl", hash = "sha256:afd0fe1b2270917c5e23c2a65ce50c2a4abb63daafb0d419fde368e272a76b7c", size = 89019 }, + { url = "https://files.pythonhosted.org/packages/39/ea/3930d07dafc9e286ed356a679aa02d777c06e9bfd1164fa7c19c288a5483/watchdog-6.0.0-cp312-cp312-macosx_10_13_universal2.whl", hash = "sha256:bdd4e6f14b8b18c334febb9c4425a878a2ac20efd1e0b231978e7b150f92a948", size = 96471 }, + { url = "https://files.pythonhosted.org/packages/12/87/48361531f70b1f87928b045df868a9fd4e253d9ae087fa4cf3f7113be363/watchdog-6.0.0-cp312-cp312-macosx_10_13_x86_64.whl", hash = "sha256:c7c15dda13c4eb00d6fb6fc508b3c0ed88b9d5d374056b239c4ad1611125c860", size = 88449 }, + { url = "https://files.pythonhosted.org/packages/5b/7e/8f322f5e600812e6f9a31b75d242631068ca8f4ef0582dd3ae6e72daecc8/watchdog-6.0.0-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:6f10cb2d5902447c7d0da897e2c6768bca89174d0c6e1e30abec5421af97a5b0", size = 89054 }, + { url = "https://files.pythonhosted.org/packages/68/98/b0345cabdce2041a01293ba483333582891a3bd5769b08eceb0d406056ef/watchdog-6.0.0-cp313-cp313-macosx_10_13_universal2.whl", hash = "sha256:490ab2ef84f11129844c23fb14ecf30ef3d8a6abafd3754a6f75ca1e6654136c", size = 96480 }, + { url = "https://files.pythonhosted.org/packages/85/83/cdf13902c626b28eedef7ec4f10745c52aad8a8fe7eb04ed7b1f111ca20e/watchdog-6.0.0-cp313-cp313-macosx_10_13_x86_64.whl", hash = "sha256:76aae96b00ae814b181bb25b1b98076d5fc84e8a53cd8885a318b42b6d3a5134", size = 88451 }, + { url = "https://files.pythonhosted.org/packages/fe/c4/225c87bae08c8b9ec99030cd48ae9c4eca050a59bf5c2255853e18c87b50/watchdog-6.0.0-cp313-cp313-macosx_11_0_arm64.whl", hash = "sha256:a175f755fc2279e0b7312c0035d52e27211a5bc39719dd529625b1930917345b", size = 89057 }, + { url = "https://files.pythonhosted.org/packages/30/ad/d17b5d42e28a8b91f8ed01cb949da092827afb9995d4559fd448d0472763/watchdog-6.0.0-pp310-pypy310_pp73-macosx_10_15_x86_64.whl", hash = "sha256:c7ac31a19f4545dd92fc25d200694098f42c9a8e391bc00bdd362c5736dbf881", size = 87902 }, + { url = "https://files.pythonhosted.org/packages/5c/ca/c3649991d140ff6ab67bfc85ab42b165ead119c9e12211e08089d763ece5/watchdog-6.0.0-pp310-pypy310_pp73-macosx_11_0_arm64.whl", hash = "sha256:9513f27a1a582d9808cf21a07dae516f0fab1cf2d7683a742c498b93eedabb11", size = 88380 }, + { url = "https://files.pythonhosted.org/packages/a9/c7/ca4bf3e518cb57a686b2feb4f55a1892fd9a3dd13f470fca14e00f80ea36/watchdog-6.0.0-py3-none-manylinux2014_aarch64.whl", hash = "sha256:7607498efa04a3542ae3e05e64da8202e58159aa1fa4acddf7678d34a35d4f13", size = 79079 }, + { url = "https://files.pythonhosted.org/packages/5c/51/d46dc9332f9a647593c947b4b88e2381c8dfc0942d15b8edc0310fa4abb1/watchdog-6.0.0-py3-none-manylinux2014_armv7l.whl", hash = "sha256:9041567ee8953024c83343288ccc458fd0a2d811d6a0fd68c4c22609e3490379", size = 79078 }, + { url = "https://files.pythonhosted.org/packages/d4/57/04edbf5e169cd318d5f07b4766fee38e825d64b6913ca157ca32d1a42267/watchdog-6.0.0-py3-none-manylinux2014_i686.whl", hash = "sha256:82dc3e3143c7e38ec49d61af98d6558288c415eac98486a5c581726e0737c00e", size = 79076 }, + { url = "https://files.pythonhosted.org/packages/ab/cc/da8422b300e13cb187d2203f20b9253e91058aaf7db65b74142013478e66/watchdog-6.0.0-py3-none-manylinux2014_ppc64.whl", hash = "sha256:212ac9b8bf1161dc91bd09c048048a95ca3a4c4f5e5d4a7d1b1a7d5752a7f96f", size = 79077 }, + { url = "https://files.pythonhosted.org/packages/2c/3b/b8964e04ae1a025c44ba8e4291f86e97fac443bca31de8bd98d3263d2fcf/watchdog-6.0.0-py3-none-manylinux2014_ppc64le.whl", hash = "sha256:e3df4cbb9a450c6d49318f6d14f4bbc80d763fa587ba46ec86f99f9e6876bb26", size = 79078 }, + { url = "https://files.pythonhosted.org/packages/62/ae/a696eb424bedff7407801c257d4b1afda455fe40821a2be430e173660e81/watchdog-6.0.0-py3-none-manylinux2014_s390x.whl", hash = "sha256:2cce7cfc2008eb51feb6aab51251fd79b85d9894e98ba847408f662b3395ca3c", size = 79077 }, + { url = "https://files.pythonhosted.org/packages/b5/e8/dbf020b4d98251a9860752a094d09a65e1b436ad181faf929983f697048f/watchdog-6.0.0-py3-none-manylinux2014_x86_64.whl", hash = "sha256:20ffe5b202af80ab4266dcd3e91aae72bf2da48c0d33bdb15c66658e685e94e2", size = 79078 }, + { url = "https://files.pythonhosted.org/packages/07/f6/d0e5b343768e8bcb4cda79f0f2f55051bf26177ecd5651f84c07567461cf/watchdog-6.0.0-py3-none-win32.whl", hash = "sha256:07df1fdd701c5d4c8e55ef6cf55b8f0120fe1aef7ef39a1c6fc6bc2e606d517a", size = 79065 }, + { url = "https://files.pythonhosted.org/packages/db/d9/c495884c6e548fce18a8f40568ff120bc3a4b7b99813081c8ac0c936fa64/watchdog-6.0.0-py3-none-win_amd64.whl", hash = "sha256:cbafb470cf848d93b5d013e2ecb245d4aa1c8fd0504e863ccefa32445359d680", size = 79070 }, + { url = "https://files.pythonhosted.org/packages/33/e8/e40370e6d74ddba47f002a32919d91310d6074130fe4e17dabcafc15cbf1/watchdog-6.0.0-py3-none-win_ia64.whl", hash = "sha256:a1914259fa9e1454315171103c6a30961236f508b9b623eae470268bbcc6a22f", size = 79067 }, +] + +[[package]] +name = "wcmatch" +version = "10.1" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "bracex" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/79/3e/c0bdc27cf06f4e47680bd5803a07cb3dfd17de84cde92dd217dcb9e05253/wcmatch-10.1.tar.gz", hash = "sha256:f11f94208c8c8484a16f4f48638a85d771d9513f4ab3f37595978801cb9465af", size = 117421 } +wheels = [ + { url = "https://files.pythonhosted.org/packages/eb/d8/0d1d2e9d3fabcf5d6840362adcf05f8cf3cd06a73358140c3a97189238ae/wcmatch-10.1-py3-none-any.whl", hash = "sha256:5848ace7dbb0476e5e55ab63c6bbd529745089343427caa5537f230cc01beb8a", size = 39854 }, +] + +[[package]] +name = "zipp" +version = "3.23.0" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/e3/02/0f2892c661036d50ede074e376733dca2ae7c6eb617489437771209d4180/zipp-3.23.0.tar.gz", hash = "sha256:a07157588a12518c9d4034df3fbbee09c814741a33ff63c05fa29d26a2404166", size = 25547 } +wheels = [ + { url = "https://files.pythonhosted.org/packages/2e/54/647ade08bf0db230bfea292f893923872fd20be6ac6f53b2b936ba839d75/zipp-3.23.0-py3-none-any.whl", hash = "sha256:071652d6115ed432f5ce1d34c336c0adfd6a884660d1e9712a256d3d3bd4b14e", size = 10276 }, +] commit 5801691e9802212610f779535450e73867715e88 Date: 2025-07-08T08:41:13-07:00 Use JAX AbstractMesh (#159) * use abstract mesh * Handle empty abstract mesh diff --git a/src/haliax/_src/state_dict.py b/src/haliax/_src/state_dict.py index 505bcf9..986acde 100644 --- a/src/haliax/_src/state_dict.py +++ b/src/haliax/_src/state_dict.py @@ -197,7 +197,7 @@ def from_state_dict(tree: T, state_dict: StateDict, prefix: Optional[str] = None if isinstance(array, np.ndarray): mesh = partitioning._get_mesh() # TODO: modernize this - if mesh.devices.size > 1: # this happens with the default mesh + if jax.device_count() > 1: # this happens with the default mesh pspec = partitioning.pspec_for_axis(tree.axes) sharding = jax.sharding.NamedSharding(mesh, pspec) array = jax.make_array_from_callback(tree.array.shape, sharding, lambda indices: array[indices]) diff --git a/src/haliax/partitioning.py b/src/haliax/partitioning.py index 4043671..20ba373 100644 --- a/src/haliax/partitioning.py +++ b/src/haliax/partitioning.py @@ -10,7 +10,24 @@ import equinox as eqx import jax from equinox import is_array, module_update_wrapper from jax.lax import with_sharding_constraint -from jax.sharding import Mesh, NamedSharding, PartitionSpec, SingleDeviceSharding +from jax.sharding import ( + Mesh, + NamedSharding, + PartitionSpec, + SingleDeviceSharding, +) + +try: # jax>=0.4.26 + from jax.sharding import AbstractMesh, get_abstract_mesh +except Exception: # pragma: no cover - older JAX versions + AbstractMesh = Mesh # type: ignore[misc,assignment] + def get_abstract_mesh(): # type: ignore[dead-code] + try: + from jax.interpreters.pxla import thread_resources + except Exception: + from jax.experimental.maps import thread_resources + + return thread_resources.env.physical_mesh from jaxtyping import PyTree import haliax.tree_util as htu @@ -604,10 +621,25 @@ def round_axis_for_partitioning(axis: Axis, mapping: Optional[ResourceMapping] = return Axis(axis.name, new_size) -def _get_mesh() -> Mesh: +def _get_mesh() -> Mesh | AbstractMesh: + """Return the current mesh. + + On newer versions of JAX this prefers ``get_abstract_mesh`` which does not + capture concrete devices. If no abstract mesh is currently active we fall + back to the concrete mesh used by ``Mesh``'s context manager so existing + code continues to work. + """ + + try: # jax>=0.4.26 + mesh = get_abstract_mesh() + if not getattr(mesh, "empty", False): + return mesh + except Exception: # pragma: no cover - older JAX versions + pass + try: from jax.interpreters.pxla import thread_resources - except ImportError: + except Exception: # pragma: no cover - jax<0.4 from jax.experimental.maps import thread_resources return thread_resources.env.physical_mesh commit 998b0539b37272cdc98375928bff3684bcac1fb6 Date: 2025-07-08T13:26:17-07:00 wip (#162) diff --git a/src/haliax/core.py b/src/haliax/core.py index 4e93715..3bedda1 100644 --- a/src/haliax/core.py +++ b/src/haliax/core.py @@ -27,6 +27,7 @@ from .axis import ( PartialShapeDict, ShapeDict, axis_name, + axis_spec_to_shape_dict, axis_spec_to_tuple, dslice, eliminate_axes, @@ -1679,7 +1680,7 @@ def broadcast_to( all_axes = to_add + a.axes if enforce_no_extra_axes and len(all_axes) != len(axes): - raise ValueError(f"Cannot broadcast {a} to {axes}: extra axes present") + raise ValueError(f"Cannot broadcast {a.shape} to {axis_spec_to_shape_dict(axes)}: extra axes present") extra_axes = tuple(ax for ax in a.axes if ax not in axes) commit 8ef37a76cfef9711012e6493806a50e6561deaab Date: 2025-07-08T13:39:26-07:00 Fix Levanter tests (#164) * wip * chatgpt tells me this is nicer diff --git a/.github/workflows/run_quick_levanter_tests.yaml b/.github/workflows/run_quick_levanter_tests.yaml index 68ec21c..212ce4d 100644 --- a/.github/workflows/run_quick_levanter_tests.yaml +++ b/.github/workflows/run_quick_levanter_tests.yaml @@ -1,38 +1,48 @@ -name: Run Levanter Tests +name: Run Levanter & Haliax Tests -on: [pull_request] +on: + pull_request: + branches: [main] jobs: - build: - + test: runs-on: ubuntu-latest - + strategy: + matrix: + python-version: [3.10, 3.11] steps: - - uses: actions/checkout@v3 - - name: Set up Python 3.10.11 + - name: Checkout repository + uses: actions/checkout@v3 + + - name: Cache pip and uv artifacts + uses: actions/cache@v3 + with: + path: | + ~/.cache/pip + ~/.cache/uv + key: ${{ runner.os }}-pip-uv-${{ matrix.python-version }}-${{ hashFiles('**/requirements.lock', '**/uv.lock') }} + restore-keys: | + ${{ runner.os }}-pip-uv-${{ matrix.python-version }}- + + - name: Set up Python ${{ matrix.python-version }} uses: actions/setup-python@v4 with: - python-version: 3.10.11 - - name: Install dependencies - run: | - python -m pip install --upgrade pip - pip install flake8 pytest - pip install "jax[cpu]==0.5.3" "jaxlib[cpu]==0.5.3" .[dev] + python-version: ${{ matrix.python-version }} - - name: Install Levanter from source + - name: Install uv and sync dependencies run: | - cd .. - git clone https://github.com/stanford-crfm/levanter.git - cd levanter - pip install -e .[tests] - pip install -r tests/requirements.txt - # i don't know why this is necessary - pip install tensorboardX - - name: Install Haliax on top + pip install uv + uv venv .venv + uv sync + + - name: Install Levanter and Haliax in editable mode run: | - # install second since levanter will install a built version of haliax - cd ../haliax - - name: Test levanter with pytest + uv pip install -e .[tests] + uv pip install -e ../haliax + + - name: Run pytest suite + env: + XLA_FLAGS: --xla_force_host_platform_device_count=8 + VIRTUAL_ENV: ${{ github.workspace }}/.venv run: | - cd ../levanter - XLA_FLAGS=--xla_force_host_platform_device_count=8 PYTHONPATH=tests:src:../src pytest tests -m "not entry and not slow" + pytest tests -m "not entry and not slow" commit 9d1f650cd97420ab33f960e8717d409ce493962e Date: 2025-07-08T14:54:57-07:00 Fix levanter tests for UV (#165) * wip * chatgpt tells me this is nicer * lol * grrr diff --git a/.github/workflows/run_quick_levanter_tests.yaml b/.github/workflows/run_quick_levanter_tests.yaml index 212ce4d..a235ff1 100644 --- a/.github/workflows/run_quick_levanter_tests.yaml +++ b/.github/workflows/run_quick_levanter_tests.yaml @@ -9,7 +9,7 @@ jobs: runs-on: ubuntu-latest strategy: matrix: - python-version: [3.10, 3.11] + python-version: ["3.10", "3.11"] steps: - name: Checkout repository uses: actions/checkout@v3 @@ -39,10 +39,11 @@ jobs: run: | uv pip install -e .[tests] uv pip install -e ../haliax + uv pip install pytest - name: Run pytest suite env: XLA_FLAGS: --xla_force_host_platform_device_count=8 VIRTUAL_ENV: ${{ github.workspace }}/.venv run: | - pytest tests -m "not entry and not slow" + uv run pytest tests -m "not entry and not slow" commit 6bc182e90c753a0bcceeadfa6f4951572dd1f4f0 Date: 2025-07-08T14:55:26-07:00 Replace deprecated static_field (#166) diff --git a/src/haliax/nn/dropout.py b/src/haliax/nn/dropout.py index ad1da1e..9c8f38a 100644 --- a/src/haliax/nn/dropout.py +++ b/src/haliax/nn/dropout.py @@ -61,8 +61,8 @@ class Dropout(eqx.Module): """ # key difference from equinox: these are static fields - pdrop: float = eqx.static_field() - broadcast_axes: Optional[AxisSpec] = eqx.static_field() + pdrop: float = eqx.field(static=True) + broadcast_axes: Optional[AxisSpec] = eqx.field(static=True) inference: bool = False # note: not static def __init__( diff --git a/src/haliax/nn/embedding.py b/src/haliax/nn/embedding.py index 21b2aa5..cc2733b 100644 --- a/src/haliax/nn/embedding.py +++ b/src/haliax/nn/embedding.py @@ -17,8 +17,8 @@ class Embedding(eqx.Module): weight: NamedArray # axes - Vocab: Axis = eqx.static_field() - Embed: AxisSpec = eqx.static_field() + Vocab: Axis = eqx.field(static=True) + Embed: AxisSpec = eqx.field(static=True) @staticmethod def init(Vocab: Axis, Embed: AxisSpec, *, init_scale: float = 1, key, initializer_range: Optional[float] = None): diff --git a/src/haliax/nn/linear.py b/src/haliax/nn/linear.py index 736293c..c5a1809 100644 --- a/src/haliax/nn/linear.py +++ b/src/haliax/nn/linear.py @@ -28,8 +28,8 @@ class Linear(ModuleWithStateDictSerialization): weight: NamedArray bias: Optional[NamedArray] - In: AxisSpec = eqx.static_field() - Out: AxisSpec = eqx.static_field() + In: AxisSpec = eqx.field(static=True) + Out: AxisSpec = eqx.field(static=True) dot_general: DotGeneralOp = eqx.field(default_factory=DotGeneralOp.default) @staticmethod @@ -140,9 +140,9 @@ class MoELinear(eqx.Module): weight: NamedArray bias: Optional[NamedArray] - Experts: AxisSpec = eqx.static_field() - In: Axis = eqx.static_field() - Out: Axis = eqx.static_field() + Experts: AxisSpec = eqx.field(static=True) + In: Axis = eqx.field(static=True) + Out: Axis = eqx.field(static=True) # TODO: support quanitization for ragged_dot? # dot_general: DotGeneralOp = eqx.field(default_factory=DotGeneralOp.default) diff --git a/src/haliax/nn/normalization.py b/src/haliax/nn/normalization.py index 9f684b8..28294e0 100644 --- a/src/haliax/nn/normalization.py +++ b/src/haliax/nn/normalization.py @@ -20,10 +20,10 @@ A = TypeVar("A", Scalar, NamedArray, jnp.ndarray) class LayerNormBase(ModuleWithStateDictSerialization): - axis: AxisSpec = eqx.static_field() + axis: AxisSpec = eqx.field(static=True) weight: Optional[NamedArray] bias: Optional[NamedArray] - eps: float = eqx.static_field(default=1e-5) + eps: float = eqx.field(default=1e-5, static=True) dtype: Optional[jnp.dtype] = eqx.field(default=None, static=True) @abstractmethod diff --git a/src/haliax/nn/scan.py b/src/haliax/nn/scan.py index ba8278c..97401a0 100644 --- a/src/haliax/nn/scan.py +++ b/src/haliax/nn/scan.py @@ -90,8 +90,8 @@ class BlockSeq(ModuleWithStateDictSerialization, Generic[M]): """ blocks: Sequence[M] - Block: Axis = eqx.static_field() - gradient_checkpointing: ScanCheckpointPolicy = eqx.static_field() + Block: Axis = eqx.field(static=True) + gradient_checkpointing: ScanCheckpointPolicy = eqx.field(static=True) @classmethod def init( @@ -279,8 +279,8 @@ class Stacked(ModuleWithStateDictSerialization, Generic[M]): # TODO: we can probably make this module support pipeline parallelism, but that's a whole project in itself stacked: M - Block: Axis = eqx.static_field() - gradient_checkpointing: ScanCheckpointPolicy = eqx.static_field() + Block: Axis = eqx.field(static=True) + gradient_checkpointing: ScanCheckpointPolicy = eqx.field(static=True) @classmethod def init( commit be87443d026f8aa25b68582a34a51f3c76d1460a Date: 2025-07-08T14:56:39-07:00 Set num_devices during tests in agents.md (#163) * use uv in tests, fix agents.md env variable * uv lock commit 99fd2bb10945fc89108ca54e13e8f9af993c8889 Date: 2025-07-10T14:54:34-07:00 scan_via etc (#168) * wip * chatgpt tells me this is nicer * lol * grrr * better type * better type * multiarg scan_via and fold_via * Add fold_via and scan_via to BlockSeq and BlockFoldable (#167) * vmap_via and fix vmap * remove deprecated __jax_array__ and associated fallout diff --git a/docs/scan.md b/docs/scan.md index 1a70c98..f6809dd 100644 --- a/docs/scan.md +++ b/docs/scan.md @@ -458,7 +458,9 @@ We also provide a way to create a sequence of layers that can be applied to a se same interface as [haliax.nn.Stacked][], but with a different implementation. This is the [haliax.nn.BlockSeq][] module. BlockSeq implements those for loops directly, rather than using [haliax.fold][] or [haliax.scan][]. -[haliax.nn.scan.BlockFoldable][] is an interface that both [haliax.nn.Stacked][] and [haliax.nn.BlockSeq][] implement. +[haliax.nn.scan.BlockFoldable][] is an interface that both [haliax.nn.Stacked][] and [haliax.nn.BlockSeq][] implement. It +exposes the usual ``fold`` and ``scan`` methods as well as helpers ``fold_via`` and ``scan_via`` which return +callables that perform the respective operations using a custom block function. ## API diff --git a/src/haliax/core.py b/src/haliax/core.py index 3bedda1..c0a968a 100644 --- a/src/haliax/core.py +++ b/src/haliax/core.py @@ -241,15 +241,15 @@ class NamedArray(metaclass=NamedArrayMeta): raise ValueError(f"Expected scalar, got {self.array.ndim}-dimensional array") return self.array - def __jax_array__(self): - if self.ndim == 0: - return self.array - else: - raise ValueError( - "Only scalar NamedArrays can be implicitly converted to jax arrays, but " - f"got {self.shape} array. This error typically occurs when you pass a " - "NamedArray to a plain jax.numpy function. Please use `x.array` instead." - ) + # def __jax_array__(self): + # if self.ndim == 0: + # return self.array + # else: + # raise ValueError( + # "Only scalar NamedArrays can be implicitly converted to jax arrays, but " + # f"got {self.shape} array. This error typically occurs when you pass a " + # "NamedArray to a plain jax.numpy function. Please use `x.array` instead." + # ) @ft.cached_property def shape(self) -> Dict[str, int]: @@ -1787,12 +1787,22 @@ def broadcast_arrays_and_return_axes( """ if len(arrays) == 0: return ((), ()) + elif len(arrays) == 1: + a = arrays[0] + if a is None: + return (None,), () + if isinstance(a, NamedArray): + return (a,), a.axes + return (named(jnp.asarray(a), ()), ), () # sort the arrays by size, so that we use the biggest ones to broadcast the others # need to hold on to the order so we can return the arrays in the same order actual_arrays = [x for x in arrays if isinstance(x, NamedArray)] size_order = sorted(range(len(actual_arrays)), key=lambda i: actual_arrays[i].size, reverse=True) all_axes = [actual_arrays[i].axes for i in size_order] + if len(all_axes) == 0: + return (arrays, ()) + full_axes = ft.reduce(lambda a, b: _broadcast_axes(a, b, require_subset) if a is not None else None, all_axes) # type: ignore if full_axes is None: raise ValueError(f"Cannot broadcast arrays {arrays}: no subset relationship") diff --git a/src/haliax/nn/attention.py b/src/haliax/nn/attention.py index 447ad50..60e6a28 100644 --- a/src/haliax/nn/attention.py +++ b/src/haliax/nn/attention.py @@ -155,7 +155,7 @@ def combine_masks_or(mask1: Optional[NamedArray], mask2: Optional[NamedArray]) - return mask1 | mask2.broadcast_axis(mask1.axes) -def causal_mask(QPos: Axis, KPos: Axis, q_start: int = 0, k_start: int = 0) -> NamedArray: +def causal_mask(QPos: Axis, KPos: Axis, q_start: int | NamedArray = 0, k_start: int | NamedArray= 0) -> NamedArray: """ Creates a materialized causal mask for attention. @@ -163,7 +163,18 @@ def causal_mask(QPos: Axis, KPos: Axis, q_start: int = 0, k_start: int = 0) -> N :param KPos: Axis of key sequence length :return: NamedArray of shape (QPos, KPos) """ - return haliax.arange(QPos, start=q_start) >= haliax.arange(KPos, start=k_start).broadcast_axis(QPos) + # if q_start is a named array, we vmap the arange + if isinstance(q_start, NamedArray): + q_range = haliax.vmap(haliax.arange, q_start.axes)(QPos, start=q_start) + else: + q_range = haliax.arange(QPos, start=q_start) + + if isinstance(k_start, NamedArray): + k_range = haliax.vmap(haliax.arange, k_start.axes)(KPos, start=k_start) + else: + k_range = haliax.arange(KPos, start=k_start) + + return q_range >= k_range.broadcast_axis(QPos) def prefix_lm_mask(QSeqLen: Axis, KSeqLen: Axis, prefix_len: int, q_start: int = 0, k_start: int = 0) -> NamedArray: diff --git a/src/haliax/nn/scan.py b/src/haliax/nn/scan.py index 97401a0..4a77f56 100644 --- a/src/haliax/nn/scan.py +++ b/src/haliax/nn/scan.py @@ -2,7 +2,8 @@ import dataclasses import functools import re import warnings -from typing import Any, Callable, Dict, Generic, Optional, Protocol, Sequence, Type, TypeVar, cast, overload, ParamSpec +from typing import Any, Callable, Concatenate, Dict, Generic, Optional, Protocol, Sequence, Type, TypeVar, cast, \ + overload, ParamSpec import equinox as eqx import jax @@ -27,13 +28,18 @@ CarryT = TypeVar("CarryT") OutputT_co = TypeVar("OutputT_co", covariant=True) P = ParamSpec("P") -class FoldFunction(Protocol[M_contra, CarryT]): - def __call__(self, module: M_contra, carry: CarryT) -> CarryT: +class FoldFunction(Protocol[M_contra, P, CarryT]): + def __call__(self, module: M_contra, carry: CarryT, *args: P.args, **kwargs: P.kwargs) -> CarryT: ... -class ScanFunction(Protocol[M_contra, CarryT, OutputT_co]): - def __call__(self, module: M_contra, carry: CarryT) -> tuple[CarryT, OutputT_co]: +class ScanFunction(Protocol[M_contra, CarryT, P, OutputT_co]): + def __call__(self, module: M_contra, carry: CarryT, *args: P.args, **kwargs: P.kwargs) -> tuple[CarryT, OutputT_co]: + ... + + +class VmapFunction(Protocol[M_contra, P, OutputT_co]): + def __call__(self, module: M_contra, *args: P.args, **kwargs: P.kwargs) -> OutputT_co: ... @@ -43,12 +49,13 @@ class ModuleInit(Protocol[M_co]): class BlockFoldable(Protocol[M]): - """ - A superclass for [haliax.nn.Stacked][] and [haliax.nn.BlockSeq][] that exposes the fold and scan methods, as - well as a few other methods that are useful for these modules. + """Common interface for :class:`~haliax.nn.Stacked` and :class:`~haliax.nn.BlockSeq`. - This is a protocol, so you can use it as a type hint for a function that takes a Stacked or BlockSeq. - Equinox modules can't directly inherit from Protocols, but you can use it as a type hint. + The interface exposes the :py:meth:`fold` and :py:meth:`scan` methods along with the helper + methods :py:meth:`fold_via`, :py:meth:`scan_via`, and :py:meth:`vmap_via`. + + This is a protocol, so you can use it as a type hint for a function that takes a ``Stacked`` or ``BlockSeq``. + Equinox modules can't directly inherit from ``Protocol`` classes, but you can use it as a type hint. """ Block: Axis @@ -70,6 +77,39 @@ class BlockFoldable(Protocol[M]): def fold(self, init: T, *args, **kwargs) -> T: ... + @overload + def fold_via(self, fn: FoldFunction[M, P, CarryT]) -> Callable[Concatenate[CarryT, P], CarryT]: + ... + + @overload + def fold_via(self, fn: Callable[[M, CarryT], CarryT]) -> Callable[[CarryT], CarryT]: + ... + + def fold_via(self, fn: Callable[..., CarryT]) -> Callable[Concatenate[CarryT, P], CarryT]: + ... + + @overload + def scan_via(self, fn: ScanFunction[M, CarryT, P, OutputT_co]) -> Callable[Concatenate[CarryT, P], tuple[CarryT, OutputT_co]]: + ... + + @overload + def scan_via(self, fn: Callable[[M, CarryT], tuple[CarryT, OutputT_co]]) -> Callable[[CarryT], tuple[CarryT, OutputT_co]]: + ... + + def scan_via(self, fn: Callable[..., tuple[CarryT, OutputT_co]]) -> Callable[P, tuple[CarryT, OutputT_co]]: + ... + + @overload + def vmap_via(self, fn: VmapFunction[M, P, OutputT_co]) -> Callable[P, OutputT_co]: + ... + + @overload + def vmap_via(self, fn: Callable[[M], OutputT_co]) -> Callable[[], OutputT_co]: + ... + + def vmap_via(self, fn: Callable[..., OutputT_co]) -> Callable[..., OutputT_co]: + ... + def unstacked(self) -> Sequence[M]: """ Returns the unstacked version of this module. This is useful for logging or saving checkpoints. @@ -177,6 +217,87 @@ class BlockSeq(ModuleWithStateDictSerialization, Generic[M]): return do_fold(init, *args, **kwargs) + @overload + def fold_via(self, fn: FoldFunction[M, P, CarryT]) -> Callable[Concatenate[CarryT, P], CarryT]: + ... + + @overload + def fold_via(self, fn: Callable[[M, CarryT], CarryT]) -> Callable[[CarryT], CarryT]: + ... + + def fold_via(self, fn: Callable[..., CarryT]): + """Return a function that folds over the sequence using ``fn``. + + ``fn`` should take a block and a carry and return a new carry. The + returned function mirrors :func:`haliax.fold` over the block axis. + """ + + def do_fold(init: CarryT, *args, **kwargs) -> CarryT: + carry = init + for block in self.blocks: + carry = fn(block, carry, *args, **kwargs) + carry = tree_checkpoint_name(carry, self._carry_ckpt_name) + return carry + + return do_fold + + @overload + def scan_via(self, fn: ScanFunction[M, CarryT, P, OutputT_co]) -> Callable[Concatenate[CarryT, P], tuple[CarryT, OutputT_co]]: + ... + + @overload + def scan_via(self, fn: Callable[[M, CarryT], tuple[CarryT, OutputT_co]]) -> Callable[[CarryT], tuple[CarryT, OutputT_co]]: + ... + + def scan_via(self, fn: Callable[..., tuple[CarryT, OutputT_co]]): + """Return a function that scans over the sequence using ``fn``. + + ``fn`` should take a block and a carry and return ``(carry, output)``. + Semantics match :func:`haliax.scan` over the block axis. + """ + + def do_scan(init: CarryT, *args, **kwargs) -> tuple[CarryT, OutputT_co]: + out = [] + carry = init + for block in self.blocks: + carry, extra = fn(block, carry, *args, **kwargs) + carry = tree_checkpoint_name(carry, self._carry_ckpt_name) + extra = tree_checkpoint_name(extra, self._output_ckpt_name) + out.append(extra) + + stacked_out = haliax.tree_util.tree_map(lambda *x: haliax.stack(self.Block, x), *out) + return carry, stacked_out + + return do_scan + + @overload + def vmap_via(self, fn: VmapFunction[M, P, OutputT_co]) -> Callable[P, OutputT_co]: + ... + + @overload + def vmap_via(self, fn: Callable[[M], OutputT_co]) -> Callable[[], OutputT_co]: + ... + + def vmap_via(self, fn: Callable[..., OutputT_co]) -> Callable[..., OutputT_co]: + """Return a function that applies each block independently using ``fn``. + + ``fn`` should take a block and a carry and return an output. The + returned function mirrors :func:`haliax.vmap` over the block axis. + """ + + def do_vmap(init: CarryT, *args, **kwargs) -> OutputT_co: + # Apply fn to each block independently + outputs = [] + for block in self.blocks: + output = fn(block, init, *args, **kwargs) + outputs.append(output) + + # Stack the outputs + stacked_out = haliax.tree_util.tree_map(lambda *x: haliax.stack(self.Block, x), *outputs) + return stacked_out + + return do_vmap + def unstacked(self) -> Sequence[M]: return self.blocks @@ -398,7 +519,7 @@ class Stacked(ModuleWithStateDictSerialization, Generic[M]): return do_fold(init, *args, **kwargs) @overload - def fold_via(self, fn: FoldFunction[M, CarryT]) -> Callable[[CarryT], CarryT]: + def fold_via(self, fn: FoldFunction[M, P, CarryT]) -> Callable[Concatenate[CarryT, P], CarryT]: ... @overload @@ -412,16 +533,16 @@ class Stacked(ModuleWithStateDictSerialization, Generic[M]): returned function mirrors :func:`haliax.fold` over the block axis. """ - def do_block(carry: CarryT, block: M) -> CarryT: - return fn(block, carry) + def do_block(carry: CarryT, block: M, *args, **kwargs) -> CarryT: + return fn(block, carry, *args, **kwargs) - def do_fold(init: CarryT) -> CarryT: - return haliax.fold(do_block, self.Block, remat=self.gradient_checkpointing)(init, self.stacked) + def do_fold(init: CarryT, *args, **kwargs) -> CarryT: + return haliax.fold(do_block, self.Block, remat=self.gradient_checkpointing)(init, self.stacked, *args, **kwargs) return do_fold @overload - def scan_via(self, fn: ScanFunction[M, CarryT, OutputT_co]) -> Callable[[CarryT], tuple[CarryT, OutputT_co]]: + def scan_via(self, fn: ScanFunction[M, CarryT, P, OutputT_co]) -> Callable[Concatenate[CarryT, P], tuple[CarryT, OutputT_co]]: ... @overload @@ -435,42 +556,47 @@ class Stacked(ModuleWithStateDictSerialization, Generic[M]): Semantics match :func:`haliax.scan` over the block axis. """ - def do_block(carry: CarryT, block: M) -> tuple[CarryT, OutputT_co]: - return fn(block, carry) + def do_block(carry: CarryT, block: M, *args, **kwargs) -> tuple[CarryT, OutputT_co]: + carry, output = fn(block, carry, *args, **kwargs) + return carry, output - def do_scan(init: CarryT) -> tuple[CarryT, OutputT_co]: - return haliax.scan(do_block, self.Block, remat=self.gradient_checkpointing)(init, self.stacked) + + def do_scan(init: CarryT, *args, **kwargs) -> tuple[CarryT, OutputT_co]: + return haliax.scan(do_block, self.Block, remat=self.gradient_checkpointing)(init, self.stacked, *args, **kwargs) return do_scan - def vmap(self, init, *extra_args, **extra_kwargs): - """Apply each block independently using :func:`haliax.vmap`. + @overload + def vmap_via(self, fn: VmapFunction[M, P, OutputT_co]) -> Callable[P, OutputT_co]: + ... + + @overload + def vmap_via(self, fn: Callable[[M], OutputT_co]) -> Callable[[], OutputT_co]: + ... + + def vmap_via(self, fn: Callable[..., OutputT_co]) -> Callable[..., OutputT_co]: + """Return a function that applies each block independently using ``fn``. + + ``fn`` should take a block and a carry and return an output. The + returned function mirrors :func:`haliax.vmap` over the block axis. + """ + + def do_vmap(*args, **kwargs) -> OutputT_co: + # Create a function that captures the additional arguments + def do_block_with_args(block: M, *args, **kwargs) -> OutputT_co: + return fn(block, *args, **kwargs) + + return haliax.vmap(do_block_with_args, self.Block)(self.stacked, *args, **kwargs) - This maps ``init`` through every block in parallel, so each block - receives the same ``init`` but its own parameters. Extra ``args`` and - ``kwargs`` are also mapped over the block axis by default. + return do_vmap + + def vmap(self, *extra_args, **extra_kwargs): + """Apply each block independently using :func:`haliax.vmap`. Returns the stacked outputs of each block. """ - if haliax.is_named_array(init): - init = init.broadcast_axis(self.Block) - elif haliax.jax_utils.is_jax_array_like(init): - init = jnp.broadcast_to(init, (self.Block.size,) + init.shape) - else: - init = tuple(init for _ in range(self.Block.size)) - - arg_spec = (0, 0) + (0,) * len(extra_args) - kwarg_spec = {k: 0 for k in extra_kwargs} - - do_vmap = haliax.vmap( - Stacked._do_block, - self.Block, - default=0, - args=arg_spec, - kwargs=kwarg_spec, - ) - return do_vmap(init, self.stacked, *extra_args, **extra_kwargs) + return haliax.vmap(type(self.stacked).__call__, self.Block)(self.stacked, *extra_args, **extra_kwargs) @staticmethod def _do_block(carry, block, *extra_args, **extra_kwargs): diff --git a/src/haliax/ops.py b/src/haliax/ops.py index d6508b4..4017a13 100644 --- a/src/haliax/ops.py +++ b/src/haliax/ops.py @@ -85,6 +85,8 @@ def where( raise ValueError("x must be a NamedArray or scalar if y is a NamedArray") x = named(x, ()) x, y = broadcast_arrays(x, y) + if isinstance(condition, NamedArray): + condition = condition.scalar() return jax.lax.cond(condition, lambda _: x, lambda _: y, None) condition, x, y = broadcast_arrays(condition, x, y) # type: ignore diff --git a/src/haliax/wrap.py b/src/haliax/wrap.py index 8af9063..df57f40 100644 --- a/src/haliax/wrap.py +++ b/src/haliax/wrap.py @@ -5,6 +5,7 @@ import jax from haliax.core import NamedArray, _broadcast_order, broadcast_to from .axis import AxisSelection, AxisSelector, axis_spec_to_shape_dict, eliminate_axes +from .jax_utils import is_scalarish def wrap_elemwise_unary(f, a, *args, **kwargs): @@ -94,8 +95,33 @@ def wrap_elemwise_binary(op): b = broadcast_to(b, axes) return NamedArray(op(a.array, b.array), axes) elif isinstance(a, NamedArray): + # b isn't named. + if not is_scalarish(a): + if not is_scalarish(b): + raise ValueError( + f"Cannot apply {op.__name__} to a NamedArray and a non-scalar {type(b)}. " + "Either both must be NamedArrays or b must be a scalar." + ) + else: + if is_scalarish(b): + return NamedArray(op(a.array, b), a.axes) + a = a.scalar() + return op(a, b) + return NamedArray(op(a.array, b), a.axes) elif isinstance(b, NamedArray): + if not is_scalarish(b): + if not is_scalarish(a): + raise ValueError( + f"Cannot apply {op.__name__} to a non-scalar {type(a)} and a NamedArray. " + "Either both must be NamedArrays or a must be a scalar." + ) + else: + if is_scalarish(a): + return NamedArray(op(a, b.array), b.axes) + b = b.scalar() + return op(a, b) + return NamedArray(op(a, b.array), b.axes) else: return op(a, b) diff --git a/tests/core_test.py b/tests/core_test.py index 5d7fe2f..e83c213 100644 --- a/tests/core_test.py +++ b/tests/core_test.py @@ -34,7 +34,7 @@ def test_reduction_functions(): m1 = NamedArray(rand_m, (Height, Width, Depth)) # sum out everything - assert jnp.all(jnp.equal(hax.sum(m1), jnp.sum(m1.array))) + assert jnp.all(jnp.equal(hax.sum(m1).array, jnp.sum(m1.array))) # ensure it's a scalar assert jnp.all(jnp.equal(hax.sum(m1, axis=Height).array, jnp.sum(m1.array, axis=0))) @@ -60,7 +60,7 @@ def test_reduction_functions(): ) # argmax - assert jnp.all(jnp.equal(hax.argmax(m1, axis=None), jnp.argmax(m1.array))) + assert jnp.all(jnp.equal(hax.argmax(m1, axis=None).array, jnp.argmax(m1.array))) assert jnp.all(jnp.equal(hax.argmax(m1, axis=Height).array, jnp.argmax(m1.array, axis=0))) @@ -75,7 +75,7 @@ def test_reduction_functions_with_where(): jmask = m1.array > 0.5 # sum out everything - assert jnp.all(jnp.equal(hax.sum(m1, where=mask), jnp.sum(rand_m, where=jmask))) + assert jnp.all(jnp.equal(hax.sum(m1, where=mask).array, jnp.sum(rand_m, where=jmask))) # ensure it's a scalar assert jnp.all(jnp.equal(hax.sum(m1, axis=H, where=mask).array, jnp.sum(rand_m, axis=0, where=jmask))) @@ -507,7 +507,7 @@ def test_index(): assert named1[{"H": slice(0, 10, 2), "W": 0}].axes == (Axis("H", 5), D) # try indexing with 3 integers: returns scalar ndarray - assert jnp.all(jnp.equal(named1[{"H": 0, "W": 0, "D": 0}], named1.array[0, 0, 0])) + assert jnp.all(jnp.equal(named1[{"H": 0, "W": 0, "D": 0}].array, named1.array[0, 0, 0])) def test_index_with_tracer(): diff --git a/tests/test_dot.py b/tests/test_dot.py index 9f9d2fa..1406a3e 100644 --- a/tests/test_dot.py +++ b/tests/test_dot.py @@ -31,7 +31,7 @@ def test_dot(): # reduce to scalar assert jnp.all( jnp.equal( - hax.dot(m1, m2, axis=None), + hax.dot(m1, m2, axis=None).array, jnp.einsum("ijk,kji->", m1.array, m2.array), ) ) diff --git a/tests/test_hof.py b/tests/test_hof.py index 840bce5..1df5999 100644 --- a/tests/test_hof.py +++ b/tests/test_hof.py @@ -79,7 +79,7 @@ def test_scan_doesnt_scan_scalars(): named1 = hax.random.uniform(PRNGKey(0), (Height,)) def scan_fun(acc, z, x): - return acc + z * x, x * z + return (acc + z * x).scalar(), x * z total, selected = hax.scan(scan_fun, Height)(0.0, 4.0, named1) diff --git a/tests/test_ops.py b/tests/test_ops.py index c81a549..e25c744 100644 --- a/tests/test_ops.py +++ b/tests/test_ops.py @@ -215,14 +215,14 @@ def test_mean_respects_where(): named1 = hax.random.uniform(PRNGKey(0), (Height, Width)) where = hax.random.uniform(PRNGKey(1), (Height, Width)) > 0.5 - assert not jnp.all(jnp.isclose(hax.mean(named1), hax.mean(named1, where=where))) - assert jnp.all(jnp.isclose(hax.mean(named1, where=where), jnp.mean(named1.array, where=where.array))) + assert not hax.all(hax.isclose(hax.mean(named1), hax.mean(named1, where=where))) + assert jnp.all(jnp.isclose(hax.mean(named1, where=where).array, jnp.mean(named1.array, where=where.array))) # check broadcasting where = hax.random.uniform(PRNGKey(2), (Height,)) > 0.5 - assert not jnp.all(jnp.isclose(hax.mean(named1), hax.mean(named1, where=where))) + assert not jnp.all(jnp.isclose(hax.mean(named1).array, hax.mean(named1, where=where).array)) assert jnp.all( - jnp.isclose(hax.mean(named1, where=where), jnp.mean(named1.array, where=where.array.reshape((-1, 1)))) + jnp.isclose(hax.mean(named1, where=where).array, jnp.mean(named1.array, where=where.array.reshape((-1, 1)))) ) diff --git a/tests/test_scan.py b/tests/test_scan.py index c251d3d..05ac7a0 100644 --- a/tests/test_scan.py +++ b/tests/test_scan.py @@ -364,3 +364,401 @@ def test_scan_via(): assert hax.all(hax.isclose(carry, expected_carry)) assert hax.all(hax.isclose(outs, expected_outs)) + + +def test_scan_via_multi_args(): + class Module(eqx.Module): + w: hax.NamedArray + + def with_output(self, x, y, z, *, static1, static2): + assert static1 is True + assert static2 is False + out = x + self.w + y + z + return out, 2 * self.w + y + + @staticmethod + def init(named): + return Module(w=named) + + Block = hax.Axis("block", 4) + E = hax.Axis("E", 6) + + named = hax.random.uniform(jax.random.PRNGKey(0), (Block, E)) + m = Stacked.init(Block, Module)(named=named) + + x = hax.random.uniform(jax.random.PRNGKey(1), (E,)) + y = hax.random.uniform(jax.random.PRNGKey(2), (E,)) + z = 3.0 # scalar that shouldn't be scanned + + carry, outs = m.scan_via(Module.with_output)(x, y, z, static1=True, static2=False) + + # compute expected values via a reference Python loop + expected_carry = x + expected_outs_list = [] + for i in range(Block.size): + expected_outs_list.append(2 * named["block", i] + y) + expected_carry = expected_carry + named["block", i] + y + z + + expected_outs = hax.stack(Block, expected_outs_list) + + assert hax.all(hax.isclose(carry, expected_carry)) + assert hax.all(hax.isclose(outs, expected_outs)) + + +def test_scan_via_static_args(): + class Module(eqx.Module): + w: hax.NamedArray + + def with_output(self, x, static1, *, static2): + assert static1 == 1.0 + assert static2 is False + out = x + self.w + static1 + return out, 2 * self.w + + @staticmethod + def init(named): + return Module(w=named) + + Block = hax.Axis("block", 4) + E = hax.Axis("E", 6) + + named = hax.random.uniform(jax.random.PRNGKey(0), (Block, E)) + m = Stacked.init(Block, Module)(named=named) + + x = hax.random.uniform(jax.random.PRNGKey(1), (E,)) + + carry, outs = m.scan_via(Module.with_output)(x, 1.0, static2=False) + + expected_carry = x + expected_outs_list = [] + for i in range(Block.size): + expected_outs_list.append(2 * named["block", i]) + expected_carry = expected_carry + named["block", i] + 1.0 # True -> 1.0 + + expected_outs = hax.stack(Block, expected_outs_list) + + assert hax.all(hax.isclose(carry, expected_carry)) + assert hax.all(hax.isclose(outs, expected_outs)) + + +def test_scan_via_doesnt_scan_scalars(): + class Module(eqx.Module): + w: hax.NamedArray + + def with_output(self, x, scalar): + out = x + self.w + scalar + return out, x * scalar + + @staticmethod + def init(named): + return Module(w=named) + + Block = hax.Axis("block", 4) + E = hax.Axis("E", 6) + + named = hax.random.uniform(jax.random.PRNGKey(0), (Block, E)) + m = Stacked.init(Block, Module)(named=named) + + x = hax.random.uniform(jax.random.PRNGKey(1), (E,)) + scalar = 4.0 + + carry, outs = m.scan_via(Module.with_output)(x, scalar) + + expected_carry = x + expected_outs_list = [] + for i in range(Block.size): + expected_outs_list.append(expected_carry * scalar) + expected_carry = expected_carry + named["block", i] + scalar + + expected_outs = hax.stack(Block, expected_outs_list) + + assert hax.all(hax.isclose(carry, expected_carry)) + assert hax.all(hax.isclose(outs, expected_outs)) + + +def test_fold_via_multi_args(): + class Module(eqx.Module): + w: hax.NamedArray + + def intermediate(self, x, y, z, *, static1, static2): + assert static1 is True + assert static2 is False + return x + 2 * self.w + y + z + + @staticmethod + def init(named): + return Module(w=named) + + Block = hax.Axis("block", 3) + E = hax.Axis("E", 5) + + named = hax.random.uniform(jax.random.PRNGKey(0), (Block, E)) + m = Stacked.init(Block, Module)(named=named) + + x = hax.random.uniform(jax.random.PRNGKey(1), (E,)) + y = hax.random.uniform(jax.random.PRNGKey(2), (E,)) + z = 3.0 # scalar that shouldn't be scanned + + result = m.fold_via(Module.intermediate)(x, y, z, static1=True, static2=False) + + expected = x + for i in range(Block.size): + expected = expected + 2 * named["block", i] + y + z + + assert hax.all(hax.isclose(result, expected)) + + +def test_fold_via_static_args(): + class Module(eqx.Module): + w: hax.NamedArray + + def intermediate(self, x, static1, *, static2): + assert static1 is True + assert static2 is False + return x + 2 * self.w + static1 + + @staticmethod + def init(named): + return Module(w=named) + + Block = hax.Axis("block", 3) + E = hax.Axis("E", 5) + + named = hax.random.uniform(jax.random.PRNGKey(0), (Block, E)) + m = Stacked.init(Block, Module)(named=named) + + x = hax.random.uniform(jax.random.PRNGKey(1), (E,)) + + result = m.fold_via(Module.intermediate)(x, True, static2=False) + + expected = x + for i in range(Block.size): + expected = expected + 2 * named["block", i] + 1.0 + + assert hax.all(hax.isclose(result, expected)) + + +def test_fold_via_doesnt_reduce_scalars(): + class Module(eqx.Module): + w: hax.NamedArray + + def intermediate(self, x, scalar): + return x + 2 * self.w + scalar + + @staticmethod + def init(named): + return Module(w=named) + + Block = hax.Axis("block", 3) + E = hax.Axis("E", 5) + + named = hax.random.uniform(jax.random.PRNGKey(0), (Block, E)) + m = Stacked.init(Block, Module)(named=named) + + x = hax.random.uniform(jax.random.PRNGKey(1), (E,)) + scalar = 4.0 + + result = m.fold_via(Module.intermediate)(x, scalar) + + expected = x + for i in range(Block.size): + expected = expected + 2 * named["block", i] + scalar + + assert hax.all(hax.isclose(result, expected)) + + +def test_vmap_via(): + class Module(eqx.Module): + w: hax.NamedArray + + def transform(self, x): + return x + self.w + + @staticmethod + def init(named): + return Module(w=named) + + Block = hax.Axis("block", 4) + E = hax.Axis("E", 6) + + named = hax.random.uniform(jax.random.PRNGKey(0), (Block, E)) + m = Stacked.init(Block, Module)(named=named) + + x = hax.random.uniform(jax.random.PRNGKey(1), (E,)) + outs = m.vmap_via(Module.transform)(x) + + expected_outs = x + named + + assert hax.all(hax.isclose(outs, expected_outs)) + + +def test_vmap_via_multi_args(): + class Module(eqx.Module): + w: hax.NamedArray + + def transform(self, x, y, z, *, static1, static2): + assert static1 is True + assert static2 is False + return x + self.w + y + z + + @staticmethod + def init(named): + return Module(w=named) + + Block = hax.Axis("block", 4) + E = hax.Axis("E", 6) + + named = hax.random.uniform(jax.random.PRNGKey(0), (Block, E)) + m = Stacked.init(Block, Module)(named=named) + + x = hax.random.uniform(jax.random.PRNGKey(1), (E,)) + y = hax.random.uniform(jax.random.PRNGKey(2), (E,)) + z = 3.0 # scalar that shouldn't be vmapped + + outs = m.vmap_via(Module.transform)(x, y, z, static1=True, static2=False) + + expected_outs = x + named + y + z + + assert hax.all(hax.isclose(outs, expected_outs)) + + +def test_vmap_via_static_args(): + class Module(eqx.Module): + w: hax.NamedArray + + def transform(self, x, static1, *, static2): + assert static1 == 1.0 + assert static2 is False + return x + self.w + static1 + + @staticmethod + def init(named): + return Module(w=named) + + Block = hax.Axis("block", 4) + E = hax.Axis("E", 6) + + named = hax.random.uniform(jax.random.PRNGKey(0), (Block, E)) + m = Stacked.init(Block, Module)(named=named) + + x = hax.random.uniform(jax.random.PRNGKey(1), (E,)) + + outs = m.vmap_via(Module.transform)(x, 1.0, static2=False) + + expected_outs = x + named + 1.0 + + assert hax.all(hax.isclose(outs, expected_outs)) + + +def test_vmap_via_doesnt_vmap_scalars(): + class Module(eqx.Module): + w: hax.NamedArray + + def transform(self, x, scalar): + return x + self.w + scalar + + @staticmethod + def init(named): + return Module(w=named) + + Block = hax.Axis("block", 4) + E = hax.Axis("E", 6) + + named = hax.random.uniform(jax.random.PRNGKey(0), (Block, E)) + m = Stacked.init(Block, Module)(named=named) + + x = hax.random.uniform(jax.random.PRNGKey(1), (E,)) + scalar = 4.0 + + outs = m.vmap_via(Module.transform)(x, scalar) + + expected_outs = x + named + scalar + + assert hax.all(hax.isclose(outs, expected_outs)) + + +def test_vmap_via_blockseq(): + class Module(eqx.Module): + w: hax.NamedArray + + def transform(self, x): + return x + self.w + + @staticmethod + def init(named): + return Module(w=named) + + Block = hax.Axis("block", 4) + E = hax.Axis("E", 6) + + named = hax.random.uniform(jax.random.PRNGKey(0), (Block, E)) + m = BlockSeq.init(Block, Module)(named=named) + + x = hax.random.uniform(jax.random.PRNGKey(1), (E,)) + outs = m.vmap_via(Module.transform)(x) + + expected_outs = x + named + + assert hax.all(hax.isclose(outs, expected_outs)) + + +def test_vmap_via_blockseq_multi_args(): + class Module(eqx.Module): + w: hax.NamedArray + + def transform(self, x, y, z, *, static1, static2): + assert static1 is True + assert static2 is False + return x + self.w + y + z + + @staticmethod + def init(named): + return Module(w=named) + + Block = hax.Axis("block", 4) + E = hax.Axis("E", 6) + + named = hax.random.uniform(jax.random.PRNGKey(0), (Block, E)) + m = BlockSeq.init(Block, Module)(named=named) + + x = hax.random.uniform(jax.random.PRNGKey(1), (E,)) + y = hax.random.uniform(jax.random.PRNGKey(2), (E,)) + z = 3.0 # scalar that shouldn't be vmapped + + outs = m.vmap_via(Module.transform)(x, y, z, static1=True, static2=False) + + expected_outs = x + named + y + z + + assert hax.all(hax.isclose(outs, expected_outs)) + + +def test_vmap_via_consistency(): + """Test that vmap_via gives the same results as vmap for Stacked.""" + class Module(eqx.Module): + w: hax.NamedArray + + def transform(self, x): + return x + self.w + + def __call__(self, x): + return self.transform(x) + + @staticmethod + def init(named): + return Module(w=named) + + Block = hax.Axis("block", 4) + E = hax.Axis("E", 6) + + named = hax.random.uniform(jax.random.PRNGKey(0), (Block, E)) + m = Stacked.init(Block, Module)(named=named) + + x = hax.random.uniform(jax.random.PRNGKey(1), (E,)) + + # Test vmap_via + outs_via = m.vmap_via(Module.transform)(x) + + # Test direct vmap + outs_direct = m.vmap(x) + + assert hax.all(hax.isclose(outs_via, outs_direct)) diff --git a/tests/test_tree_util.py b/tests/test_tree_util.py index 901f6d4..91d911e 100644 --- a/tests/test_tree_util.py +++ b/tests/test_tree_util.py @@ -32,7 +32,7 @@ def test_resize_axis(): assert module2.name3.axes == (NewA,) # we don't mess with the mean or std of the original array too much - assert jnp.allclose(module2.name1.mean(), module.name1.mean(), rtol=1e-1, atol=1e-2) + assert jnp.allclose(module2.name1.mean().array, module.name1.mean().array, rtol=1e-1, atol=1e-2) def test_scan_aware_tree_map(): commit 12297cd4013b990b73b84d3a2cae19760a5345c9 Date: 2025-07-10T21:40:53-07:00 Add named array padding function (#169) diff --git a/docs/api.md b/docs/api.md index 1fac737..ed79348 100644 --- a/docs/api.md +++ b/docs/api.md @@ -258,6 +258,7 @@ These are all more or less directly from JAX's NumPy API. ::: haliax.clip ::: haliax.isclose +::: haliax.pad ::: haliax.top_k ::: haliax.trace ::: haliax.tril diff --git a/src/haliax/__init__.py b/src/haliax/__init__.py index 12cc604..153fdb0 100644 --- a/src/haliax/__init__.py +++ b/src/haliax/__init__.py @@ -66,7 +66,7 @@ from .core import ( from .haxtyping import Named from .hof import fold, map, scan, vmap from .jax_utils import tree_checkpoint_name -from .ops import clip, isclose, pad_left, trace, tril, triu, where +from .ops import clip, isclose, pad_left, pad, trace, tril, triu, where from .partitioning import auto_sharded, axis_mapping, fsdp, named_jit, shard, shard_with_axis_mapping from .specialized_fns import top_k from .types import Scalar @@ -1082,6 +1082,7 @@ __all__ = [ "are_shape_checks_enabled", "isclose", "pad_left", + "pad", "stack", "concatenate", "eliminate_axes", diff --git a/src/haliax/ops.py b/src/haliax/ops.py index 4017a13..475e9a0 100644 --- a/src/haliax/ops.py +++ b/src/haliax/ops.py @@ -1,10 +1,10 @@ import typing -from typing import Optional, Union +from typing import Mapping, Optional, Union import jax import jax.numpy as jnp -from .axis import Axis, AxisSelector +from .axis import Axis, AxisSelector, axis_name from .core import NamedArray, NamedOrNumeric, broadcast_arrays, broadcast_arrays_and_return_axes, named from .jax_utils import is_scalarish @@ -152,10 +152,48 @@ def pad_left(array: NamedArray, axis: Axis, new_axis: Axis, value=0) -> NamedArr return NamedArray(padded, array.axes[:idx] + (new_axis,) + array.axes[idx + 1 :]) +def pad( + array: NamedArray, + pad_width: Mapping[AxisSelector, tuple[int, int]], + *, + mode: str = "constant", + constant_values: NamedOrNumeric = 0, + **kwargs, +) -> NamedArray: + """Version of ``jax.numpy.pad`` that works with ``NamedArray``. + + ``pad_width`` should be a mapping from axis (or axis name) to a ``(before, after)`` + tuple specifying how much padding to add on each side of that axis. Any axis + not present in ``pad_width`` will not be padded. + """ + + padding = [] + new_axes = [] + for ax in array.axes: + left_right = pad_width.get(ax) + if left_right is None: + left_right = pad_width.get(axis_name(ax)) # type: ignore[arg-type] + if left_right is None: + left_right = (0, 0) + left, right = left_right + padding.append((left, right)) + new_axes.append(ax.resize(ax.size + left + right)) + + result = jnp.pad( + array.array, + padding, + mode=mode, + constant_values=raw_array_or_scalar(constant_values), + **kwargs, + ) + + return NamedArray(result, tuple(new_axes)) + + def raw_array_or_scalar(x: NamedOrNumeric): if isinstance(x, NamedArray): return x.array return x -__all__ = ["trace", "where", "tril", "triu", "isclose", "pad_left", "clip"] +__all__ = ["trace", "where", "tril", "triu", "isclose", "pad_left", "pad", "clip"] diff --git a/tests/test_ops.py b/tests/test_ops.py index e25c744..34df7e8 100644 --- a/tests/test_ops.py +++ b/tests/test_ops.py @@ -237,3 +237,16 @@ def test_reductions_produce_scalar_named_arrays_when_None_axis(): # But if we specify axes, we always get a NamedArray, even if it's a scalar assert isinstance(hax.mean(named1, axis=("Height", "Width")), NamedArray) assert hax.mean(named1, axis=("Height", "Width")).axes == () + + +def test_pad(): + Height = Axis("Height", 3) + Width = Axis("Width", 2) + + arr = hax.arange((Height, Width)) + padded = hax.pad(arr, {Height: (1, 2), Width: (0, 1)}, mode="constant", constant_values=0) + + expected = jnp.pad(arr.array, [(1, 2), (0, 1)], mode="constant", constant_values=0) + assert padded.axes[0].size == Height.size + 3 + assert padded.axes[1].size == Width.size + 1 + assert jnp.all(expected == padded.array) commit 0c47dbe8bc2fa4f69e11dd4af3dca2eb58dea7f5 Date: 2025-07-12T22:07:05-07:00 Document dslice semantics and update indexing behavior (#170) diff --git a/docs/indexing.md b/docs/indexing.md index bde3839..46f2460 100644 --- a/docs/indexing.md +++ b/docs/indexing.md @@ -147,6 +147,11 @@ def f(x, slice_size: int): f(q, 2) ``` +When indexing with ``dslice`` the slice is gathered starting at ``start`` for +``size`` elements. Reads beyond the end of the array return the ``fill_value`` +(0 by default). When used with ``at`` updates, any writes outside the bounds of +the array are dropped. These semantics match JAX's scatter/gather behavior. + For convenience/brevity, `dslice` is aliased as `ds`. In addition, we also expose `dblock`, which is a convenience function for computing the start and size of a slice given a block index and the size of the slice. Thus, the above example can be written as follows: diff --git a/src/haliax/axis.py b/src/haliax/axis.py index 3560525..b90a10e 100644 --- a/src/haliax/axis.py +++ b/src/haliax/axis.py @@ -598,14 +598,19 @@ def resolve_axis(axis_spec: AxisSpec, axis_selection: AxisSelection) -> AxisSpec class dslice(eqx.Module): - """ - Dynamic slice, comprising a (start, length) pair. Also aliased as ds. + """Dynamic slice, comprising a (start, length) pair. Also aliased as ``ds``. + + NumPy-style slices like ``a[i:i+16]`` don't work inside :func:`jax.jit`, because + JAX requires slice bounds to be static. ``dslice`` works around this by + separating the dynamic ``start`` from the static ``size`` so that you can + write ``a[dslice(i, 16)]`` or simply ``a[ds(i, 16)]``. - Normal numpy-isms like a[i:i+16] don't work in Jax inside jit, because slice doesn't like tracers and JAX - can't see that the slice is constant. This is a workaround that lets you do a[dslice(i, 16)] or even a[ds(i, 16)] - instead. + When used in indexing or ``at`` updates, ``dslice`` behaves like a gather of + ``size`` elements starting at ``start``. Reads beyond the end of the array are + filled with a value (0 by default) and writes outside the array bounds are + dropped, matching JAX's default scatter/gather semantics. - This class's name is taken from [jax.experimental.pallas.dslice][]. + This class's name is taken from :mod:`jax.experimental.pallas`. """ start: int diff --git a/src/haliax/core.py b/src/haliax/core.py index c0a968a..c6a94bd 100644 --- a/src/haliax/core.py +++ b/src/haliax/core.py @@ -1163,6 +1163,11 @@ def index(array: NamedArray, slices: Mapping[AxisSelector, NamedIndex]) -> Named you might use `array[{"batch": slice(0, 10)}]` or `array["batch", 0:10]` to select the first 10 elements of the 'batch' axis. + When indexing with a ``dslice`` the slice is gathered starting at the given + ``start`` for ``size`` elements. Values read past the end of the array are + filled with the ``fill_value`` (defaults to ``0``), and writes outside the + bounds are dropped. + See Also: * [haliax.NamedArray.at][] for a functional equivalent of in-place array modifications. @@ -1172,8 +1177,12 @@ def index(array: NamedArray, slices: Mapping[AxisSelector, NamedIndex]) -> Named """ # indices where we have array args new_axes, ordered_slices = _compute_new_axes_and_slices_for_index(array, slices) - sliced, ordered_slices = _handle_dynamic_slices(array.array, ordered_slices) - sliced = sliced[tuple(ordered_slices)] + needs_fill = any(isinstance(s, dslice) or is_pallas_dslice(s) for s in slices.values()) + ordered_slices = [s.array if isinstance(s, NamedArray) else s for s in ordered_slices] + if needs_fill: + sliced = array.array.at[tuple(ordered_slices)].get(mode="fill", fill_value=0) + else: + sliced = array.array[tuple(ordered_slices)] return haliax.named(sliced, new_axes) @@ -1190,9 +1199,19 @@ def _compute_new_axes_and_slices_for_index( axis_index = array.axis_indices(axis) if axis_index is None: raise ValueError(f"axis {axis} not found in {array}") - if isinstance(slice_, py_slice) or isinstance(slice_, dslice) or is_pallas_dslice(slice_): + if isinstance(slice_, py_slice): ordered_slices[axis_index] = slice_ kept_axes[axis_index] = True + elif is_pallas_dslice(slice_) or isinstance(slice_, dslice): + # we want to treat this like a slice, but the closest approximation is an arange, but those have to broadcast. + # So instead we make a named array arange with the same name as the axis. + start = slice_.start + size = slice_.size + orig_axis = array.axes[axis_index] + ordered_slices[axis_index] = haliax.arange(orig_axis.resize(size), start=start) + kept_axes[axis_index] = False + array_slice_indices.append(axis_index) + index_axis_names.add(orig_axis.name) elif isinstance(slice_, int): ordered_slices[axis_index] = slice_ kept_axes[axis_index] = False @@ -1292,34 +1311,6 @@ def _compute_new_axes_and_slices_for_index( return new_axes, ordered_slices -def _handle_dynamic_slices(array: jnp.ndarray, slices): - """ - Helper function to handle dynamic slices in the array. These have to be handled with jax.lax.dynamic_slice, - which is for when the start index is not known at compile time. (Sizes must always be known at compile time.) - - Notes: - **MUTATES `slices` IN PLACE** - - Returns: - array.array: the sliced array - - """ - indices_for_dslice = [0] * array.ndim - lengths_for_dslice = list(array.shape) - dslice_indices = [] - need_to_slice = False - for axis_index, slice_ in enumerate(slices): - if isinstance(slice_, dslice) or is_pallas_dslice(slice_): - dslice_indices.append(axis_index) - indices_for_dslice[axis_index] = slice_.start - lengths_for_dslice[axis_index] = slice_.size - need_to_slice = True - if need_to_slice: - array = jax.lax.dynamic_slice(array, indices_for_dslice, lengths_for_dslice) - for i in dslice_indices: - slices[i] = py_slice(None, None, None) - return array, slices - def split(a: NamedArray, axis: AxisSelector, new_axes: Sequence[Axis]) -> Sequence[NamedArray]: """ @@ -2056,38 +2047,8 @@ class _NamedIndexUpdateRef: def _raw_indices_for_at(array, indexes): sliced_axes, ordered_slices = _compute_new_axes_and_slices_for_index(array, indexes) - del sliced_axes - # this isn't the fastest (it does the _compute_new_axes_and_slices_for_index twice) - # but it's easy _sliced = index(array, indexes) - # we have to handle dslices differently than for normal indexing, because we can't use - # extra dynamic_slices... - # we'd like to just replace these with iota, but we have account for broadcasting semantics - # for the other arrays - dslice_sizes = tuple(x.size for x in ordered_slices if isinstance(x, dslice) or is_pallas_dslice(x)) # type: ignore - current_array_slice_shape = next((x.shape for x in ordered_slices if is_jax_array_like(x)), None) # type: ignore - dims_to_expand = list(range(len(dslice_sizes))) - if current_array_slice_shape is not None: - iota_shape = dslice_sizes + current_array_slice_shape - else: - iota_shape = dslice_sizes - - def iota_for_dslice(dslice, cur_dynamic_slice): - return jax.lax.broadcasted_iota(int, iota_shape, cur_dynamic_slice) + dslice.start - - if len(dslice_sizes) > 0: - cur_dynamic_slice = 0 - for i in range(len(ordered_slices)): - if isinstance(ordered_slices[i], dslice) or is_pallas_dslice(ordered_slices[i]): - ordered_slices[i] = iota_for_dslice(ordered_slices[i], cur_dynamic_slice) - cur_dynamic_slice += 1 - elif is_jax_array_like(ordered_slices[i]): - # prepend array slices with one 1 for each dynamic slice - ordered_slices[i] = jnp.expand_dims(ordered_slices[i], axis=dims_to_expand) - - assert cur_dynamic_slice == len(dslice_sizes) - - # ok the ordered slices are now correct + ordered_slices = [s.array if isinstance(s, NamedArray) else s for s in ordered_slices] return ordered_slices, _sliced.axes diff --git a/tests/core_test.py b/tests/core_test.py index e83c213..4e7757d 100644 --- a/tests/core_test.py +++ b/tests/core_test.py @@ -586,11 +586,36 @@ def test_slice_nd_dslice(): named1 = hax.random.uniform(PRNGKey(0), (H, W, D)) from haliax import ds - assert jnp.all(jnp.equal(named1["H", ds(0, 5), "D", ds(3, 7)].array, named1.array[0:5, :, 3:10])) + ref = jnp.take(named1.array, jnp.arange(0, 5), axis=0, mode="fill", fill_value=0) + ref = jnp.take(ref, jnp.arange(3, 10), axis=2, mode="fill", fill_value=0) + ref = jnp.transpose(ref, (0, 2, 1)) + assert jnp.all(jnp.equal(named1["H", ds(0, 5), "D", ds(3, 7)].array, ref)) # test mixed normal and dslice - assert jnp.all(jnp.equal(named1["H", ds(1, 5), "D", 3:7].array, named1.array[1:6, :, 3:7])) - assert jnp.all(jnp.equal(named1["H", ds(2, 5), "D", 3].array, named1.array[2:7, :, 3])) - assert jnp.all(jnp.equal(named1["H", ds(3, 5), "D", 3:10:2].array, named1.array[3:8, :, 3:10:2])) + ref = jnp.take(named1.array, jnp.arange(1, 6), axis=0, mode="fill", fill_value=0) + ref = jnp.take(ref, jnp.arange(3, 7), axis=2, mode="fill", fill_value=0) + assert jnp.all(jnp.equal(named1["H", ds(1, 5), "D", 3:7].array, ref)) + ref = jnp.take(named1.array, jnp.arange(2, 7), axis=0, mode="fill", fill_value=0) + ref = jnp.take(ref, jnp.arange(3, 4), axis=2, mode="fill", fill_value=0) + ref = ref.squeeze(2) + assert jnp.all(jnp.equal(named1["H", ds(2, 5), "D", 3].array, ref)) + ref = jnp.take(named1.array, jnp.arange(3, 8), axis=0, mode="fill", fill_value=0) + ref = jnp.take(ref, jnp.arange(3, 10, 2), axis=2, mode="fill", fill_value=0) + assert jnp.all(jnp.equal(named1["H", ds(3, 5), "D", 3:10:2].array, ref)) + + +def test_dslice_oob_read_and_write(): + Seq = hax.Axis("seq", 5) + from haliax import ds + + arr = hax.arange((Seq,), dtype=int) + out = arr[{"seq": ds(3, 4)}] + ref = jnp.take(arr.array, jnp.arange(3, 7), mode="fill", fill_value=0) + assert jnp.array_equal(out.array, ref) + + upd = hax.arange((Seq.resize(4),), dtype=int) + updated = arr.at[{"seq": ds(3, 4)}].set(upd) + ref_upd = arr.array.at[jnp.arange(3, 7)].set(upd.array, mode="drop") + assert jnp.array_equal(updated.array, ref_upd) def test_slice_nd_array_present_dims(): commit a26bef49f142f21dba25acd3459c756ddf4c4538 Date: 2025-07-12T23:07:31-07:00 Fix typos in docs and code comments (#171) diff --git a/README.md b/README.md index 7f7a34c..8eb9bb1 100644 --- a/README.md +++ b/README.md @@ -10,14 +10,14 @@ <a href=""> <img alt="License" src="https://img.shields.io/github/license/stanford-crfm/haliax?color=blue" /> </a> -<a href="https://https://pypi.org/project/haliax/"> +<a href="https://pypi.org/project/haliax/"> <img alt="PyPI" src="https://img.shields.io/pypi/v/haliax?color=blue" /> </a> > *Though you don’t seem to be much for listening, it’s best to be careful. If you managed to catch hold of even just a piece of my name, you’d have all manner of power over me.*<br/> > — Patrick Rothfuss, *The Name of the Wind* -Haliax is a [JAX](https:://github.com/google/jax) library for building neural networks with named tensors, in the tradition of Alexander Rush's [Tensor Considered Harmful](https://nlp.seas.harvard.edu/NamedTensor). +Haliax is a [JAX](https://github.com/google/jax) library for building neural networks with named tensors, in the tradition of Alexander Rush's [Tensor Considered Harmful](https://nlp.seas.harvard.edu/NamedTensor). Named tensors improve the **legibility** and **compositionality** of tensor programs by using named axes instead of positional indices as typically used in NumPy, PyTorch, etc. diff --git a/docs/indexing.md b/docs/indexing.md index 46f2460..b1a3e35 100644 --- a/docs/indexing.md +++ b/docs/indexing.md @@ -1,7 +1,7 @@ # Indexing and Slicing Haliax supports Numpy-style indexing, including so-called [Advanced Indexing](https://numpy.org/doc/stable/user/basics.indexing.html#advanced-indexing), -though the syntax is necessarily different. Most forms of indexing are supporting, except we don't support indexing with +though the syntax is necessarily different. Most forms of indexing are supported, except we don't support indexing with booleans right now. (JAX doesn't support indexing with non-constant bool arrays anyway, so I don't think it's worth the effort to implement it in Haliax.) diff --git a/docs/nn.md b/docs/nn.md index 84f2fde..a1915da 100644 --- a/docs/nn.md +++ b/docs/nn.md @@ -6,7 +6,7 @@ Haliax provides a small number of neural network modules that are compatible with Equinox, though they naturally all use [haliax.NamedArray][]. (We welcome PRs for more modules! Nothing too exotic though.) -The most interesting of these modules is [haliax.nn.Stacked][], which allows you to create homogenous "stacks" +The most interesting of these modules is [haliax.nn.Stacked][], which allows you to create homogeneous "stacks" of the same module (e.g. transformer blocks), which is a common pattern in deep learning. ### Linear diff --git a/docs/state-dict.md b/docs/state-dict.md index af9d7d7..a0b8859 100644 --- a/docs/state-dict.md +++ b/docs/state-dict.md @@ -226,7 +226,7 @@ any Axis members to match the new shape. ::: haliax.state_dict.save_state_dict ::: haliax.state_dict.load_state_dict -### Converting betweewn State Dicts and Modules +### Converting between State Dicts and Modules ::: haliax.state_dict.from_state_dict ::: haliax.state_dict.to_state_dict diff --git a/docs/typing.md b/docs/typing.md index 5b9cb75..fd69c90 100644 --- a/docs/typing.md +++ b/docs/typing.md @@ -1,4 +1,4 @@ -from haliax import NamedArrayfrom haliax import NamedArray +from haliax import NamedArray # NamedArray Type Annotations diff --git a/src/haliax/nn/conv.py b/src/haliax/nn/conv.py index 6dec83e..b41e783 100644 --- a/src/haliax/nn/conv.py +++ b/src/haliax/nn/conv.py @@ -213,7 +213,7 @@ class Conv(_ConvBase): return x def _do_conv(self, inputs): - # _do_conv expects there ot be a single __batch__ dimension + # _do_conv expects there to be a single __batch__ dimension output_axes = _compute_output_axes(inputs, "__batch__", self.In, self.Out) batch_index = _index_of_name(inputs.axes, "__batch__") diff --git a/src/haliax/nn/linear.py b/src/haliax/nn/linear.py index c5a1809..1c8c825 100644 --- a/src/haliax/nn/linear.py +++ b/src/haliax/nn/linear.py @@ -143,7 +143,7 @@ class MoELinear(eqx.Module): Experts: AxisSpec = eqx.field(static=True) In: Axis = eqx.field(static=True) Out: Axis = eqx.field(static=True) - # TODO: support quanitization for ragged_dot? + # TODO: support quantization for ragged_dot? # dot_general: DotGeneralOp = eqx.field(default_factory=DotGeneralOp.default) use_gmm: bool = eqx.field(static=True) diff --git a/tests/test_rearrange.py b/tests/test_rearrange.py index 0d84e95..2dd2d81 100644 --- a/tests/test_rearrange.py +++ b/tests/test_rearrange.py @@ -293,7 +293,7 @@ def test_examples(): r = einops_rearrange(z, "{B (H: h1 h) (W: w1 w) C} -> (B: B h1 w1) ... (C: C h w) ", h1=2, w1=2) assert r.axes == (Axis("B", B.size * 2 * 2), D, Axis("C", C.size * sH.size * sW.size)) # unet attention reordering: - # postional: (qkv heads c) h w -> qkv heads c (h w) + # positional: (qkv heads c) h w -> qkv heads c (h w) # named: { (embed: qkv heads c) h w } -> qkv heads c (pos: h w) Embed = Axis("embed", 3 * 4 * C.size) attn = hax.random.randint(PRNGKey(0), (Embed, H, W), 0, 255) commit d5c68e3da1742d0bb65d6cf036b0c5748d27db04 Date: 2025-07-15T00:51:14-07:00 Merge remote-tracking branch 'origin/main' into unique commit 3bee3d26ffdb2edf073bc1da9536e057fd7b1d27 Date: 2025-07-15T08:55:44-07:00 i dunno why this made it in diff --git a/tests/test_fp8.py b/tests/test_fp8.py index 7f61f78..fec3059 100644 --- a/tests/test_fp8.py +++ b/tests/test_fp8.py @@ -27,17 +27,14 @@ def test_fp8_is_reasonable(): In, Out, key=jrandom.PRNGKey(0), dot_general=hax.quantization.Fp8DotGeneralOp.init(), init_scale=0.1 ) - input = hax.random.normal(jrandom.PRNGKey(3), In) * 0.1 - input2 = hax.random.normal(jrandom.PRNGKey(2), In) * 0.1 + input = hax.random.normal(jrandom.PRNGKey(3), In) output = linear(input) fp8_output = fp8_linear(input) - fp8_output2 = fp8_linear(input2) assert output.shape == fp8_output.shape assert output.dtype == fp8_output.dtype assert_trees_all_close(output.array, fp8_output.array, atol=2e-2, rtol=5e-2) - assert not jnp.allclose(fp8_output2.array, fp8_output.array, atol=2e-2, rtol=2e-2) # https://github.com/google/flax/blob/6f2b08e024c2fd2f8cec42a6c82408cb35412319/tests/linen/linen_test.py#L1222 commit 5d6a246fe42bb6d0998186845994cf8b9d87ace5 Date: 2025-07-15T09:25:37-07:00 add unique (#117) * add unique * this? * Add named wrappers for unique variants (#172) * i dunno why this made it in diff --git a/src/haliax/__init__.py b/src/haliax/__init__.py index 83d450d..b3f02a2 100644 --- a/src/haliax/__init__.py +++ b/src/haliax/__init__.py @@ -66,7 +66,21 @@ from .core import ( from .haxtyping import Named from .hof import fold, map, scan, vmap from .jax_utils import tree_checkpoint_name -from .ops import clip, isclose, pad_left, pad, trace, tril, triu, unique, where +from .ops import ( + clip, + isclose, + pad_left, + pad, + trace, + tril, + triu, + unique, + unique_values, + unique_counts, + unique_inverse, + unique_all, + where, +) from .partitioning import auto_sharded, axis_mapping, fsdp, named_jit, shard, shard_with_axis_mapping from .specialized_fns import top_k from .types import Scalar @@ -1035,6 +1049,10 @@ __all__ = [ "trace", "where", "unique", + "unique_values", + "unique_counts", + "unique_inverse", + "unique_all", "clip", "tril", "triu", diff --git a/src/haliax/ops.py b/src/haliax/ops.py index 7c371c0..2bf39bd 100644 --- a/src/haliax/ops.py +++ b/src/haliax/ops.py @@ -342,4 +342,106 @@ def unique( return tuple(ret) -__all__ = ["trace", "where", "tril", "triu", "isclose", "pad_left", "pad", "clip", "unique"] +def unique_values( + array: NamedArray, + Unique: Axis, + *, + axis: AxisSelector | None = None, + fill_value: ArrayLike | None = None, +) -> NamedArray: + """Shortcut for :func:`unique` that returns only unique values.""" + + return typing.cast( + NamedArray, + unique( + array, + Unique, + axis=axis, + fill_value=fill_value, + ), + ) + + +def unique_counts( + array: NamedArray, + Unique: Axis, + *, + axis: AxisSelector | None = None, + fill_value: ArrayLike | None = None, +) -> tuple[NamedArray, NamedArray]: + """Shortcut for :func:`unique` that also returns counts.""" + + values, counts = typing.cast( + tuple[NamedArray, NamedArray], + unique( + array, + Unique, + return_counts=True, + axis=axis, + fill_value=fill_value, + ), + ) + return values, counts + + +def unique_inverse( + array: NamedArray, + Unique: Axis, + *, + axis: AxisSelector | None = None, + fill_value: ArrayLike | None = None, +) -> tuple[NamedArray, NamedArray]: + """Shortcut for :func:`unique` that also returns inverse indices.""" + + values, inverse = typing.cast( + tuple[NamedArray, NamedArray], + unique( + array, + Unique, + return_inverse=True, + axis=axis, + fill_value=fill_value, + ), + ) + return values, inverse + + +def unique_all( + array: NamedArray, + Unique: Axis, + *, + axis: AxisSelector | None = None, + fill_value: ArrayLike | None = None, +) -> tuple[NamedArray, NamedArray, NamedArray, NamedArray]: + """Shortcut for :func:`unique` returning values, indices, inverse, and counts.""" + + values, indices, inverse, counts = typing.cast( + tuple[NamedArray, NamedArray, NamedArray, NamedArray], + unique( + array, + Unique, + return_index=True, + return_inverse=True, + return_counts=True, + axis=axis, + fill_value=fill_value, + ), + ) + return values, indices, inverse, counts + + +__all__ = [ + "trace", + "where", + "tril", + "triu", + "isclose", + "pad_left", + "pad", + "clip", + "unique", + "unique_values", + "unique_counts", + "unique_inverse", + "unique_all", +] diff --git a/tests/test_ops.py b/tests/test_ops.py index 14cae59..2a51efa 100644 --- a/tests/test_ops.py +++ b/tests/test_ops.py @@ -1,4 +1,5 @@ from typing import Callable +import typing import jax.numpy as jnp import pytest @@ -359,3 +360,50 @@ def test_unique(): assert jnp.all(jnp.equal(values.array, jnp.array([[1, 2], [2, 3]]))) assert jnp.all(jnp.equal(counts.array, jnp.array([2, 1]))) + + +def test_unique_shortcuts(): + Height = Axis("Height", 3) + Width = Axis("Width", 2) + + arr2d = hax.named([[1, 2], [2, 3], [1, 2]], (Height, Width)) + U = Axis("U", 3) + + # unique_values + uv = hax.unique_values(arr2d, U) + uv_expected = hax.unique(arr2d, U) + assert jnp.all(uv.array == uv_expected.array) + + # unique_counts + vc, cc = hax.unique_counts(arr2d, U) + vc_exp, cc_exp = hax.unique(arr2d, U, return_counts=True) + assert jnp.all(vc.array == vc_exp.array) + assert jnp.all(cc.array == cc_exp.array) + + # unique_inverse + Height1 = Axis("Height1", 5) + arr1d = hax.named([3, 4, 1, 3, 1], (Height1,)) + U2 = Axis("U2", 3) + vi, ii = hax.unique_inverse(arr1d, U2) + vi_exp, ii_exp = hax.unique(arr1d, U2, return_inverse=True) + assert jnp.all(vi.array == vi_exp.array) + assert jnp.all(ii.array == ii_exp.array) + + # unique_all + U3 = Axis("U3", 2) + va, ia, ina, ca = hax.unique_all(arr2d, U3, axis=Height) + va_exp, ia_exp, ina_exp, ca_exp = typing.cast( + tuple[NamedArray, NamedArray, NamedArray, NamedArray], + hax.unique( + arr2d, + U3, + axis=Height, + return_index=True, + return_inverse=True, + return_counts=True, + ), + ) + assert jnp.all(va.array == va_exp.array) + assert jnp.all(ia.array == ia_exp.array) + assert jnp.all(ina.array == ina_exp.array) + assert jnp.all(ca.array == ca_exp.array) commit a8cf6ff9002a4751bce900f837849b9b1c4e1f66 Date: 2025-07-15T09:27:18-07:00 docs: add playbook for wrapping functions (#174) diff --git a/.playbooks/wrap-non-named.md b/.playbooks/wrap-non-named.md new file mode 100644 index 0000000..ccd6ac8 --- /dev/null +++ b/.playbooks/wrap-non-named.md @@ -0,0 +1,49 @@ +# Wrapping Functions with NamedArray Support + +This playbook explains how to convert a regular JAX function that works on unnamed arrays into a Haliax function that accepts `NamedArray` inputs and returns `NamedArray` outputs. + +## When is wrapping needed? +Many JAX primitives only operate on regular arrays. To integrate them in Haliax you should provide a thin wrapper that handles axis metadata. Simple elementwise operations and reductions have helper utilities. + +## Elemwise Unary +For a unary function that acts elementwise (e.g. `jnp.abs`): + +```python +from haliax import wrap_elemwise_unary + +def abs(a): + return wrap_elemwise_unary(jnp.abs, a) +``` + +This preserves axis order and dtype. + +## Elemwise Binary +For binary operations (e.g. `jnp.add`), decorate a function with `wrap_elemwise_binary`: + +```python +from haliax import wrap_elemwise_binary + +@wrap_elemwise_binary +def add(x1, x2): + return jnp.add(x1, x2) +``` + +Broadcasting between `NamedArray`s is handled automatically. + +## Reductions +Reductions require choosing axes to eliminate. Use `wrap_reduction_call`: + +```python +from haliax import wrap_reduction_call + +def sum(a, axis=None): + return wrap_reduction_call(jnp.sum, a, axis) +``` + +`axis` can be an `AxisSelector` or tuple. The wrapper returns a `NamedArray` with those axes removed. + +## Harder Cases +Some functions need bespoke handling. For example `jnp.unique` returns several arrays and may change shape unpredictably. There is no generic helper, so you will need to manually map between `NamedArray` axes and the outputs. Use the lower level utilities in `haliax.wrap` for broadcasting and axis lookup. + +## Testing +Add tests to ensure that named and unnamed calls produce the same results and that axis names are preserved or removed correctly. diff --git a/AGENTS.md b/AGENTS.md index 2642efa..33336a7 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -17,6 +17,7 @@ repository. Follow these notes when implementing new features or fixing bugs. ## Playbook - Adding Haliax-style tensor typing annotations are described in @.playbooks/add-types.md +- Wrapping standard JAX functions so they operate on `NamedArray` is explained in @.playbooks/wrap-non-named.md ## Code Style commit 0383414f087b94cdf43eb3198cc91ce76ef7e6fa Date: 2025-07-16T12:55:40-07:00 make ScanCheckpointPolicy frozen diff --git a/src/haliax/_src/scan.py b/src/haliax/_src/scan.py index f7631d6..661934f 100644 --- a/src/haliax/_src/scan.py +++ b/src/haliax/_src/scan.py @@ -33,7 +33,7 @@ class ScanFn(Protocol[Carry, Args, Y]): ... -@dataclasses.dataclass +@dataclasses.dataclass(frozen=True) class ScanCheckpointPolicy: """ A class that represents a gradient checkpoint policy for blocks in a Stacked module. This is used to control commit 2971fc8dc5f75fd44ccafc52873f308c6417e691 Date: 2025-07-17T16:17:04-07:00 Improve sharding visualization and tests (#176) diff --git a/docs/faq.md b/docs/faq.md index f6d7ed2..5bd04bb 100644 --- a/docs/faq.md +++ b/docs/faq.md @@ -9,3 +9,9 @@ Currently, we diagnose: * Reuse of arrays or NamedArrays in a field. [Equinox modules must be trees.](https://docs.kidger.site/equinox/faq/#a-module-saved-in-two-places-has-become-two-independent-copies) * Use of arrays or NamedArrays in a static field. Static data in JAX/Equinox must be hashable, and arrays are not hashable. + +## Tip 2: `hax.debug.visualize_shardings` + +Use `hax.debug.visualize_shardings` to quickly inspect how a PyTree is sharded. +It prints the sharding of each array leaf, including the mapping from named axes +to physical axes for :class:`haliax.NamedArray` leaves. diff --git a/src/haliax/debug.py b/src/haliax/debug.py index 85820bd..c10d073 100644 --- a/src/haliax/debug.py +++ b/src/haliax/debug.py @@ -1,11 +1,14 @@ import dataclasses -from typing import List, Tuple, Union +from typing import List, Tuple, Union, Sequence import equinox as eqx +import jax import jax.numpy as jnp import jax.tree_util as jtu + from haliax.core import NamedArray +from haliax.axis import Axis from haliax.util import is_jax_or_hax_array_like from ._src.util import IdentityMap @@ -117,3 +120,70 @@ def _check_for_static_arrays(problems, module): if static_arrays: problems.static_arrays.extend(static_arrays) + + +def _pspec_parts(spec_part) -> str: + if spec_part is None: + return "unsharded" + elif isinstance(spec_part, (tuple, list)): + return "+".join(str(p) for p in spec_part) + else: + return str(spec_part) + + +def visualize_named_sharding(axes: Sequence[Axis], sharding: jax.sharding.Sharding) -> None: + """Visualize the sharding for a set of named axes. + + This extends :func:`jax.debug.visualize_sharding` to handle arrays with more + than two dimensions by falling back to a textual description when necessary. + """ + + try: + pspec = sharding.spec # type: ignore[attr-defined] + except Exception: + pspec = (None,) * len(axes) + + parts = [_pspec_parts(p) for p in pspec] + num_sharded = sum(p != "unsharded" for p in parts) + + if num_sharded <= 2: + try: + jax.debug.visualize_sharding([ax.size for ax in axes], sharding) + except Exception: + pass + + mapping = ", ".join(f"{ax.name}->{part}" for ax, part in zip(axes, parts)) + print(mapping) + + +def visualize_shardings(tree) -> None: + """Print the sharding for each array-like leaf in ``tree``. + + Both :class:`NamedArray` and regular JAX arrays are supported. NamedArrays + will show the mapping from logical axis names to physical axes. Plain arrays + will fall back to :func:`jax.debug.visualize_sharding`. + """ + + import haliax.tree_util as htu + + def _show(x): + if isinstance(x, NamedArray): + arr = x.array + axes = x.axes + else: + arr = x + axes = None + + def cb(sh): + if axes is not None: + visualize_named_sharding(axes, sh) + else: + try: + jax.debug.visualize_sharding(arr.shape, sh) + except Exception: + pass + + jax.debug.inspect_array_sharding(arr, callback=cb) + return x + + htu.tree_map(_show, tree, is_leaf=is_jax_or_hax_array_like) diff --git a/tests/test_visualize_sharding.py b/tests/test_visualize_sharding.py new file mode 100644 index 0000000..18f6c63 --- /dev/null +++ b/tests/test_visualize_sharding.py @@ -0,0 +1,67 @@ +import numpy as np +import jax +import jax.numpy as jnp + +import haliax as hax +from haliax import Axis +from haliax.partitioning import ResourceAxis, axis_mapping, named_jit +from test_utils import skip_if_not_enough_devices +from haliax.debug import visualize_shardings + +Dim1 = Axis("dim1", 8) +Dim2 = Axis("dim2", 8) +Dim3 = Axis("dim3", 2) + +resource_map = { + "dim1": ResourceAxis.DATA, + "dim2": ResourceAxis.MODEL, + "dim3": ResourceAxis.REPLICA, +} + + +def test_visualize_shardings_runs(capsys): + mesh = jax.sharding.Mesh( + np.array(jax.devices()).reshape(-1, 1, 1), + (ResourceAxis.DATA, ResourceAxis.MODEL, ResourceAxis.REPLICA), + ) + with axis_mapping(resource_map), mesh: + arr = hax.ones((Dim1, Dim2, Dim3)) + visualize_shardings(arr) + + out = capsys.readouterr().out + assert "dim1" in out and "dim2" in out and "dim3" in out + + +def test_visualize_shardings_inside_jit(capsys): + mesh = jax.sharding.Mesh(np.array(jax.devices()).reshape(-1, 1), (ResourceAxis.DATA, ResourceAxis.MODEL)) + + @named_jit(out_axis_resources={"dim1": ResourceAxis.DATA}) + def fn(x): + visualize_shardings(x) + return x + + with axis_mapping({"dim1": ResourceAxis.DATA}), mesh: + x = hax.ones(Dim1) + fn(x) + + out = capsys.readouterr().out + assert "dim1" in out + + +def test_visualize_shardings_plain_array(capsys): + x = jnp.ones((4, 4)) + visualize_shardings(x) + out = capsys.readouterr().out + assert out.strip() != "" + + +@skip_if_not_enough_devices(2) +def test_visualize_shardings_model_axis(capsys): + devices = jax.devices() + mesh = jax.sharding.Mesh(np.array(devices).reshape(-1, 2), (ResourceAxis.DATA, ResourceAxis.MODEL)) + with axis_mapping({"dim1": ResourceAxis.DATA, "dim2": ResourceAxis.MODEL}), mesh: + arr = hax.ones((Dim1, Dim2)) + visualize_shardings(arr) + + out = capsys.readouterr().out + assert "dim2" in out commit 05b2f2abb3675c3ac5f65db4a8e8c0a580e1bab5 Date: 2025-07-20T23:11:44-07:00 Make internal dataclasses frozen (#179) diff --git a/src/haliax/_src/parsing.py b/src/haliax/_src/parsing.py index 4bce2d3..d2233c9 100644 --- a/src/haliax/_src/parsing.py +++ b/src/haliax/_src/parsing.py @@ -5,7 +5,7 @@ from typing import Mapping, NoReturn, Optional, Sequence from haliax.axis import Axis, AxisSelector -@dataclasses.dataclass +@dataclasses.dataclass(frozen=True) class _AxisCapture: binding: Optional[str] = None axes: tuple[str, ...] = () @@ -16,7 +16,7 @@ class _AxisCapture: raise ValueError("Empty axes not allowed") -@dataclasses.dataclass +@dataclasses.dataclass(frozen=True) class Expression: captures: Sequence[_AxisCapture | EllipsisType] is_ordered: bool diff --git a/src/haliax/_src/rearrange.py b/src/haliax/_src/rearrange.py index ce6e5ef..7b68220 100644 --- a/src/haliax/_src/rearrange.py +++ b/src/haliax/_src/rearrange.py @@ -149,7 +149,7 @@ def einops_rearrange(array: NamedArray, expression: str, **bindings: AxisSelecto return auto_sharded(NamedArray(finished_array, plan.final_axes)) -@dataclasses.dataclass +@dataclasses.dataclass(frozen=True) class _Plan: intermediate_axes: tuple[Axis, ...] transpose: Optional[tuple[int, ...]] commit 7b0fd0985a8ab4cb717339d60e7da1eeeedd01db Date: 2025-07-20T23:34:54-07:00 tweak agents.md diff --git a/AGENTS.md b/AGENTS.md index 33336a7..1b6d9a0 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -17,7 +17,7 @@ repository. Follow these notes when implementing new features or fixing bugs. ## Playbook - Adding Haliax-style tensor typing annotations are described in @.playbooks/add-types.md -- Wrapping standard JAX functions so they operate on `NamedArray` is explained in @.playbooks/wrap-non-named.md +- [Wrapping standard JAX functions](.playbooks/wrap-non-named.md) so they operate on `NamedArray` ## Code Style @@ -58,15 +58,14 @@ repository. Follow these notes when implementing new features or fixing bugs. * **Generic code**: many utilities are written with Python generics and dataclasses. Where possible, write reusable functions or classes that operate over TypeVars instead of hard coding concrete types. -* **Configurations**: configuration files are dataclasses loaded via `draccus`. Keep configs - declarative and typed. -* **Reproducibility**: Levanter aims for deterministic training where possible. Avoid sources of +* **Reproducibility**: Haliax aims for determinism where possible. Avoid sources of nondeterminism unless explicitly required. * Prefer Stacked with fold or scan over writing custom loops, for better compile times and gradient checkpointing support +* For configuration, we prefer frozen dataclasses over dictionaries. ## Library conventions -- Haliax revolves around `NamedArray` and explicit `Axis` objects. Prefer APIs that accept - axes or axis names rather than hard‑coding positional dimensions. +- Haliax revolves around `NamedArray` and named shapes, either via Axis objects or "shape dicts" (e.g. `{"batch": 42, "embed": 16}). + Prefer APIs that accept axes or axis names rather than hard‑coding positional dimensions. In particular, use AxisSpec and AxisSelection where possible. - Utilities should be written so they work with arbitrary axis names. Avoid relying on fixed axis orders when possible. - Use the provided modules in `haliax.nn` or Equinox when building neural network layers. @@ -74,5 +73,4 @@ repository. Follow these notes when implementing new features or fixing bugs. for a float32 array with a "batch" axis, or `ht.Float[NamedArray, "batch"]` for any floating point dtype. ## Documentation -- Public functions and modules require docstrings. If behavior is non‑obvious, - add examples in `docs/`. +- Public functions and modules require docstrings. If behavior is non‑obvious, add examples in `docs/`. commit e2e4852179e67c454b0d11d97b7ea6f5e7dbad74 Date: 2025-07-21T09:08:00-07:00 refactor broadcast_to to use shape dicts (#180) diff --git a/src/haliax/core.py b/src/haliax/core.py index c6a94bd..e38cf0d 100644 --- a/src/haliax/core.py +++ b/src/haliax/core.py @@ -32,6 +32,7 @@ from .axis import ( dslice, eliminate_axes, selects_axis, + _check_size_consistency, ) from .types import GatherScatterModeStr, IntScalar, PrecisionLike, Scalar @@ -1649,39 +1650,62 @@ def _broadcast_axes( def broadcast_to( a: NamedOrNumeric, axes: AxisSpec, ensure_order: bool = True, enforce_no_extra_axes: bool = True ) -> NamedArray: - """ - Broadcasts a so that it has the given axes. - If ensure_order is True (default), then the returned array will have the same axes in the same order as the given - axes. Otherwise, the axes may not be moved if they are already in the array. The axes may not be contiguous however + """Broadcast ``a`` so that it has the given axes. + + If ``ensure_order`` is ``True`` (default) then the returned array's axes are + arranged in the same order as ``axes``. Otherwise existing axes may remain in + their current order, though they may still be moved to the front if new axes + are added. - If enforce_no_extra_axes is True and the array has axes that are not in axes, then a ValueError is raised. + If ``enforce_no_extra_axes`` is ``True`` and ``a`` has axes that are not in + ``axes`` then a ``ValueError`` is raised. """ - axes = axis_spec_to_tuple(axes) + + axes_dict = axis_spec_to_shape_dict(axes) + axes_tuple = axis_spec_to_tuple(axes) if not isinstance(a, NamedArray): a = named(jnp.asarray(a), ()) assert isinstance(a, NamedArray) # mypy gets confused - if a.axes == axes: - return a + a_axes_dict = axis_spec_to_shape_dict(a.axes) + + # fill in missing sizes and check for mismatches + for name, sz in list(axes_dict.items()): + if sz is None: + if name not in a_axes_dict: + raise ValueError( + f"Cannot broadcast: size for axis '{name}' is unspecified and it does not exist in array" + ) + axes_dict[name] = a_axes_dict[name] + elif name in a_axes_dict: + _check_size_consistency(axes, a.axes, name, sz, a_axes_dict[name]) - to_add = tuple(ax for ax in axes if ax not in a.axes) + extra_axis_names = [ax.name for ax in a.axes if ax.name not in axes_dict] + if enforce_no_extra_axes and extra_axis_names: + raise ValueError( + f"Cannot broadcast {a.shape} to {axes_dict}: extra axes present {extra_axis_names}" + ) - all_axes = to_add + a.axes + axes_names_in_a = {ax.name for ax in a.axes} + to_add = tuple( + Axis(axis_name(ax), axes_dict[axis_name(ax)]) + for ax in axes_tuple + if axis_name(ax) not in axes_names_in_a + ) - if enforce_no_extra_axes and len(all_axes) != len(axes): - raise ValueError(f"Cannot broadcast {a.shape} to {axis_spec_to_shape_dict(axes)}: extra axes present") + all_axes = to_add + a.axes - extra_axes = tuple(ax for ax in a.axes if ax not in axes) + extra_axes = tuple(ax for ax in a.axes if ax.name not in axes_dict) - # broadcast whatever we need to the front and reorder a_array = jnp.broadcast_to(a.array, [ax.size for ax in all_axes]) a = NamedArray(a_array, all_axes) - # if the new axes are already in the right order, then we're done - if ensure_order and not _is_subsequence(axes, all_axes): - a = a.rearrange(axes + extra_axes) + axes_tuple_complete = tuple(Axis(axis_name(ax), axes_dict[axis_name(ax)]) for ax in axes_tuple) + + if ensure_order and not _is_subsequence(axes_tuple_complete, all_axes): + a = a.rearrange(axes_tuple_complete + extra_axes) return typing.cast(NamedArray, a) commit e67a67f96b5d89939741f3afa9373d56ba902ead Date: 2025-07-23T09:32:26-07:00 Add link to LLM primer (#181) * clarify primer audience * Update mkdocs.yml diff --git a/AGENTS.md b/AGENTS.md index 1b6d9a0..5c36ec5 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -74,3 +74,4 @@ repository. Follow these notes when implementing new features or fixing bugs. ## Documentation - Public functions and modules require docstrings. If behavior is non‑obvious, add examples in `docs/`. +- For a concise overview of Haliax aimed at LLM agents, see [docs/primer.md](docs/primer.md). diff --git a/docs/primer.md b/docs/primer.md new file mode 100644 index 0000000..cc3a458 --- /dev/null +++ b/docs/primer.md @@ -0,0 +1,114 @@ +# Haliax Primer + +Haliax provides named tensors built on top of JAX. This primer is written for LLM agents and other downstream libraries and collects the core ideas for quick reference. + +## Axes and Named Arrays + +Arrays are indexed by `Axis` objects. You can define them explicitly or generate several with `make_axes`. +You may also specify shapes with a **shape dict**, mapping axis names to sizes. + +```python +import haliax as hax +from haliax import Axis + +Batch = Axis("batch", 4) +Feature = Axis("feature", 8) +# or: Batch, Feature = hax.make_axes(batch=4, feature=8) +# using Axis objects +x = hax.zeros((Batch, Feature)) +# or using a shape dict +shape = {"batch": 4, "feature": 8} +x = hax.zeros(shape) +``` + +Most functions accept either axes or shape dicts interchangeably. + +A tensor with named axes is a [`NamedArray`][haliax.NamedArray]. Elementwise operations mirror `jax.numpy` but accept named axes. + +## Indexing and Broadcasting + +Use axis names when slicing. Dictionaries are convenient for several axes: + +```python +first = x["batch", 0] +sub = x["batch", 1:3] +# or with a dict +first = x[{"batch": 0}] +sub = x[{"batch": slice(1, 3)}] +``` + +Axes broadcast by matching names. `broadcast_axis` adds a new axis to an array: + +```python +row = hax.arange(Feature) +outer = row.broadcast_axis(Batch) * hax.arange(Batch) +``` + +See [Indexing and Slicing](indexing.md) and [Broadcasting](broadcasting.md) for details. + +## Rearranging Axes + +`rearrange` changes axis order and can merge or split axes using einops‑style syntax. It is useful when interfacing with positional APIs. + +```python +# transpose features and batch +x_t = hax.rearrange(x, "batch feature -> feature batch") +``` + +More examples appear in [Rearrange](rearrange.md). + +## Matrix Multiplication + +`dot` contracts over named axes while preserving order independence. + +```python +Weight = Axis("weight", 8) +w = hax.ones((Feature, Weight)) +prod = hax.dot(x, w, axis=Feature) +``` + +For more complex contractions use [`einsum`][haliax.einsum]. See [Matrix Multiplication](matmul.md). + +## Scans and Folds + +Use [`scan`][haliax.scan] or [`fold`][haliax.fold] to apply a function along an axis with optional gradient checkpointing. + +```python +Time = Axis("time", 10) +sequence = hax.ones((Time, Feature)) + +def add(prev, cur): + return prev + cur + +result = hax.fold(add, Time)(hax.zeros((Feature,)), sequence) +``` + +See [Scan and Fold](scan.md) for checkpointing policies and stacked modules. + +## Partitioning + +Arrays and modules can be distributed across devices by mapping named axes to mesh axes: + +```python +with hax.axis_mapping({"batch": "data"}): + sharded = hax.shard(x) +``` + +The [Partitioning](partitioning.md) guide explains how to set up device meshes and shard arrays. + +## Typing Support + +Type annotations use `haliax.haxtyping` which extends `jaxtyping`: + +```python +import haliax.haxtyping as ht + +def f(t: ht.Float[hax.NamedArray, "batch feature"]): + ... +``` + +See [Typing](typing.md) for matching runtime checks and dtype-aware annotations. + +--- + +This primer highlights common patterns. The [cheatsheet](cheatsheet.md) lists many additional conversions from JAX to Haliax. diff --git a/mkdocs.yml b/mkdocs.yml index e429b6b..97f5c07 100644 --- a/mkdocs.yml +++ b/mkdocs.yml @@ -100,3 +100,5 @@ nav: - Serialization: 'state-dict.md' - API Reference: 'api.md' - FAQ: 'faq.md' + - LLMs: + - "LLM Primer": 'primer.md' commit c06793be07e29d2476376d07b55b7d4c08782388 Date: 2025-07-26T14:51:46-07:00 docs: link references using mkdocs syntax (#182) diff --git a/docs/faq.md b/docs/faq.md index 5bd04bb..003e911 100644 --- a/docs/faq.md +++ b/docs/faq.md @@ -2,16 +2,16 @@ See also the [Equinox FAQ](https://docs.kidger.site/equinox/faq/) -## Tip 1: `hax.debug.diagnose_common_issues` +## [`hax.debug.diagnose_common_issues`][haliax.debug.diagnose_common_issues] -`hax.debug.diagnose_common_issues` is a function that will raise an exception if it detects problems with your module. +[haliax.debug.diagnose_common_issues][] is a function that will raise an exception if it detects problems with your module. Currently, we diagnose: * Reuse of arrays or NamedArrays in a field. [Equinox modules must be trees.](https://docs.kidger.site/equinox/faq/#a-module-saved-in-two-places-has-become-two-independent-copies) * Use of arrays or NamedArrays in a static field. Static data in JAX/Equinox must be hashable, and arrays are not hashable. -## Tip 2: `hax.debug.visualize_shardings` +## [`hax.debug.visualize_shardings`][haliax.debug.visualize_shardings] -Use `hax.debug.visualize_shardings` to quickly inspect how a PyTree is sharded. +Use [haliax.debug.visualize_shardings][] to quickly inspect how a PyTree is sharded. It prints the sharding of each array leaf, including the mapping from named axes to physical axes for :class:`haliax.NamedArray` leaves. diff --git a/docs/fp8.md b/docs/fp8.md index 6d49527..0810c87 100644 --- a/docs/fp8.md +++ b/docs/fp8.md @@ -115,7 +115,7 @@ module = hax.quantization.apply_updates(module, updates, grads) ``` That's it! Just a few lines of code to enable FP8. The `quantize_linear_layers` function will transform your module to use -quantization-aware training for linear layers (or a subset if you want), and the combo of `partition_for_grad_overwrite` and `apply_updates` function will apply the updates to the module +quantization-aware training for linear layers (or a subset if you want), and the combo of [haliax.quantization.partition_for_grad_overwrite][] and [haliax.quantization.apply_updates][] function will apply the updates to the module in a way that is compatible with FP8. ## How FP8 works @@ -140,7 +140,7 @@ depend on the gradients.) The way this happens is by "hijacking" the gradient computation. When you call `eqx.filter_grad(loss_fn)(module, data)`, you will get the gradient computation as normal, but you'll also get the updated state of the FP8 `dot_general` module. This updated state needs to directly replace the state in the module (rather than be used for a gradient step), which is -why you need to use the `partition_for_grad_overwrite` +why you need to use the [haliax.quantization.partition_for_grad_overwrite][] The FP8 `dot_general` module is implemented in [haliax.quantization.Fp8DotGeneralOp][]. It's actually not that complicated: diff --git a/docs/indexing.md b/docs/indexing.md index b1a3e35..cbaa716 100644 --- a/docs/indexing.md +++ b/docs/indexing.md @@ -101,7 +101,7 @@ two solutions: [haliax.slice][] and dynamic slices ([haliax.dslice][] a.k.a. [ha ## Dynamic Slices -[haliax.slice][] is a convenience function that wraps `jax.lax.dynamic_slice` and allows you to slice an array with a +[haliax.slice][] is a convenience function that wraps [jax.lax.dynamic_slice][] and allows you to slice an array with a dynamic start and size. This is useful for situations where you need to slice an array in a way that can't be determined at compile time. For example, the above example can be written as follows: @@ -124,7 +124,7 @@ def f(x, slice_size: int): In light of the requirement that all array sizes be known at compile time, Haliax provides both a simple [haliax.slice][] function, as well as [haliax.dslice][], which can be used with `[]`. The simple slice function is just a wrapper -around [jax.lax.dynamic_slice][]] and not worth discussing here. +around [jax.lax.dynamic_slice][] and not worth discussing here. `dslice` is a trick borrowed from the new experimental [jax.experimental.pallas][] module. It's essentially a slice, except that instead of a start and an end (and maybe a stride), it takes a start and a size. The size must be diff --git a/docs/matmul.md b/docs/matmul.md index 53391ea..50c9dae 100644 --- a/docs/matmul.md +++ b/docs/matmul.md @@ -11,7 +11,7 @@ more suitable for expressing a particular contraction In general: See also the API reference for [haliax.dot][] and [haliax.einsum][] and the [cheat sheet section](cheatsheet.md#matrix-multiplication). -### `haliax.dot` +### [`haliax.dot`][haliax.dot] With [haliax.dot][], you specify the axes to contract over, without needing to write out the axes you want to keep (though you can if you want): @@ -57,7 +57,7 @@ y = hax.dot(x, w, c, axis=()) # shape is (H, W, D, C), equivalent to np.einsum( y = hax.dot(x, w, c, axis=(), out_axes=(D, ..., H)) # shape is (D, W, C, H), equivalent to np.einsum("hwdc,dc,c->dwch", x, w, c) ``` -### `haliax.einsum` +### [`haliax.einsum`][haliax.einsum] [haliax.einsum][] is at its best when you want to express a more complex tensor contraction. It is similar to [numpy.einsum](https://numpy.org/doc/stable/reference/generated/numpy.einsum.html) diff --git a/docs/partitioning.md b/docs/partitioning.md index f27ab41..e04b6f3 100644 --- a/docs/partitioning.md +++ b/docs/partitioning.md @@ -80,7 +80,7 @@ with hax.axis_mapping({"batch": "data"}): ``` Unlike in JAX, which has separate APIs for partitioning arrays inside and outside of `jit`, Haliax has a single API: -`hax.shard` work inside and outside of `jit`. Haliax automatically +[haliax.shard][] works inside and outside of `jit`. Haliax automatically chooses which JAX function to use based on context. diff --git a/docs/scan.md b/docs/scan.md index f6809dd..019de4b 100644 --- a/docs/scan.md +++ b/docs/scan.md @@ -17,11 +17,11 @@ def scan(f, init, xs, length=None): return carry, np.stack(ys) ``` -Haliax provides two versions of this pattern: [haliax.fold][] and [haliax.scan][]. haliax.scan works much like JAX's scan, -except it is curried and it works with NamedArrays. haliax.fold is a more restricted version of scan that is easier to +Haliax provides two versions of this pattern: [haliax.fold][] and [haliax.scan][]. [haliax.scan][] works much like JAX's scan, +except it is curried and it works with NamedArrays. [haliax.fold][] is a more restricted version of scan that is easier to use if you don't need the full generality of scan. (It works with functions that only return `carry`, not `carry, output`.) -## `haliax.scan` +## [haliax.scan][haliax.scan] Unlike JAX's scan, Haliax's scan is curried - it takes the function and configuration first, then the initial carry and scan arguments as a separate call: `scan(f, axis)(init, xs)`. @@ -32,7 +32,7 @@ Unlike JAX's scan, Haliax's scan is curried - it takes the function and configur ### Basic Example -Here's a practical example of using `haliax.scan` to sum values along an axis while keeping track of intermediates: +Here's a practical example of using [haliax.scan][] to sum values along an axis while keeping track of intermediates: ```python Time = Axis("Time", 100) @@ -89,9 +89,9 @@ final_state, path = hax.scan(simulate_brownian_motion, Time)(init_state, None) More commonly, you might use this for an RNN or Transformer model. (See [haliax.nn.Stacked][].) -## `haliax.fold` +## [haliax.fold][haliax.fold] -`haliax.fold` is a simpler version of `haliax.scan` that is easier to use when you don't need the full generality of `scan`. +[haliax.fold][] is a simpler version of [haliax.scan][] that is easier to use when you don't need the full generality of `scan`. Specifically, `fold` is for functions that only return a `carry`, not a `carry, output`. Morally, `fold` is like this Python code: @@ -138,10 +138,10 @@ init_state = ( final_state = hax.fold(running_stats, Time)(init_state, data) ``` -## `haliax.map` +## [haliax.map][haliax.map] -`haliax.map` is a convenience function that applies a function to each element of an axis. It is similar -to [jax.lax.map][] but works with NamedArrays, providing a similar interface to `haliax.scan` and `haliax.fold`. +[haliax.map][] is a convenience function that applies a function to each element of an axis. It is similar +to [jax.lax.map][] but works with NamedArrays, providing a similar interface to [haliax.scan][] and [haliax.fold][]. ```python @@ -155,13 +155,13 @@ def my_fn(x): result = hax.map(my_fn, Time)(data) ``` -You should generally prefer to use [haliax.vmap][] instead of `haliax.map`, but it's there if you need it. -(It uses less memory than `haliax.vmap` but is slower.) +You should generally prefer to use [haliax.vmap][] instead of [haliax.map][], but it's there if you need it. +(It uses less memory than [haliax.vmap][] but is slower.) ## Gradient Checkpointing / Rematerialization -Both `haliax.scan` and `haliax.fold` support gradient checkpointing, which can be useful for deep models. +Both [haliax.scan][] and [haliax.fold][] support gradient checkpointing, which can be useful for deep models. Typically, you'd use this as part of [haliax.nn.Stacked][] or [haliax.nn.BlockSeq][] but you can also use it directly. Gradient checkpointing is a technique for reducing memory usage during backpropagation by recomputing some @@ -409,7 +409,7 @@ JAX array will have its first axis vmapped over. Sometimes you may want to apply each block independently, without feeding the output of one block into the next. `Stacked.vmap` does exactly that: it uses -[`haliax.vmap`][] to broadcast the initial value to every block and evaluates +[haliax.vmap][] to broadcast the initial value to every block and evaluates them in parallel, returning the stack of outputs. ```python commit 3d910bb950693d8c546b48de523f4212c3b6e0a9 Date: 2025-07-26T23:44:32-07:00 Clarify haliax.vmap axis usage (#183) diff --git a/docs/vmap.md b/docs/vmap.md index 5931e11..ca92cad 100644 --- a/docs/vmap.md +++ b/docs/vmap.md @@ -1,9 +1,38 @@ -## Vectorization +## Vectorization with `haliax.vmap` +`haliax.vmap` is a [`NamedArray`][haliax.NamedArray] aware wrapper around +[`jax.vmap`][jax.vmap]. Instead of supplying positional axis numbers you pass +the [`Axis`][haliax.Axis] (or axis name) you want to map over. Any +`NamedArray` containing that axis is mapped in parallel and the axis is +reinserted in the output. Regular JAX arrays can be mapped as well by +providing a `default` spec or per‑argument overrides. -This primitive is also used by [`Stacked.vmap`](scan.md#apply-blocks-in-parallel-with-vmap) -to apply an entire stack of blocks in parallel. +Unlike vanilla `jax.vmap`, you may supply **one or more axes**. When multiple +axes are given, the function is vmapped over each axis in turn (innermost first). +If an axis isn't already present in the array you must also specify its size, +either by passing an `Axis` object (`Axis("batch", 4)`) or a mapping such as +`{"batch": 4}` so the new dimension can be inserted. -(This is a work in progress. Please contact dlwh for more information.) +### Basic Example + +```python +import haliax as hax + +Batch = hax.Axis("batch", 4) + +def double(x): + return x * 2 + +x = hax.arange(Batch) +y = hax.vmap(double, Batch)(x) +``` + +The result `y` has the same `Batch` axis as `x`, and each element was processed +in parallel. With JAX you would write `jax.vmap(double)(x.array)` and manually +specify `in_axes`, but Haliax handles the axis automatically. + +For applying many modules in parallel see +[`Stacked.vmap`](scan.md#apply-blocks-in-parallel-with-vmap) which builds on this +primitive. ::: haliax.vmap commit ade2739a5db4964d97772031f81826b2b148ba4a Date: 2025-07-27T21:20:14-07:00 Add named bincount (#184) * Add named bincount * docs: document bincount and update guidelines diff --git a/.playbooks/wrap-non-named.md b/.playbooks/wrap-non-named.md index ccd6ac8..756fd0b 100644 --- a/.playbooks/wrap-non-named.md +++ b/.playbooks/wrap-non-named.md @@ -47,3 +47,6 @@ Some functions need bespoke handling. For example `jnp.unique` returns several a ## Testing Add tests to ensure that named and unnamed calls produce the same results and that axis names are preserved or removed correctly. + +## Documentation +Once your wrapper works, document it. Add `::: haliax.your_function` (replacing the name) to `docs/api.md` so users can find the new API. diff --git a/AGENTS.md b/AGENTS.md index 5c36ec5..b3f3560 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -41,7 +41,8 @@ repository. Follow these notes when implementing new features or fixing bugs. `[Object 1][full.path.object1]`) * **Documentation**: When adding new features, ensure that the documentation is updated accordingly. This includes updating the Mkdocs files and any relevant docstrings. If you add a new module or - significant functionality, consider adding a dedicated section in the documentation. + significant functionality, consider adding a dedicated section in the documentation. When you + wrap a new JAX function, add a reference to it in `docs/api.md` so users can discover it. ## Testing diff --git a/docs/api.md b/docs/api.md index ed79348..fc72d6a 100644 --- a/docs/api.md +++ b/docs/api.md @@ -256,6 +256,7 @@ These are all more or less directly from JAX's NumPy API. ### Other Operations +::: haliax.bincount ::: haliax.clip ::: haliax.isclose ::: haliax.pad diff --git a/src/haliax/__init__.py b/src/haliax/__init__.py index b3f02a2..a043db9 100644 --- a/src/haliax/__init__.py +++ b/src/haliax/__init__.py @@ -79,6 +79,7 @@ from .ops import ( unique_counts, unique_inverse, unique_all, + bincount, where, ) from .partitioning import auto_sharded, axis_mapping, fsdp, named_jit, shard, shard_with_axis_mapping @@ -1053,6 +1054,7 @@ __all__ = [ "unique_counts", "unique_inverse", "unique_all", + "bincount", "clip", "tril", "triu", diff --git a/src/haliax/ops.py b/src/haliax/ops.py index 2bf39bd..2a17b49 100644 --- a/src/haliax/ops.py +++ b/src/haliax/ops.py @@ -430,6 +430,33 @@ def unique_all( return values, indices, inverse, counts +def bincount( + x: NamedArray, + Counts: Axis, + *, + weights: NamedArray | ArrayLike | None = None, + minlength: int = 0, +) -> NamedArray: + """Named version of `jax.numpy.bincount`. + + The output axis is specified by ``Counts``. + """ + + if x.ndim != 1: + raise ValueError("bincount only supports 1D arrays") + + w_array = None + if weights is not None: + if isinstance(weights, NamedArray): + weights = haliax.broadcast_to(weights, x.axes) + w_array = weights.array + else: + w_array = jnp.asarray(weights) + + result = jnp.bincount(x.array, weights=w_array, minlength=minlength, length=Counts.size) + return NamedArray(result, (Counts,)) + + __all__ = [ "trace", "where", @@ -444,4 +471,5 @@ __all__ = [ "unique_counts", "unique_inverse", "unique_all", + "bincount", ] diff --git a/tests/test_ops.py b/tests/test_ops.py index 2a51efa..997e52e 100644 --- a/tests/test_ops.py +++ b/tests/test_ops.py @@ -407,3 +407,19 @@ def test_unique_shortcuts(): assert jnp.all(ia.array == ia_exp.array) assert jnp.all(ina.array == ina_exp.array) assert jnp.all(ca.array == ca_exp.array) + + +def test_bincount(): + X = Axis("X", 6) + x = hax.named([0, 1, 1, 2, 3, 1], (X,)) + B = Axis("B", 5) + + out = hax.bincount(x, B) + expected = jnp.bincount(x.array, length=B.size) + assert out.axes == (B,) + assert jnp.all(out.array == expected) + + w = hax.arange((X,), dtype=jnp.float32) + out_w = hax.bincount(x, B, weights=w) + expected_w = jnp.bincount(x.array, weights=w.array, length=B.size) + assert jnp.allclose(out_w.array, expected_w) commit 901d33d05b7aa71ffc58f150959f03acd67ffb03 Date: 2025-07-29T12:57:48-07:00 Add gmm path test for MoELinear (#189) diff --git a/tests/test_moe_linear.py b/tests/test_moe_linear.py new file mode 100644 index 0000000..f8d85e7 --- /dev/null +++ b/tests/test_moe_linear.py @@ -0,0 +1,70 @@ +import jax +import jax.random as jrandom +from jax import numpy as jnp + +import haliax as hax +from haliax.nn import MoELinear + + +def _expected_moe_linear_output(moe: MoELinear, x: hax.NamedArray, group_sizes: hax.NamedArray): + dim_numbers = jax.lax.RaggedDotDimensionNumbers( + ( + ((x.axis_indices(moe.In),), (moe.weight.axis_indices(moe.In),)), + ((), ()), + ), + x.axis_indices(hax.axis.without_axes(x.axes, moe.In)), + (moe.weight.axis_indices(moe.Experts),), + ) + out_raw = jax.lax.ragged_dot_general( + lhs=x.array, + rhs=moe.weight.array, + group_sizes=group_sizes.array, + ragged_dot_dimension_numbers=dim_numbers, + ) + out_axes = hax.replace_axis(x.axes, moe.In, moe.Out) + out = hax.named(out_raw, out_axes) + if moe.bias is not None: + out = out + moe.bias + return out + + +def test_moe_linear_matches_ragged_dot_general(): + B, In, Out, E = hax.make_axes(B=3, In=4, Out=5, E=2) + key = jrandom.PRNGKey(0) + moe = MoELinear.init(E, In, Out, key=key) + + x = hax.random.normal(jrandom.PRNGKey(1), (B, In)) + group_sizes = hax.named(jnp.array([2, 1], dtype=jnp.int32), (E,)) + + actual = moe(x, group_sizes) + expected = _expected_moe_linear_output(moe, x, group_sizes) + + assert actual.axes == expected.axes + assert jnp.allclose(actual.array, expected.array, rtol=1e-5, atol=1e-5) + + +def test_moe_linear_out_first_property(): + E, In, Out = hax.make_axes(E=2, In=4, Out=3) + moe = MoELinear.init(E, In, Out, key=jrandom.PRNGKey(0), out_first=True) + assert moe.out_first + assert moe.weight.axes[:3] == (E, Out, In) + + moe2 = MoELinear.init(E, In, Out, key=jrandom.PRNGKey(1), out_first=False) + assert not moe2.out_first + assert moe2.weight.axes[:3] == (E, In, Out) + + +def test_moe_linear_gmm_matches_ragged_dot_general(): + B, In, Out, E = hax.make_axes(B=3, In=4, Out=5, E=2) + moe = MoELinear.init(E, In, Out, key=jrandom.PRNGKey(0), use_gmm=True) + + x = hax.random.normal(jrandom.PRNGKey(1), (B, In)) + group_sizes = hax.named(jnp.array([2, 1], dtype=jnp.int32), (E,)) + + with jax.sharding.Mesh(jax.devices(), ("data",)): + actual = moe(x, group_sizes) + + expected = _expected_moe_linear_output(moe, x, group_sizes) + + assert actual.axes == expected.axes + assert jnp.allclose(actual.array, expected.array, rtol=1e-5, atol=1e-5) commit e1e4bf0d25f16f151fd2e617855337da809cb246 Date: 2025-08-01T09:00:38-07:00 support scalar NamedArray shift in roll (#190) diff --git a/src/haliax/core.py b/src/haliax/core.py index e38cf0d..b49c8e2 100644 --- a/src/haliax/core.py +++ b/src/haliax/core.py @@ -1361,13 +1361,26 @@ def unbind(array: NamedArray, axis: AxisSelector) -> List[NamedArray]: return [haliax.auto_sharded(NamedArray(a, new_axes)) for a in arrays] -def roll(array: NamedArray, shift: Union[int, Tuple[int, ...]], axis: AxisSelection) -> NamedArray: - """ - Roll an array along an axis or axes. Analogous to np.roll +def roll( + array: NamedArray, + shift: Union[IntScalar, Tuple[int, ...], "NamedArray"], + axis: AxisSelection, +) -> NamedArray: + """Roll an array along an axis or axes. + + ``shift`` may be a scalar ``NamedArray`` in addition to an ``int`` or tuple of + integers. """ + axis_indices = array.axis_indices(axis) if axis_indices is None: raise ValueError(f"axis {axis} not found in {array}") + + if isinstance(shift, NamedArray): + if shift.ndim != 0: + raise TypeError("shift must be a scalar NamedArray") + shift = shift.array + return NamedArray(jnp.roll(array.array, shift, axis_indices), array.axes) diff --git a/tests/test_ops.py b/tests/test_ops.py index 997e52e..93d139a 100644 --- a/tests/test_ops.py +++ b/tests/test_ops.py @@ -423,3 +423,17 @@ def test_bincount(): out_w = hax.bincount(x, B, weights=w) expected_w = jnp.bincount(x.array, weights=w.array, length=B.size) assert jnp.allclose(out_w.array, expected_w) + + +def test_roll_scalar_named_shift(): + H = Axis("H", 4) + W = Axis("W", 3) + + arr = hax.arange((H, W)) + shift = hax.named(jnp.array(1), ()) + + rolled = hax.roll(arr, shift, H) + expected = jnp.roll(arr.array, shift.array, axis=0) + + assert rolled.axes == arr.axes + assert jnp.all(rolled.array == expected) commit 48a241a065983df536690e37ae94537209979b7a Date: 2025-08-01T16:10:03-07:00 add ensure_scalar helper and use it (#191) diff --git a/src/haliax/core.py b/src/haliax/core.py index b49c8e2..4ecd35b 100644 --- a/src/haliax/core.py +++ b/src/haliax/core.py @@ -15,7 +15,7 @@ import numpy as np import haliax import haliax.axis -from haliax.jax_utils import is_jax_array_like, is_pallas_dslice +from haliax.jax_utils import ensure_scalar, is_jax_array_like, is_pallas_dslice from haliax.util import ensure_tuple from ._src.util import index_where, py_slice, slice_t @@ -1115,9 +1115,7 @@ def updated_slice( if axis_index is None: raise ValueError(f"axis {axis} not found in {array}") if isinstance(s, NamedArray): # this can happen in the vmap case - if s.ndim != 0: - raise ValueError(f"NamedArray {s} must be a scalar for axis {axis} in updated_slice") - s = s.scalar() + s = ensure_scalar(s, name=str(axis)) array_slice_indices[axis_index] = s total_length = array.axes[axis_index].size @@ -1376,10 +1374,7 @@ def roll( if axis_indices is None: raise ValueError(f"axis {axis} not found in {array}") - if isinstance(shift, NamedArray): - if shift.ndim != 0: - raise TypeError("shift must be a scalar NamedArray") - shift = shift.array + shift = ensure_scalar(shift, name="shift") return NamedArray(jnp.roll(array.array, shift, axis_indices), array.axes) diff --git a/src/haliax/jax_utils.py b/src/haliax/jax_utils.py index 06066da..eb8edc7 100644 --- a/src/haliax/jax_utils.py +++ b/src/haliax/jax_utils.py @@ -153,6 +153,21 @@ def is_scalarish(x): return jnp.isscalar(x) or (getattr(x, "shape", None) == ()) +def ensure_scalar(x, *, name: str = "value"): + """Return ``x`` if it is not a :class:`NamedArray`, otherwise ensure it is a scalar. + + This is useful for APIs that can accept either Python scalars or scalar + ``NamedArray`` objects (for example ``roll`` or ``updated_slice``). If ``x`` + is a ``NamedArray`` with rank greater than 0 a :class:`TypeError` is raised. + """ + + if isinstance(x, haliax.NamedArray): + if x.ndim != 0: + raise TypeError(f"{name} must be a scalar NamedArray") + return x.array + return x + + def is_on_mac_metal(): return jax.devices()[0].platform.lower() == "metal" diff --git a/src/haliax/ops.py b/src/haliax/ops.py index 2a17b49..251e2c2 100644 --- a/src/haliax/ops.py +++ b/src/haliax/ops.py @@ -9,7 +9,7 @@ import haliax from .axis import Axis, AxisSelector, axis_name from .core import NamedArray, NamedOrNumeric, broadcast_arrays, broadcast_arrays_and_return_axes, named -from .jax_utils import is_scalarish +from .jax_utils import ensure_scalar, is_scalarish def trace(array: NamedArray, axis1: AxisSelector, axis2: AxisSelector, offset=0, dtype=None) -> NamedArray: @@ -89,7 +89,7 @@ def where( x = named(x, ()) x, y = broadcast_arrays(x, y) if isinstance(condition, NamedArray): - condition = condition.scalar() + condition = ensure_scalar(condition, name="condition") return jax.lax.cond(condition, lambda _: x, lambda _: y, None) condition, x, y = broadcast_arrays(condition, x, y) # type: ignore diff --git a/src/haliax/wrap.py b/src/haliax/wrap.py index df57f40..fc073ee 100644 --- a/src/haliax/wrap.py +++ b/src/haliax/wrap.py @@ -5,7 +5,7 @@ import jax from haliax.core import NamedArray, _broadcast_order, broadcast_to from .axis import AxisSelection, AxisSelector, axis_spec_to_shape_dict, eliminate_axes -from .jax_utils import is_scalarish +from .jax_utils import ensure_scalar, is_scalarish def wrap_elemwise_unary(f, a, *args, **kwargs): @@ -105,7 +105,7 @@ def wrap_elemwise_binary(op): else: if is_scalarish(b): return NamedArray(op(a.array, b), a.axes) - a = a.scalar() + a = ensure_scalar(a) return op(a, b) return NamedArray(op(a.array, b), a.axes) @@ -119,7 +119,7 @@ def wrap_elemwise_binary(op): else: if is_scalarish(a): return NamedArray(op(a, b.array), b.axes) - b = b.scalar() + b = ensure_scalar(b) return op(a, b) return NamedArray(op(a, b.array), b.axes) diff --git a/tests/test_ops.py b/tests/test_ops.py index 93d139a..d7eacd8 100644 --- a/tests/test_ops.py +++ b/tests/test_ops.py @@ -437,3 +437,14 @@ def test_roll_scalar_named_shift(): assert rolled.axes == arr.axes assert jnp.all(rolled.array == expected) + + +def test_roll_bad_named_shift(): + H = Axis("H", 4) + W = Axis("W", 3) + + arr = hax.arange((H, W)) + shift = hax.arange((Axis("dummy", 2),)) + + with pytest.raises(TypeError): + hax.roll(arr, shift, H) commit 3aaaf19b652917bfd4eb753688b42884b989195a Date: 2025-08-13T23:15:19-07:00 refactor infer_resource_partitions to use pspec_for (#192) diff --git a/src/haliax/partitioning.py b/src/haliax/partitioning.py index 20ba373..f1d81d0 100644 --- a/src/haliax/partitioning.py +++ b/src/haliax/partitioning.py @@ -177,24 +177,21 @@ def shard_with_axis_mapping(x: T, mapping: ResourceMapping, mesh: Optional[Mesh] return shard(x, mapping, mesh) -def infer_resource_partitions( +def pspec_for( tree: PyTree, resource_mapping: Optional[ResourceMapping] = None, preserve_existing_shardings: bool = True, use_auto_sharding: bool = True, - mesh: Optional[Mesh] = None, ) -> PyTree: - """ - Infer the sharding for a module, to be used with named_jit. - The basic idea is to tree all NamedArrays as leaves for the purposes of this function, - and to create NamedShardings from those names plus the resource_mapping. - If preserve_existing_shardings is True, then NamedArrays that are already sharded are left alone. + """Infer the :class:`PartitionSpec` for a module. - If resource_mapping is not provided, this function attempts to use the global resource mapping. + This behaves like :func:`infer_resource_partitions` but returns ``PartitionSpec`` + objects instead of :class:`~jax.sharding.NamedSharding`. It is primarily a helper + for :func:`infer_resource_partitions` but may be useful when only the partition + specification is required. - If use_auto_sharding is True, then we use the new experimental AUTO-sharding feature, which is not yet - fully supported by JAX. If it is False, then we will guess fully replicated for any unnamed arrays that - don't have a sharding. + If ``preserve_existing_shardings`` is ``True``, then arrays that already have a + sharding are left untouched and ``None`` is returned for those leaves. """ if resource_mapping is None: resource_mapping = current_thread_local_mapping() @@ -202,35 +199,26 @@ def infer_resource_partitions( if resource_mapping is None: raise ValueError("No resource mapping found") - mesh = mesh or _get_mesh() - assert not isinstance(mesh, dict) - def partition_spec(node: typing.Any): if isinstance(node, NamedArray): # If our NamedArray doesn't have an array (or a shapedtypestruct), we can't shard it - # so better to not try if not is_jax_array_like(node.array): return None - if preserve_existing_shardings: - current_sharding = getattr(node.array, "sharding", None) - else: - current_sharding = None - + current_sharding = getattr(node.array, "sharding", None) if preserve_existing_shardings else None if current_sharding is not None: - return current_sharding + return None else: - sharding = NamedSharding(mesh, pspec_for_axis(node.axes, resource_mapping)) - return sharding + return pspec_for_axis(node.axes, resource_mapping) elif is_jax_array_like(node): sharding = getattr(node, "sharding", None) # TODO: these are usually replicated. Is there a better way to tell? if node.shape == (): - return NamedSharding(mesh, PartitionSpec()) + return PartitionSpec() elif isinstance(sharding, SingleDeviceSharding): - return NamedSharding(mesh, PartitionSpec(None)) - elif sharding is not None: - return sharding + return PartitionSpec(None) + elif sharding is not None and preserve_existing_shardings: + return None # elif use_auto_sharding: # TODO: auto doesn't seem to really work reliably yet # compat between 0.4.10 and 0.4.11 @@ -238,15 +226,54 @@ def infer_resource_partitions( # return AUTO(mesh) # else: # return AUTO - return NamedSharding(mesh, PartitionSpec(None)) + return PartitionSpec(None) elif isinstance(node, (bool, float, complex, int)): - return NamedSharding(mesh, PartitionSpec()) + return PartitionSpec() else: return None return htu.tree_map(partition_spec, tree) +def infer_resource_partitions( + tree: PyTree, + resource_mapping: Optional[ResourceMapping] = None, + preserve_existing_shardings: bool = True, + use_auto_sharding: bool = True, + mesh: Optional[Mesh] = None, +) -> PyTree: + """ + Infer the sharding for a module, to be used with ``named_jit``. + + This first calls :func:`pspec_for` to compute ``PartitionSpec`` objects and then + wraps them in :class:`~jax.sharding.NamedSharding` using the provided mesh. If + ``preserve_existing_shardings`` is ``True``, then arrays that are already sharded + retain their current sharding. + """ + pspecs = pspec_for( + tree, + resource_mapping=resource_mapping, + preserve_existing_shardings=preserve_existing_shardings, + use_auto_sharding=use_auto_sharding, + ) + + mesh = mesh or _get_mesh() + assert not isinstance(mesh, dict) + + def to_sharding(node: typing.Any, spec: typing.Any): + if spec is None: + if isinstance(node, NamedArray): + return getattr(node.array, "sharding", None) + elif is_jax_array_like(node): + return getattr(node, "sharding", None) + else: + return None + else: + return NamedSharding(mesh, spec) + + return htu.tree_map(to_sharding, tree, pspecs) + + class WrappedCallable(typing.Protocol[Args, R]): """ A wrapper for a callable that preserves the original function's name and qualname. @@ -659,6 +686,7 @@ __all__ = [ "auto_sharded", "shard", "shard_with_axis_mapping", + "pspec_for", "infer_resource_partitions", "named_jit", "fsdp", diff --git a/tests/test_partitioning.py b/tests/test_partitioning.py index c1768ee..cb91206 100644 --- a/tests/test_partitioning.py +++ b/tests/test_partitioning.py @@ -7,7 +7,13 @@ from jaxtyping import Array import haliax as hax from haliax import Axis, NamedArray -from haliax.partitioning import ResourceAxis, axis_mapping, infer_resource_partitions, named_jit +from haliax.partitioning import ( + ResourceAxis, + axis_mapping, + infer_resource_partitions, + named_jit, + pspec_for, +) from test_utils import skip_if_not_enough_devices @@ -40,6 +46,19 @@ def test_infer_named_axes(): assert axes.unnamed1.is_fully_replicated +def test_pspec_for_named_axes(): + mesh = Mesh(np.array(jax.devices()).reshape(-1, 1), (ResourceAxis.DATA, ResourceAxis.MODEL)) + with axis_mapping(resource_map), mesh: + mod = MyModule(named=hax.ones((Dim1, Dim2, Dim3)), unnamed1=jnp.ones(Dim2.size), static_field=1) + + specs: MyModule = pspec_for(mod, preserve_existing_shardings=False) + + spec = PartitionSpec(None, ResourceAxis.DATA, ResourceAxis.MODEL) + + assert specs.named == spec + assert specs.unnamed1 == PartitionSpec(None) + + class MyModuleInit(eqx.Module): named: NamedArray unnamed1: Array commit e6003fc3e2748f25e44cc4634de20354581bfc9d Date: 2025-08-13T23:15:38-07:00 Add field wrapper with axis names metadata (#193) diff --git a/src/haliax/__init__.py b/src/haliax/__init__.py index a043db9..c252ac2 100644 --- a/src/haliax/__init__.py +++ b/src/haliax/__init__.py @@ -17,6 +17,7 @@ import haliax.random as random import haliax.state_dict as state_dict import haliax.tree_util as tree_util import haliax.util as util +from .field import field from ._src.dot import dot from ._src.einsum import einsum @@ -932,6 +933,7 @@ __all__ = [ "tree_util", "nn", "state_dict", + "field", "Axis", "AxisSpec", "AxisSelection", diff --git a/src/haliax/field.py b/src/haliax/field.py new file mode 100644 index 0000000..b420f88 --- /dev/null +++ b/src/haliax/field.py @@ -0,0 +1,38 @@ +from __future__ import annotations + +from typing import Any, Callable + +import equinox as eqx + + +def field( + *, + converter: Callable[[Any], Any] | None = None, + static: bool = False, + axis_names: tuple[str, ...] | None = None, + **kwargs, +): + """Wrapper around :func:`equinox.field` with optional ``axis_names`` metadata. + + Args: + converter: Optional function applied to the value during dataclass initialisation. + static: Whether the field is static in the PyTree. + axis_names: Optional axis names associated with array fields. Cannot be + specified together with ``static=True``. + **kwargs: Additional keyword arguments forwarded to :func:`dataclasses.field`. + + Returns: + A dataclasses field configured like :func:`equinox.field` with additional + ``axis_names`` metadata. + """ + if static and axis_names is not None: + raise ValueError("axis_names cannot be specified together with static=True") + + metadata = dict(kwargs.pop("metadata", {})) + metadata["axis_names"] = axis_names + + field_kwargs = {} + if converter is not None: + field_kwargs["converter"] = converter + + return eqx.field(static=static, metadata=metadata, **field_kwargs, **kwargs) diff --git a/tests/test_field.py b/tests/test_field.py new file mode 100644 index 0000000..e5b9cf1 --- /dev/null +++ b/tests/test_field.py @@ -0,0 +1,19 @@ +import jax.numpy as jnp +import equinox as eqx +import pytest + +import haliax as hax + + +class M(eqx.Module): + a: jnp.ndarray = hax.field(axis_names=("batch",)) + + +def test_axis_names_metadata(): + field = M.__dataclass_fields__["a"] + assert field.metadata["axis_names"] == ("batch",) + + +def test_axis_names_static_exclusive(): + with pytest.raises(ValueError): + hax.field(static=True, axis_names=("x",)) commit 30066d0a1eea3d282580a5a5fef815211d005abb Date: 2025-08-15T15:11:45-07:00 Remove axis_names annotation from nested module test (#194) diff --git a/src/haliax/partitioning.py b/src/haliax/partitioning.py index f1d81d0..6bb2133 100644 --- a/src/haliax/partitioning.py +++ b/src/haliax/partitioning.py @@ -1,4 +1,5 @@ import contextlib +import dataclasses import functools import threading import typing @@ -210,6 +211,37 @@ def pspec_for( return None else: return pspec_for_axis(node.axes, resource_mapping) + elif isinstance(node, eqx.Module): + # handle eqx.Module explicitly so that we can look at axis_names metadata + updates: dict[str, typing.Any] = {} + for field in dataclasses.fields(node): + if field.metadata.get("static", False): + continue + + value = getattr(node, field.name) + axis_names = field.metadata.get("axis_names") if field.metadata is not None else None + if axis_names is not None and is_jax_array_like(value): + current_sharding = ( + getattr(value, "sharding", None) if preserve_existing_shardings else None + ) + if current_sharding is not None: + updates[field.name] = None + else: + updates[field.name] = pspec_for_axis(axis_names, resource_mapping) + else: + updates[field.name] = htu.tree_map( + partition_spec, value, is_leaf=lambda x: isinstance(x, eqx.Module) + ) + + new_node = object.__new__(type(node)) + for field in dataclasses.fields(node): + object.__setattr__( + new_node, + field.name, + updates.get(field.name, getattr(node, field.name)), + ) + + return new_node elif is_jax_array_like(node): sharding = getattr(node, "sharding", None) # TODO: these are usually replicated. Is there a better way to tell? @@ -232,7 +264,7 @@ def pspec_for( else: return None - return htu.tree_map(partition_spec, tree) + return htu.tree_map(partition_spec, tree, is_leaf=lambda x: isinstance(x, eqx.Module)) def infer_resource_partitions( diff --git a/tests/test_partitioning.py b/tests/test_partitioning.py index cb91206..ef4026b 100644 --- a/tests/test_partitioning.py +++ b/tests/test_partitioning.py @@ -59,6 +59,34 @@ def test_pspec_for_named_axes(): assert specs.unnamed1 == PartitionSpec(None) +class ArrayModule(eqx.Module): + arr: Array = hax.field(axis_names=("dim2", "dim3")) + + +def test_pspec_for_plain_array_axis_names(): + mesh = Mesh(np.array(jax.devices()).reshape(-1, 1), (ResourceAxis.DATA, ResourceAxis.MODEL)) + with axis_mapping(resource_map), mesh: + mod = ArrayModule(jnp.ones((Dim2.size, Dim3.size))) + + specs: ArrayModule = pspec_for(mod, preserve_existing_shardings=False) + + assert specs.arr == PartitionSpec(ResourceAxis.DATA, ResourceAxis.MODEL) + + +class NestedArrayModule(eqx.Module): + inner: ArrayModule + + +def test_pspec_for_plain_array_axis_names_nested_module(): + mesh = Mesh(np.array(jax.devices()).reshape(-1, 1), (ResourceAxis.DATA, ResourceAxis.MODEL)) + with axis_mapping(resource_map), mesh: + mod = NestedArrayModule(ArrayModule(jnp.ones((Dim2.size, Dim3.size)))) + + specs: NestedArrayModule = pspec_for(mod, preserve_existing_shardings=False) + + assert specs.inner.arr == PartitionSpec(ResourceAxis.DATA, ResourceAxis.MODEL) + + class MyModuleInit(eqx.Module): named: NamedArray unnamed1: Array commit 08e990377453a613471d4a289001d8dce290ef58 Date: 2025-09-04T21:13:00-07:00 Improve scan error when unnamed arrays mismatch axis (#202) * test: check eqx module field in scan mismatch error * Improve scan error paths with argument names diff --git a/src/haliax/_src/scan.py b/src/haliax/_src/scan.py index 661934f..1373988 100644 --- a/src/haliax/_src/scan.py +++ b/src/haliax/_src/scan.py @@ -1,9 +1,11 @@ import dataclasses import functools as ft +import inspect from typing import Any, Callable, Literal, ParamSpec, Protocol, Sequence, Tuple, TypeVar, Union, overload import equinox as eqx import jax +import jax.tree_util as jtu from jaxtyping import PyTree import haliax @@ -357,7 +359,46 @@ def scan( return carry, y true_axis = _infer_axis_size_from_tree(axis_first_xs, axis) - axis_size = _infer_axis_size_from_tree(axis_first_xs, axis).size + axis_size = true_axis.size + + # build a mapping from positional argument indices to their names for friendlier error messages + sig = inspect.signature(f) + arg_pos_names: dict[int, str] = {} + params = list(sig.parameters.values())[1:] # skip carry + pos_count = 0 + var_pos_name: str | None = None + for param in params: + if param.kind in ( + inspect.Parameter.POSITIONAL_ONLY, + inspect.Parameter.POSITIONAL_OR_KEYWORD, + ): + arg_pos_names[pos_count] = param.name + pos_count += 1 + elif param.kind == inspect.Parameter.VAR_POSITIONAL: + var_pos_name = param.name + break + if var_pos_name is not None: + for i in range(pos_count, len(args)): + arg_pos_names[i] = f"{var_pos_name}[{i - pos_count}]" + + path_leaves, _ = jtu.tree_flatten_with_path(axis_first_xs, is_leaf=is_named_array) + mismatched = [] + for path, leaf in path_leaves: + if isinstance(leaf, NamedArray): + lead_size = leaf.array.shape[0] + elif is_jax_array_like(leaf): + lead_size = leaf.shape[0] + else: + continue + if lead_size != axis_size: + mismatched.append((path, lead_size)) + if mismatched: + details = ", ".join( + f"{_format_tree_path(p, arg_pos_names)} has leading dimension {s}" for p, s in mismatched + ) + raise ValueError( + f"scan got `length` argument of {axis_size} but some inputs had different leading axis sizes: {details}" + ) nested_scan = checkpoint.nested outer_block_size = nested_scan_outer_block(nested_scan, axis_size) @@ -508,6 +549,36 @@ def _zero_if_array_else_none(x: Any) -> ResolvedUnnamedAxisSpec: return 0 if is_jax_array_like(x) else None +def _format_tree_path( + path: tuple[jtu.KeyEntry, ...], arg_pos_names: dict[int, str] | None = None +) -> str: + parts: list[str] = [] + i = 0 + if len(path) >= 2 and isinstance(path[0], jtu.SequenceKey): + if path[0].idx == 0 and isinstance(path[1], jtu.SequenceKey): + name = (arg_pos_names or {}).get(path[1].idx) + if name is not None: + parts.append(name) + else: + parts.append(f"[{path[1].idx}]") + i = 2 + elif path[0].idx == 1 and isinstance(path[1], jtu.DictKey): + parts.append(str(path[1].key)) + i = 2 + for p in path[i:]: + if isinstance(p, jtu.GetAttrKey): + parts.append("." + p.name) + elif isinstance(p, jtu.DictKey): + parts.append(f"[{p.key!r}]") + elif isinstance(p, jtu.SequenceKey): + parts.append(f"[{p.idx}]") + else: # pragma: no cover - future-proofing + parts.append(str(p)) + if parts and parts[0].startswith("."): + parts[0] = parts[0][1:] + return "".join(parts) or "<root>" + + def _infer_axis_size_from_tree(result, axis): if isinstance(axis, str): result_leaves = jax.tree_util.tree_leaves(result, is_leaf=_is_passive_array) diff --git a/tests/test_hof.py b/tests/test_hof.py index 1df5999..e0e3415 100644 --- a/tests/test_hof.py +++ b/tests/test_hof.py @@ -5,6 +5,7 @@ from jax.random import PRNGKey import haliax as hax from haliax import Axis, NamedArray from haliax.util import is_named_array +import pytest def test_scan(): @@ -136,6 +137,38 @@ def test_scan_hierarchical(): assert jnp.all(jnp.equal(selected.array, selected_blocked.array)) +def test_scan_reports_mismatched_unnamed_array(): + Height = Axis("Height", 2) + + def f(c, x, y): + return c, x + y + + good = jnp.zeros((Height.size, 3)) + bad = jnp.zeros((Height.size - 1, 3)) + + with pytest.raises(ValueError) as e: + hax.scan(f, Height)(0, good, y=bad) + + assert "y has leading dimension" in str(e.value) + + +def test_scan_reports_eqx_module_field_path(): + Height = Axis("Height", 2) + + class Foo(eqx.Module): + my_array: jnp.ndarray + + foo = Foo(jnp.zeros((Height.size - 1, 3))) + + def f(c, foo): + return c, foo.my_array + + with pytest.raises(ValueError) as e: + hax.scan(f, Height)(0, foo) + + assert "foo.my_array" in str(e.value) + + def test_fold(): Height = Axis("Height", 10) Width = Axis("Width", 3) commit 52580bce30461907cd637a86af5c8930cece3563 Date: 2025-09-11T11:25:38-07:00 Add NamedArray wrapper for searchsorted (#203) diff --git a/docs/api.md b/docs/api.md index fc72d6a..67e4fe9 100644 --- a/docs/api.md +++ b/docs/api.md @@ -260,6 +260,7 @@ These are all more or less directly from JAX's NumPy API. ::: haliax.clip ::: haliax.isclose ::: haliax.pad +::: haliax.searchsorted ::: haliax.top_k ::: haliax.trace ::: haliax.tril diff --git a/src/haliax/__init__.py b/src/haliax/__init__.py index c252ac2..5e06d7c 100644 --- a/src/haliax/__init__.py +++ b/src/haliax/__init__.py @@ -80,6 +80,7 @@ from .ops import ( unique_counts, unique_inverse, unique_all, + searchsorted, bincount, where, ) @@ -1056,6 +1057,7 @@ __all__ = [ "unique_counts", "unique_inverse", "unique_all", + "searchsorted", "bincount", "clip", "tril", diff --git a/src/haliax/ops.py b/src/haliax/ops.py index 251e2c2..ca0ce64 100644 --- a/src/haliax/ops.py +++ b/src/haliax/ops.py @@ -430,6 +430,34 @@ def unique_all( return values, indices, inverse, counts +def searchsorted( + a: NamedArray, + v: NamedArray | ArrayLike, + *, + side: str = "left", + sorter: NamedArray | ArrayLike | None = None, + method: str = "scan", +) -> NamedArray: + """Named version of `jax.numpy.searchsorted`. + + ``a`` and ``sorter`` (if provided) must be one-dimensional. + The returned array has the same axes as ``v``. + """ + + if a.ndim != 1: + raise ValueError("searchsorted only supports 1D 'a'") + + if not isinstance(v, NamedArray): + v = haliax.named(v, ()) + + sorter_arr = None + if sorter is not None: + sorter_arr = sorter.array if isinstance(sorter, NamedArray) else jnp.asarray(sorter) + + result = jnp.searchsorted(a.array, v.array, side=side, sorter=sorter_arr, method=method) + return NamedArray(result, v.axes) + + def bincount( x: NamedArray, Counts: Axis, @@ -471,5 +499,6 @@ __all__ = [ "unique_counts", "unique_inverse", "unique_all", + "searchsorted", "bincount", ] diff --git a/tests/core_test.py b/tests/core_test.py index 4e7757d..201f16e 100644 --- a/tests/core_test.py +++ b/tests/core_test.py @@ -238,6 +238,26 @@ def test_cumsum_etc(): assert hax.argsort(named1, axis=Width).axes == (Height, Width, Depth) +def test_searchsorted(): + A = hax.Axis("a", 5) + V = hax.Axis("v", 4) + + a = hax.named([1, 3, 5, 7, 9], axis=A) + v = hax.named([0, 3, 6, 10], axis=V) + + result = hax.searchsorted(a, v) + assert jnp.all(result.array == jnp.searchsorted(a.array, v.array)) + assert result.axes == (V,) + + unsorted = hax.named([5, 1, 3, 7, 4], axis=A) + sorter = hax.argsort(unsorted, axis=A) + result = hax.searchsorted(unsorted, v, sorter=sorter, side="right") + assert jnp.all( + result.array == jnp.searchsorted(unsorted.array, v.array, sorter=sorter.array, side="right") + ) + assert result.axes == (V,) + + def test_rearrange(): H, W, D, C = hax.make_axes(H=2, W=3, D=4, C=5) commit 665ad260931b1695793fa0598c5ea507da21defc Date: 2025-09-11T17:00:41-07:00 docs: prune api parity list (#204) diff --git a/.agents/projects/api_parity.md b/.agents/projects/api_parity.md new file mode 100644 index 0000000..b60b4d9 --- /dev/null +++ b/.agents/projects/api_parity.md @@ -0,0 +1,215 @@ +# JAX NumPy API Parity +This document tracks JAX NumPy functions not yet wrapped by Haliax. + +APIs that don't translate well to named tensors are intentionally omitted here. This includes dtype constructors, raw array converters (e.g. `from_dlpack`), indexing helpers like `c_`/`r_`, and functions whose JAX counterparts already work with `NamedArray` out of the box. Basic array construction is handled by `haliax.named`, so functions such as `array` or `asarray` are not listed. + +## numpy +- [ ] `allclose` +- [ ] `amin` +- [ ] `append` +- [ ] `apply_along_axis` +- [ ] `apply_over_axes` +- [ ] `argpartition` +- [ ] `argwhere` +- [ ] `array_equal` +- [ ] `array_equiv` +- [ ] `array_split` +- [ ] `astype` +- [ ] `atan2` +- [ ] `average` +- [ ] `bartlett` +- [ ] `bitwise_count` +- [ ] `bitwise_invert` +- [ ] `bitwise_left_shift` +- [ ] `bitwise_right_shift` +- [ ] `blackman` +- [ ] `block` +- [ ] `broadcast_shapes` +- [ ] `can_cast` +- [ ] `choose` +- [ ] `column_stack` +- [ ] `compress` +- [ ] `concat` +- [ ] `convolve` +- [ ] `copysign` +- [ ] `corrcoef` +- [ ] `correlate` +- [ ] `count_nonzero` +- [ ] `cov` +- [ ] `cumulative_prod` +- [ ] `cumulative_sum` +- [ ] `delete` +- [ ] `diag` +- [ ] `diag_indices` +- [ ] `diag_indices_from` +- [ ] `diagflat` +- [ ] `diagonal` +- [ ] `diff` +- [ ] `digitize` +- [ ] `dsplit` +- [ ] `dstack` +- [ ] `ediff1d` +- [ ] `einsum_path` +- [ ] `empty` +- [ ] `empty_like` +- [ ] `expand_dims` +- [ ] `extract` +- [ ] `eye` +- [ ] `fill_diagonal` +- [ ] `flatnonzero` +- [ ] `flip` +- [ ] `fliplr` +- [ ] `flipud` +- [ ] `gcd` +- [ ] `gradient` +- [ ] `hamming` +- [ ] `hanning` +- [ ] `heaviside` +- [ ] `histogram` +- [ ] `histogram2d` +- [ ] `histogram_bin_edges` +- [ ] `histogramdd` +- [ ] `hsplit` +- [ ] `hstack` +- [ ] `identity` +- [ ] `indices` +- [ ] `inner` +- [ ] `insert` +- [ ] `interp` +- [ ] `intersect1d` +- [ ] `iscomplexobj` +- [ ] `isin` +- [ ] `iterable` +- [ ] `ix_` +- [ ] `kaiser` +- [ ] `kron` +- [ ] `lcm` +- [ ] `ldexp` +- [ ] `lexsort` +- [ ] `mask_indices` +- [ ] `median` +- [ ] `meshgrid` +- [ ] `mgrid` +- [ ] `modf` +- [ ] `moveaxis` +- [ ] `nan_to_num` +- [ ] `nanargmax` +- [ ] `nanargmin` +- [ ] `nancumprod` +- [ ] `nancumsum` +- [ ] `nanmax` +- [ ] `nanmean` +- [ ] `nanmedian` +- [ ] `nanmin` +- [ ] `nanpercentile` +- [ ] `nanprod` +- [ ] `nanquantile` +- [ ] `nanstd` +- [ ] `nansum` +- [ ] `nanvar` +- [ ] `nonzero` +- [ ] `ogrid` +- [ ] `packbits` +- [ ] `partition` +- [ ] `percentile` +- [ ] `permute_dims` +- [ ] `piecewise` +- [ ] `place` +- [ ] `poly` +- [ ] `polyadd` +- [ ] `polyder` +- [ ] `polydiv` +- [ ] `polyfit` +- [ ] `polyint` +- [ ] `polymul` +- [ ] `polysub` +- [ ] `polyval` +- [ ] `pow` +- [ ] `promote_types` +- [ ] `put` +- [ ] `put_along_axis` +- [ ] `quantile` +- [ ] `ravel_multi_index` +- [ ] `reshape` +- [ ] `resize` +- [ ] `result_type` +- [ ] `rollaxis` +- [ ] `roots` +- [ ] `rot90` +- [ ] `select` +- [ ] `setdiff1d` +- [ ] `setxor1d` +- [ ] `spacing` +- [ ] `squeeze` +- [ ] `swapaxes` +- [ ] `take_along_axis` +- [ ] `transpose` +- [ ] `trapezoid` +- [ ] `tri` +- [ ] `tril_indices` +- [ ] `tril_indices_from` +- [ ] `trim_zeros` +- [ ] `triu_indices` +- [ ] `triu_indices_from` +- [ ] `union1d` +- [ ] `unpackbits` +- [ ] `unravel_index` +- [ ] `unstack` +- [ ] `unwrap` +- [ ] `vander` +- [ ] `vsplit` +- [ ] `vstack` + +## fft +- [ ] `fft` +- [ ] `fft2` +- [ ] `fftfreq` +- [ ] `fftn` +- [ ] `fftshift` +- [ ] `hfft` +- [ ] `ifft` +- [ ] `ifft2` +- [ ] `ifftn` +- [ ] `ifftshift` +- [ ] `ihfft` +- [ ] `irfft` +- [ ] `irfft2` +- [ ] `irfftn` +- [ ] `rfft` +- [ ] `rfft2` +- [ ] `rfftfreq` +- [ ] `rfftn` + +## linalg +- [ ] `cholesky` +- [ ] `cond` +- [ ] `cross` +- [ ] `det` +- [ ] `diagonal` +- [ ] `eig` +- [ ] `eigh` +- [ ] `eigvals` +- [ ] `eigvalsh` +- [ ] `inv` +- [ ] `lstsq` +- [ ] `matmul` +- [ ] `matrix_norm` +- [ ] `matrix_power` +- [ ] `matrix_rank` +- [ ] `matrix_transpose` +- [ ] `norm` +- [ ] `outer` +- [ ] `pinv` +- [ ] `qr` +- [ ] `slogdet` +- [ ] `solve` +- [ ] `svd` +- [ ] `svdvals` +- [ ] `tensordot` +- [ ] `tensorinv` +- [ ] `tensorsolve` +- [ ] `trace` +- [ ] `vdot` +- [ ] `vecdot` +- [ ] `vecmat` +- [ ] `vector_norm` commit 5d8672d1d965e6752dafab2e8f24d5bd684efc4d Date: 2025-09-11T17:26:32-07:00 feat: add array comparison helpers (#206) diff --git a/.agents/projects/api_parity.md b/.agents/projects/api_parity.md index b60b4d9..1ceaede 100644 --- a/.agents/projects/api_parity.md +++ b/.agents/projects/api_parity.md @@ -4,15 +4,15 @@ This document tracks JAX NumPy functions not yet wrapped by Haliax. APIs that don't translate well to named tensors are intentionally omitted here. This includes dtype constructors, raw array converters (e.g. `from_dlpack`), indexing helpers like `c_`/`r_`, and functions whose JAX counterparts already work with `NamedArray` out of the box. Basic array construction is handled by `haliax.named`, so functions such as `array` or `asarray` are not listed. ## numpy -- [ ] `allclose` +- [x] `allclose` - [ ] `amin` - [ ] `append` - [ ] `apply_along_axis` - [ ] `apply_over_axes` - [ ] `argpartition` - [ ] `argwhere` -- [ ] `array_equal` -- [ ] `array_equiv` +- [x] `array_equal` +- [x] `array_equiv` - [ ] `array_split` - [ ] `astype` - [ ] `atan2` diff --git a/docs/api.md b/docs/api.md index 67e4fe9..44a030a 100644 --- a/docs/api.md +++ b/docs/api.md @@ -259,6 +259,9 @@ These are all more or less directly from JAX's NumPy API. ::: haliax.bincount ::: haliax.clip ::: haliax.isclose +::: haliax.allclose +::: haliax.array_equal +::: haliax.array_equiv ::: haliax.pad ::: haliax.searchsorted ::: haliax.top_k diff --git a/src/haliax/__init__.py b/src/haliax/__init__.py index 5e06d7c..3296957 100644 --- a/src/haliax/__init__.py +++ b/src/haliax/__init__.py @@ -69,6 +69,9 @@ from .hof import fold, map, scan, vmap from .jax_utils import tree_checkpoint_name from .ops import ( clip, + allclose, + array_equal, + array_equiv, isclose, pad_left, pad, @@ -1105,6 +1108,9 @@ __all__ = [ "shard", "enable_shape_checks", "are_shape_checks_enabled", + "allclose", + "array_equal", + "array_equiv", "isclose", "pad_left", "pad", diff --git a/src/haliax/ops.py b/src/haliax/ops.py index ca0ce64..8efb98a 100644 --- a/src/haliax/ops.py +++ b/src/haliax/ops.py @@ -138,6 +138,29 @@ def isclose(a: NamedArray, b: NamedArray, rtol=1e-05, atol=1e-08, equal_nan=Fals return NamedArray(jnp.isclose(a.array, b.array, rtol=rtol, atol=atol, equal_nan=equal_nan), a.axes) +def allclose(a: NamedArray, b: NamedArray, rtol=1e-05, atol=1e-08, equal_nan=False) -> bool: + """Returns True if two arrays are element-wise equal within a tolerance.""" + a, b = broadcast_arrays(a, b) + return bool(jnp.allclose(a.array, b.array, rtol=rtol, atol=atol, equal_nan=equal_nan)) + + +def array_equal(a: NamedArray, b: NamedArray) -> bool: + """Returns True if two arrays have the same shape and elements.""" + if set(a.axes) != set(b.axes): + return False + b = b.rearrange(a.axes) + return bool(jnp.array_equal(a.array, b.array)) + + +def array_equiv(a: NamedArray, b: NamedArray) -> bool: + """Returns True if two arrays are shape-consistent and equal.""" + try: + a, b = broadcast_arrays(a, b) + except ValueError: + return False + return bool(jnp.array_equal(a.array, b.array)) + + def pad_left(array: NamedArray, axis: Axis, new_axis: Axis, value=0) -> NamedArray: """Pad an array along named axes.""" amount_to_pad_to = new_axis.size - axis.size diff --git a/tests/test_ops.py b/tests/test_ops.py index d7eacd8..4547766 100644 --- a/tests/test_ops.py +++ b/tests/test_ops.py @@ -425,6 +425,32 @@ def test_bincount(): assert jnp.allclose(out_w.array, expected_w) +def test_allclose_array_equal_equiv(): + A = Axis("A", 2) + B = Axis("B", 3) + x = hax.random.uniform(PRNGKey(0), (A, B)) + y = x + 1e-6 + + assert hax.allclose(x, y) + assert not hax.allclose(x, x + 1.0) + + x1 = hax.ones((A, B)) + y_reordered = x1.rearrange((B, A)) + assert hax.array_equal(x1, y_reordered) + + scalar = hax.ones(()) + assert hax.array_equiv(x1, scalar) + assert not hax.array_equal(x1, scalar) + + y_vec = hax.ones((B,)) + assert hax.array_equiv(x1, y_vec) + assert not hax.array_equal(x1, y_vec) + + C = Axis("C", 4) + z = hax.ones((C,)) + assert not hax.array_equiv(x1, z) + + def test_roll_scalar_named_shift(): H = Axis("H", 4) W = Axis("W", 3) commit f1b58ed35f32fcaa545c0244a8ea0af41bef5aa8 Date: 2025-09-12T00:51:17-07:00 Add NaN-aware reduction wrappers and amin alias (#207) * Add tests for NaN reductions and amin * fix: type annotate nan reduction tests diff --git a/.agents/projects/api_parity.md b/.agents/projects/api_parity.md index 1ceaede..13ee754 100644 --- a/.agents/projects/api_parity.md +++ b/.agents/projects/api_parity.md @@ -5,7 +5,7 @@ APIs that don't translate well to named tensors are intentionally omitted here. ## numpy - [x] `allclose` -- [ ] `amin` +- [x] `amin` - [ ] `append` - [ ] `apply_along_axis` - [ ] `apply_over_axes` @@ -93,20 +93,20 @@ APIs that don't translate well to named tensors are intentionally omitted here. - [ ] `modf` - [ ] `moveaxis` - [ ] `nan_to_num` -- [ ] `nanargmax` -- [ ] `nanargmin` -- [ ] `nancumprod` -- [ ] `nancumsum` -- [ ] `nanmax` -- [ ] `nanmean` +- [x] `nanargmax` +- [x] `nanargmin` +- [x] `nancumprod` +- [x] `nancumsum` +- [x] `nanmax` +- [x] `nanmean` - [ ] `nanmedian` -- [ ] `nanmin` +- [x] `nanmin` - [ ] `nanpercentile` -- [ ] `nanprod` +- [x] `nanprod` - [ ] `nanquantile` -- [ ] `nanstd` -- [ ] `nansum` -- [ ] `nanvar` +- [x] `nanstd` +- [x] `nansum` +- [x] `nanvar` - [ ] `nonzero` - [ ] `ogrid` - [ ] `packbits` diff --git a/docs/api.md b/docs/api.md index 44a030a..c1b00df 100644 --- a/docs/api.md +++ b/docs/api.md @@ -128,12 +128,22 @@ You can convert it to a [jax.numpy.ndarray][] with [haliax.NamedArray.scalar][], ::: haliax.all ::: haliax.amax +::: haliax.amin ::: haliax.any ::: haliax.argmax ::: haliax.argmin ::: haliax.max ::: haliax.mean ::: haliax.min +::: haliax.nanargmax +::: haliax.nanargmin +::: haliax.nanmax +::: haliax.nanmean +::: haliax.nanmin +::: haliax.nanprod +::: haliax.nanstd +::: haliax.nansum +::: haliax.nanvar ::: haliax.prod ::: haliax.ptp ::: haliax.std @@ -146,6 +156,8 @@ don't reduce it. ::: haliax.cumsum ::: haliax.cumprod +::: haliax.nancumprod +::: haliax.nancumsum ::: haliax.sort ::: haliax.argsort diff --git a/src/haliax/__init__.py b/src/haliax/__init__.py index 3296957..48b4325 100644 --- a/src/haliax/__init__.py +++ b/src/haliax/__init__.py @@ -560,6 +560,13 @@ def amax(array: NamedArray, axis: Optional[AxisSelection] = None, *, where: Opti return wrap_reduction_call(jnp.amax, array, axis, where, single_axis_only=False, supports_where=True) +def amin(array: NamedArray, axis: Optional[AxisSelection] = None, *, where: Optional[NamedArray] = None) -> NamedArray: + """ + Aliax for min. See min for details. + """ + return wrap_reduction_call(jnp.amin, array, axis, where, single_axis_only=False, supports_where=True) + + def any(array: NamedArray, axis: Optional[AxisSelection] = None, *, where: Optional[NamedArray] = None) -> NamedArray: """True if any elements along a given axis or axes are True. If axis is None, any elements are True.""" return wrap_reduction_call(jnp.any, array, axis, where, single_axis_only=False, supports_where=True) @@ -656,6 +663,84 @@ def var( ) +def nanargmax(array: NamedArray, axis: Optional[AxisSelector] = None) -> NamedArray: + return wrap_reduction_call(jnp.nanargmax, array, axis, None, single_axis_only=True, supports_where=False) + + +def nanargmin(array: NamedArray, axis: Optional[AxisSelector] = None) -> NamedArray: + return wrap_reduction_call(jnp.nanargmin, array, axis, None, single_axis_only=True, supports_where=False) + + +def nanmax( + array: NamedArray, + axis: Optional[AxisSelection] = None, + *, + where: Optional[NamedArray] = None, +) -> NamedArray: + return wrap_reduction_call(jnp.nanmax, array, axis, where, single_axis_only=False, supports_where=True) + + +def nanmean( + array: NamedArray, + axis: Optional[AxisSelection] = None, + *, + where: Optional[NamedArray] = None, + dtype: Optional[DTypeLike] = None, +) -> NamedArray: + return wrap_reduction_call(jnp.nanmean, array, axis, where, single_axis_only=False, supports_where=True, dtype=dtype) + + +def nanmin( + array: NamedArray, + axis: Optional[AxisSelection] = None, + *, + where: Optional[NamedArray] = None, +) -> NamedArray: + return wrap_reduction_call(jnp.nanmin, array, axis, where, single_axis_only=False, supports_where=True) + + +def nanprod( + array: NamedArray, + axis: Optional[AxisSelection] = None, + *, + where: Optional[NamedArray] = None, + dtype: Optional[DTypeLike] = None, +) -> NamedArray: + return wrap_reduction_call(jnp.nanprod, array, axis, where, single_axis_only=False, supports_where=True, dtype=dtype) + + +def nanstd( + array: NamedArray, + axis: Optional[AxisSelection] = None, + *, + where: Optional[NamedArray] = None, + ddof: int = 0, + dtype: Optional[DTypeLike] = None, +) -> NamedArray: + return wrap_reduction_call(jnp.nanstd, array, axis, where, single_axis_only=False, supports_where=True, dtype=dtype, ddof=ddof) + + +def nansum( + array: NamedArray, + axis: Optional[AxisSelection] = None, + *, + where: Optional[NamedArray] = None, + dtype: Optional[DTypeLike] = None, +) -> NamedArray: + return wrap_reduction_call(jnp.nansum, array, axis, where, single_axis_only=False, supports_where=True, dtype=dtype) + + +def nanvar( + array: NamedArray, + axis: Optional[AxisSelection] = None, + *, + where: Optional[NamedArray] = None, + ddof: int = 0, + dtype: Optional[DTypeLike] = None, +) -> NamedArray: + return wrap_reduction_call(jnp.nanvar, array, axis, where, single_axis_only=False, supports_where=True, dtype=dtype, ddof=ddof) + + # "Normalization" functions that use an axis but don't change the shape @@ -673,6 +758,20 @@ def cumprod(a: NamedArray, axis: AxisSelector, dtype: Optional[DTypeLike] = None return wrap_axiswise_call(jnp.cumprod, a, axis, dtype=dtype, single_axis_only=True) +def nancumsum(a: NamedArray, axis: AxisSelector, *, dtype: Optional[DTypeLike] = None) -> NamedArray: + """ + Named version of [jax.numpy.nancumsum](https://jax.readthedocs.io/en/latest/_autosummary/jax.numpy.nancumsum.html) + """ + return wrap_axiswise_call(jnp.nancumsum, a, axis, dtype=dtype, single_axis_only=True) + + +def nancumprod(a: NamedArray, axis: AxisSelector, dtype: Optional[DTypeLike] = None) -> NamedArray: + """ + Named version of [jax.numpy.nancumprod](https://jax.readthedocs.io/en/latest/_autosummary/jax.numpy.nancumprod.html) + """ + return wrap_axiswise_call(jnp.nancumprod, a, axis, dtype=dtype, single_axis_only=True) + + def sort(a: NamedArray, axis: AxisSelector) -> NamedArray: """ Named version of [jax.numpy.sort](https://jax.readthedocs.io/en/latest/_autosummary/jax.numpy.sort.html) @@ -1034,12 +1133,22 @@ __all__ = [ "trunc", "all", "amax", + "amin", "any", "argmax", "argmin", "max", "mean", "min", + "nanargmax", + "nanargmin", + "nanmax", + "nanmean", + "nanmin", + "nanprod", + "nanstd", + "nansum", + "nanvar", "prod", "product", "ptp", @@ -1048,6 +1157,8 @@ __all__ = [ "var", "cumsum", "cumprod", + "nancumprod", + "nancumsum", "sort", "scan", "fold", diff --git a/tests/test_nan_reductions.py b/tests/test_nan_reductions.py new file mode 100644 index 0000000..46b2269 --- /dev/null +++ b/tests/test_nan_reductions.py @@ -0,0 +1,59 @@ +from typing import Any, Callable + +import jax.numpy as jnp +import haliax as hax + + +def _sample_array(): + Height, Width = hax.make_axes(Height=2, Width=3) + data = jnp.array([[1.0, jnp.nan, 3.0], [jnp.nan, 5.0, 6.0]]) + arr = hax.named(data, (Height, Width)) + return Height, Width, data, arr + + +def test_amin_alias(): + Height, Width = hax.make_axes(Height=2, Width=3) + data = jnp.arange(6.0).reshape(2, 3) + arr = hax.named(data, (Height, Width)) + assert jnp.array_equal(hax.amin(arr).array, jnp.amin(data)) + assert jnp.array_equal(hax.amin(arr, axis=Height).array, jnp.amin(data, axis=0)) + assert hax.amin(arr, axis=Height).axes == (Width,) + + +def test_nan_reductions(): + Height, Width, data, arr = _sample_array() + + funcs: list[tuple[Callable[..., Any], Callable[..., Any]]] = [ + (hax.nanmin, jnp.nanmin), + (hax.nanmax, jnp.nanmax), + (hax.nanmean, jnp.nanmean), + (hax.nansum, jnp.nansum), + (hax.nanprod, jnp.nanprod), + (hax.nanstd, jnp.nanstd), + (hax.nanvar, jnp.nanvar), + ] + + for hfunc, jfunc in funcs: + assert jnp.allclose(hfunc(arr).array, jfunc(data), equal_nan=True) + assert jnp.allclose(hfunc(arr, axis=Height).array, jfunc(data, axis=0), equal_nan=True) + assert hfunc(arr, axis=Height).axes == (Width,) + + arg_funcs: list[tuple[Callable[..., Any], Callable[..., Any]]] = [ + (hax.nanargmax, jnp.nanargmax), + (hax.nanargmin, jnp.nanargmin), + ] + + for hfunc, jfunc in arg_funcs: + out = hfunc(arr, axis=Height) + assert jnp.array_equal(out.array, jfunc(data, axis=0)) + assert out.axes == (Width,) + + axiswise_funcs: list[tuple[Callable[..., Any], Callable[..., Any]]] = [ + (hax.nancumsum, jnp.nancumsum), + (hax.nancumprod, jnp.nancumprod), + ] + + for hfunc, jfunc in axiswise_funcs: + out = hfunc(arr, axis=Height) + assert jnp.allclose(out.array, jfunc(data, axis=0), equal_nan=True) + assert out.axes == (Height, Width) commit b600d85ec4eccffdf3aa7f34585c708fbf948399 Date: 2025-09-12T00:55:24-07:00 Test new bitwise wrappers (#208) diff --git a/.agents/projects/api_parity.md b/.agents/projects/api_parity.md index 13ee754..19e3cf1 100644 --- a/.agents/projects/api_parity.md +++ b/.agents/projects/api_parity.md @@ -18,10 +18,10 @@ APIs that don't translate well to named tensors are intentionally omitted here. - [ ] `atan2` - [ ] `average` - [ ] `bartlett` -- [ ] `bitwise_count` -- [ ] `bitwise_invert` -- [ ] `bitwise_left_shift` -- [ ] `bitwise_right_shift` +- [x] `bitwise_count` +- [x] `bitwise_invert` +- [x] `bitwise_left_shift` +- [x] `bitwise_right_shift` - [ ] `blackman` - [ ] `block` - [ ] `broadcast_shapes` @@ -109,7 +109,7 @@ APIs that don't translate well to named tensors are intentionally omitted here. - [x] `nanvar` - [ ] `nonzero` - [ ] `ogrid` -- [ ] `packbits` +- [x] `packbits` - [ ] `partition` - [ ] `percentile` - [ ] `permute_dims` @@ -152,7 +152,7 @@ APIs that don't translate well to named tensors are intentionally omitted here. - [ ] `triu_indices` - [ ] `triu_indices_from` - [ ] `union1d` -- [ ] `unpackbits` +- [x] `unpackbits` - [ ] `unravel_index` - [ ] `unstack` - [ ] `unwrap` diff --git a/docs/api.md b/docs/api.md index c1b00df..a0dd228 100644 --- a/docs/api.md +++ b/docs/api.md @@ -176,6 +176,8 @@ These are all more or less directly from JAX's NumPy API. ::: haliax.arctan ::: haliax.arctanh ::: haliax.around +::: haliax.bitwise_count +::: haliax.bitwise_invert ::: haliax.bitwise_not ::: haliax.cbrt ::: haliax.ceil @@ -233,7 +235,9 @@ These are all more or less directly from JAX's NumPy API. ::: haliax.add ::: haliax.arctan2 ::: haliax.bitwise_and +::: haliax.bitwise_left_shift ::: haliax.bitwise_or +::: haliax.bitwise_right_shift ::: haliax.bitwise_xor ::: haliax.divide ::: haliax.divmod @@ -270,6 +274,8 @@ These are all more or less directly from JAX's NumPy API. ::: haliax.bincount ::: haliax.clip +::: haliax.packbits +::: haliax.unpackbits ::: haliax.isclose ::: haliax.allclose ::: haliax.array_equal diff --git a/src/haliax/__init__.py b/src/haliax/__init__.py index 48b4325..b6ca784 100644 --- a/src/haliax/__init__.py +++ b/src/haliax/__init__.py @@ -83,6 +83,8 @@ from .ops import ( unique_counts, unique_inverse, unique_all, + packbits, + unpackbits, searchsorted, bincount, where, @@ -337,6 +339,14 @@ def around(a: A) -> A: return wrap_elemwise_unary(jnp.around, a) +def bitwise_count(a: A) -> A: + return wrap_elemwise_unary(jnp.bitwise_count, a) + + +def bitwise_invert(a: A) -> A: + return wrap_elemwise_unary(jnp.bitwise_invert, a) + + def bitwise_not(a: A) -> A: return wrap_elemwise_unary(jnp.bitwise_not, a) @@ -816,6 +826,14 @@ def bitwise_and(x1: NamedOrNumeric, x2: NamedOrNumeric, /) -> NamedOrNumeric: return jnp.bitwise_and(x1, x2) # type: ignore +@wrap_elemwise_binary +def bitwise_left_shift(x1: NamedOrNumeric, x2: NamedOrNumeric, /) -> NamedOrNumeric: + """ + Named version of [jax.numpy.bitwise_left_shift](https://jax.readthedocs.io/en/latest/_autosummary/jax.numpy.bitwise_left_shift.html) + """ + return jnp.bitwise_left_shift(x1, x2) # type: ignore + + @wrap_elemwise_binary def bitwise_or(x1: NamedOrNumeric, x2: NamedOrNumeric, /) -> NamedOrNumeric: """ @@ -824,6 +842,14 @@ def bitwise_or(x1: NamedOrNumeric, x2: NamedOrNumeric, /) -> NamedOrNumeric: return jnp.bitwise_or(x1, x2) # type: ignore +@wrap_elemwise_binary +def bitwise_right_shift(x1: NamedOrNumeric, x2: NamedOrNumeric, /) -> NamedOrNumeric: + """ + Named version of [jax.numpy.bitwise_right_shift](https://jax.readthedocs.io/en/latest/_autosummary/jax.numpy.bitwise_right_shift.html) + """ + return jnp.bitwise_right_shift(x1, x2) # type: ignore + + @wrap_elemwise_binary def bitwise_xor(x1: NamedOrNumeric, x2: NamedOrNumeric, /) -> NamedOrNumeric: """ @@ -1080,6 +1106,8 @@ __all__ = [ "arctan", "arctanh", "around", + "bitwise_count", + "bitwise_invert", "bitwise_not", "cbrt", "ceil", @@ -1171,6 +1199,8 @@ __all__ = [ "unique_counts", "unique_inverse", "unique_all", + "packbits", + "unpackbits", "searchsorted", "bincount", "clip", @@ -1179,7 +1209,9 @@ __all__ = [ "add", "arctan2", "bitwise_and", + "bitwise_left_shift", "bitwise_or", + "bitwise_right_shift", "bitwise_xor", "divide", "divmod", diff --git a/src/haliax/ops.py b/src/haliax/ops.py index 8efb98a..6859218 100644 --- a/src/haliax/ops.py +++ b/src/haliax/ops.py @@ -508,6 +508,42 @@ def bincount( return NamedArray(result, (Counts,)) +def packbits(a: NamedArray, axis: AxisSelector, *, bitorder: str = "big") -> NamedArray: + """Named version of `jax.numpy.packbits`.""" + + axis_index = a.axis_indices(axis) + if not isinstance(axis_index, int): + raise ValueError("packbits only supports a single existing axis") + + result = jnp.packbits(a.array, axis=axis_index, bitorder=bitorder) + old_axis = a.axes[axis_index] + new_size = (old_axis.size + 7) // 8 + new_axis = old_axis.resize(new_size) + new_axes = a.axes[:axis_index] + (new_axis,) + a.axes[axis_index + 1 :] + return NamedArray(result, new_axes) + + +def unpackbits( + a: NamedArray, + axis: AxisSelector, + *, + count: int | None = None, + bitorder: str = "big", +) -> NamedArray: + """Named version of `jax.numpy.unpackbits`.""" + + axis_index = a.axis_indices(axis) + if not isinstance(axis_index, int): + raise ValueError("unpackbits only supports a single existing axis") + + result = jnp.unpackbits(a.array, axis=axis_index, count=count, bitorder=bitorder) + old_axis = a.axes[axis_index] + new_size = count if count is not None else old_axis.size * 8 + new_axis = old_axis.resize(new_size) + new_axes = a.axes[:axis_index] + (new_axis,) + a.axes[axis_index + 1 :] + return NamedArray(result, new_axes) + + __all__ = [ "trace", "where", @@ -517,6 +553,8 @@ __all__ = [ "pad_left", "pad", "clip", + "packbits", + "unpackbits", "unique", "unique_values", "unique_counts", diff --git a/tests/test_bitwise_ops.py b/tests/test_bitwise_ops.py new file mode 100644 index 0000000..e209c12 --- /dev/null +++ b/tests/test_bitwise_ops.py @@ -0,0 +1,45 @@ +import jax.numpy as jnp +import haliax as hax +from haliax import Axis + + +def test_bitwise_count_invert(): + A = Axis("A", 4) + x = hax.named(jnp.array([0, 1, 2, 3], dtype=jnp.uint8), (A,)) + + inv = hax.bitwise_invert(x) + assert jnp.all(inv.array == jnp.bitwise_invert(x.array)) + + cnt = hax.bitwise_count(x) + assert jnp.all(cnt.array == jnp.bitwise_count(x.array)) + + +def test_bitwise_shift(): + A = Axis("A", 4) + x = hax.named(jnp.array([1, 2, 3, 4], dtype=jnp.int32), (A,)) + shift = hax.named(jnp.array([1, 1, 1, 1], dtype=jnp.int32), (A,)) + + left = hax.bitwise_left_shift(x, shift) + assert jnp.all(left.array == jnp.bitwise_left_shift(x.array, shift.array)) + + right = hax.bitwise_right_shift(left, shift) + assert jnp.all(right.array == jnp.bitwise_right_shift(left.array, shift.array)) + + right_scalar = hax.bitwise_right_shift(x, 1) + assert jnp.all(right_scalar.array == jnp.bitwise_right_shift(x.array, 1)) + + +def test_packbits_unpackbits(): + B = Axis("B", 10) + data = hax.named(jnp.array([0, 1, 1, 0, 1, 0, 0, 1, 1, 0], dtype=jnp.uint8), (B,)) + + packed = hax.packbits(data, B) + expected_packed = jnp.packbits(data.array, axis=0) + assert jnp.all(packed.array == expected_packed) + assert packed.axes[0].name == B.name + assert packed.axes[0].size == 2 + + unpacked = hax.unpackbits(packed, "B", count=B.size) + expected_unpacked = jnp.unpackbits(packed.array, axis=0, count=B.size) + assert jnp.all(unpacked.array == expected_unpacked) + assert unpacked.axes[0].size == B.size commit fece61e6a405b076b3e12a8029dbd580073a9d13 Date: 2025-09-12T14:13:26-07:00 Remove old headers (#205) diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml index beb7e93..ea7ede8 100644 --- a/.pre-commit-config.yaml +++ b/.pre-commit-config.yaml @@ -1,39 +1,43 @@ -# See https://pre-commit.com for more information -# See https://pre-commit.com/hooks.html for more hooks -exclude: ".git" -default_stages: - - pre-commit -fail_fast: true +# See https://pre-commit.com +exclude: ".git|.venv|tests/snapshots/.*/.*" repos: -- repo: https://github.com/pre-commit/pre-commit-hooks - rev: v4.0.1 + - repo: https://github.com/astral-sh/ruff-pre-commit + rev: v0.11.10 hooks: - - id: trailing-whitespace - - id: end-of-file-fixer - - id: check-yaml - - id: check-toml - - id: check-merge-conflict - - id: check-added-large-files + - id: ruff + args: [ --fix, --exit-non-zero-on-fix ] -- repo: https://github.com/astral-sh/ruff-pre-commit - rev: v0.11.10 - hooks: - - id: ruff - args: [ --fix, --exit-non-zero-on-fix ] + - repo: https://github.com/Lucas-C/pre-commit-hooks + rev: v1.5.5 + hooks: + - id: insert-license + files: \.py$ + args: + - --license-filepath + - etc/license_header.txt + - --use-current-year + + - repo: https://github.com/psf/black + rev: 25.1.0 + hooks: + - id: black -#- repo: local -# hooks: -# - id: ty-check -# name: ty-check -# language: python -# entry: ty check -# pass_filenames: false -# args: [--python=.venv/] -# additional_dependencies: [ty] + - repo: https://github.com/pre-commit/pre-commit-hooks + rev: v5.0.0 + hooks: + - id: check-added-large-files + - id: check-ast + - id: check-case-conflict + - id: check-merge-conflict + - id: check-toml + - id: check-yaml + args: [ --unsafe ] + - id: end-of-file-fixer + - id: trailing-whitespace -- repo: https://github.com/pre-commit/mirrors-mypy - rev: 'v1.16.1' + - repo: https://github.com/pre-commit/mirrors-mypy + rev: v1.16.1 hooks: - - id: mypy + - id: mypy args: [--ignore-missing-imports, --check-untyped-defs] diff --git a/AUTHORS.md b/AUTHORS.md new file mode 100644 index 0000000..8846e76 --- /dev/null +++ b/AUTHORS.md @@ -0,0 +1,5 @@ +# The Levanter Authors + +The Levanter Authors currently include: + +- The Board of Trustees of the Leland Stanford Junior University diff --git a/CONTRIBUTORS.md b/CONTRIBUTORS.md new file mode 100644 index 0000000..87b0423 --- /dev/null +++ b/CONTRIBUTORS.md @@ -0,0 +1,15 @@ +# Contributors + +The following individuals have contributed to Haliax: + +- David Hall <dlwh@stanford.edu> +- David Hall <dlwh@cs.stanford.edu> +- Jason Wang <blahblahj.wsy@gmail.com> +- Ivan Zhou <ivan.zhouyq@gmail.com> +- rohan-mehta-1024 <69774557+rohan-mehta-1024@users.noreply.github.com> +- Gary Miguel <garymm@garymm.org> +- Jennifer Zhou <jennifer@jezh.me> +- Joseph Camacho <camacho.joseph@gmail.com> +- Omead Pooladzandi <opooladz@ucla.edu> +- Patrick Kidger <33688385+patrick-kidger@users.noreply.github.com> +- Russell Power <russell.power@gmail.com> diff --git a/etc/license_header.txt b/etc/license_header.txt new file mode 100644 index 0000000..18bbf23 --- /dev/null +++ b/etc/license_header.txt @@ -0,0 +1,3 @@ +Copyright 2025 The Levanter Authors + +SPDX-License-Identifier: Apache-2.0 diff --git a/src/haliax/__about__.py b/src/haliax/__about__.py index e992399..6dd02e9 100644 --- a/src/haliax/__about__.py +++ b/src/haliax/__about__.py @@ -1 +1,6 @@ +# Copyright 2025 The Levanter Authors +# +# SPDX-License-Identifier: Apache-2.0 + + __version__ = "1.4" diff --git a/src/haliax/__init__.py b/src/haliax/__init__.py index b6ca784..8052b99 100644 --- a/src/haliax/__init__.py +++ b/src/haliax/__init__.py @@ -1,10 +1,14 @@ +# Copyright 2025 The Levanter Authors +# +# SPDX-License-Identifier: Apache-2.0 + + import typing as t from typing import Optional, Sequence import jax import jax.numpy as jnp - try: from jax.typing import DTypeLike except ImportError: @@ -44,7 +48,9 @@ from .axis import ( ) from .core import ( NamedArray, - NamedArrayAxes, NamedArrayAxesSpec, NamedOrNumeric, + NamedArrayAxes, + NamedArrayAxesSpec, + NamedOrNumeric, are_shape_checks_enabled, broadcast_arrays, broadcast_axis, @@ -102,7 +108,6 @@ from .wrap import ( wrap_reduction_call, ) - T = t.TypeVar("T") A = t.TypeVar("A", Scalar, NamedArray, jnp.ndarray) @@ -801,6 +806,7 @@ def argsort(a: NamedArray, axis: AxisSelector) -> NamedArray: # elemwise binary ops + # Note that all the heavy lifting is done by the `wrap_elemwise_binary` decorator @wrap_elemwise_binary def add(x1: NamedOrNumeric, x2: NamedOrNumeric, /) -> NamedOrNumeric: diff --git a/src/haliax/_src/__init__.py b/src/haliax/_src/__init__.py index e69de29..09204bb 100644 --- a/src/haliax/_src/__init__.py +++ b/src/haliax/_src/__init__.py @@ -0,0 +1,3 @@ +# Copyright 2025 The Levanter Authors +# +# SPDX-License-Identifier: Apache-2.0 diff --git a/src/haliax/_src/compile_utils.py b/src/haliax/_src/compile_utils.py index 63d98da..a2f22d0 100644 --- a/src/haliax/_src/compile_utils.py +++ b/src/haliax/_src/compile_utils.py @@ -1,3 +1,8 @@ +# Copyright 2025 The Levanter Authors +# +# SPDX-License-Identifier: Apache-2.0 + + # This whole file is copied from Equinox. # (c) 2023, Google LLC. and/or Patrick Kidger. Apache 2.0 licensed. # Patrick doesn't like that I depend on Equinox internals, so I copied this stuff diff --git a/src/haliax/_src/dot.py b/src/haliax/_src/dot.py index 9475831..fab72c8 100644 --- a/src/haliax/_src/dot.py +++ b/src/haliax/_src/dot.py @@ -1,3 +1,8 @@ +# Copyright 2025 The Levanter Authors +# +# SPDX-License-Identifier: Apache-2.0 + + import functools as ft import typing import warnings @@ -30,8 +35,7 @@ def dot( preferred_element_type: Optional[DTypeLike] = None, out_axes: Optional[PartialAxisSpec] = ..., dot_general=jax.lax.dot_general, -) -> NamedArray: - ... +) -> NamedArray: ... @typing.overload @@ -42,8 +46,7 @@ def dot( preferred_element_type: Optional[DTypeLike] = None, out_axes: Optional[PartialAxisSpec] = ..., dot_general=jax.lax.dot_general, -) -> NamedArray: - ... +) -> NamedArray: ... def dot( diff --git a/src/haliax/_src/einsum.py b/src/haliax/_src/einsum.py index 674e079..27fe15a 100644 --- a/src/haliax/_src/einsum.py +++ b/src/haliax/_src/einsum.py @@ -1,3 +1,8 @@ +# Copyright 2025 The Levanter Authors +# +# SPDX-License-Identifier: Apache-2.0 + + import functools from types import EllipsisType from typing import Optional, Tuple diff --git a/src/haliax/_src/fp8.py b/src/haliax/_src/fp8.py index 72f46d0..9fd3452 100644 --- a/src/haliax/_src/fp8.py +++ b/src/haliax/_src/fp8.py @@ -1,9 +1,13 @@ +# Copyright 2025 The Levanter Authors +# +# SPDX-License-Identifier: Apache-2.0 + + from functools import partial from jax import custom_jvp, custom_vjp, lax from jax import numpy as jnp - # All of this is copy paste from flax/linen/fp8_ops.py # (Until we get to the module) diff --git a/src/haliax/_src/parsing.py b/src/haliax/_src/parsing.py index d2233c9..a369e60 100644 --- a/src/haliax/_src/parsing.py +++ b/src/haliax/_src/parsing.py @@ -1,3 +1,8 @@ +# Copyright 2025 The Levanter Authors +# +# SPDX-License-Identifier: Apache-2.0 + + import dataclasses from types import EllipsisType from typing import Mapping, NoReturn, Optional, Sequence diff --git a/src/haliax/_src/rearrange.py b/src/haliax/_src/rearrange.py index 7b68220..351ac96 100644 --- a/src/haliax/_src/rearrange.py +++ b/src/haliax/_src/rearrange.py @@ -1,3 +1,8 @@ +# Copyright 2025 The Levanter Authors +# +# SPDX-License-Identifier: Apache-2.0 + + # Support for einops-style rearrangement strings, but supporting named axes and unordered matching import dataclasses import typing diff --git a/src/haliax/_src/scan.py b/src/haliax/_src/scan.py index 1373988..6cd8005 100644 --- a/src/haliax/_src/scan.py +++ b/src/haliax/_src/scan.py @@ -1,3 +1,8 @@ +# Copyright 2025 The Levanter Authors +# +# SPDX-License-Identifier: Apache-2.0 + + import dataclasses import functools as ft import inspect @@ -16,7 +21,6 @@ from haliax.core import NamedArray from haliax.jax_utils import is_jax_array_like, multilevel_scan, tree_checkpoint_name from haliax.util import is_jax_or_hax_array_like, is_named_array - BoolAxisSpec = Union[bool, Callable[[Any], bool]] Carry = TypeVar("Carry") X = TypeVar("X", contravariant=True) @@ -31,8 +35,7 @@ def is_named_or_shaped_array_like(x): class ScanFn(Protocol[Carry, Args, Y]): """ """ - def __call__(self, carry: Carry, *args: Args.args, **kwargs: Args.kwargs) -> tuple[Carry, Y]: - ... + def __call__(self, carry: Carry, *args: Args.args, **kwargs: Args.kwargs) -> tuple[Carry, Y]: ... @dataclasses.dataclass(frozen=True) @@ -262,8 +265,7 @@ def scan( reverse: bool = False, unroll: int = 1, is_scanned: BoolAxisSpec = is_named_or_shaped_array_like, -) -> Callable[[Carry, PyTree[X]], tuple[Carry, PyTree[Y]]]: - ... +) -> Callable[[Carry, PyTree[X]], tuple[Carry, PyTree[Y]]]: ... @overload @@ -275,8 +277,7 @@ def scan( reverse: bool = False, unroll: int = 1, is_scanned: BoolAxisSpec = is_named_or_shaped_array_like, -) -> Callable: - ... +) -> Callable: ... def scan( @@ -444,8 +445,7 @@ def fold( reverse: bool = False, unroll: int = 1, is_scanned: BoolAxisSpec = is_named_or_shaped_array_like, -) -> Callable[[Carry, PyTree[X]], Carry]: - ... +) -> Callable[[Carry, PyTree[X]], Carry]: ... @overload @@ -457,8 +457,7 @@ def fold( reverse: bool = False, unroll: int = 1, is_scanned: BoolAxisSpec = is_named_or_shaped_array_like, -) -> Callable: - ... +) -> Callable: ... def fold( @@ -549,9 +548,7 @@ def _zero_if_array_else_none(x: Any) -> ResolvedUnnamedAxisSpec: return 0 if is_jax_array_like(x) else None -def _format_tree_path( - path: tuple[jtu.KeyEntry, ...], arg_pos_names: dict[int, str] | None = None -) -> str: +def _format_tree_path(path: tuple[jtu.KeyEntry, ...], arg_pos_names: dict[int, str] | None = None) -> str: parts: list[str] = [] i = 0 if len(path) >= 2 and isinstance(path[0], jtu.SequenceKey): diff --git a/src/haliax/_src/state_dict.py b/src/haliax/_src/state_dict.py index 986acde..7018d99 100644 --- a/src/haliax/_src/state_dict.py +++ b/src/haliax/_src/state_dict.py @@ -1,3 +1,8 @@ +# Copyright 2025 The Levanter Authors +# +# SPDX-License-Identifier: Apache-2.0 + + # Module to support torch-style "state dict" serialization via safetensors import dataclasses import typing @@ -19,7 +24,6 @@ from haliax.core import NamedArray, named from haliax.jax_utils import is_jax_array_like, is_scalarish from haliax.tree_util import scan_aware_tree_map - try: import safetensors except ImportError: @@ -92,6 +96,7 @@ def _flatten_to_unflatten(t, state_dict, prefix): """ Flatten the torch compatible state_dict before loading into t, and then recover the unflattened layers. """ + # typically, `t` is a bunch of ShapeDtypeStructs, which can't be transposed etc. so we instead have to zeros() # into real arrays (that aren't actually real b/c this is inside a jit) def _dt_struct_to_array(struct): @@ -107,18 +112,15 @@ def _flatten_to_unflatten(t, state_dict, prefix): @typing.overload -def with_prefix(prefix: str | None, leaf: str) -> str: - ... +def with_prefix(prefix: str | None, leaf: str) -> str: ... @typing.overload -def with_prefix(prefix: str, leaf: None) -> str: - ... +def with_prefix(prefix: str, leaf: None) -> str: ... @typing.overload -def with_prefix(prefix: Optional[str], leaf: Optional[str]) -> Optional[str]: - ... +def with_prefix(prefix: Optional[str], leaf: Optional[str]) -> Optional[str]: ... def with_prefix(prefix: Optional[str], leaf: Optional[str]) -> Optional[str]: diff --git a/src/haliax/_src/util.py b/src/haliax/_src/util.py index 61f3ea9..3bbdd9d 100644 --- a/src/haliax/_src/util.py +++ b/src/haliax/_src/util.py @@ -1,5 +1,9 @@ -from typing import Callable, MutableMapping, Sequence, TypeAlias, TypeVar +# Copyright 2025 The Levanter Authors +# +# SPDX-License-Identifier: Apache-2.0 + +from typing import Callable, MutableMapping, Sequence, TypeAlias, TypeVar T = TypeVar("T") U = TypeVar("U") diff --git a/src/haliax/axis.py b/src/haliax/axis.py index b90a10e..b47a19a 100644 --- a/src/haliax/axis.py +++ b/src/haliax/axis.py @@ -1,3 +1,8 @@ +# Copyright 2025 The Levanter Authors +# +# SPDX-License-Identifier: Apache-2.0 + + import typing from dataclasses import dataclass from math import prod @@ -88,8 +93,7 @@ def selects_axis(selector: AxisSelection, selected: AxisSelection) -> bool: return True -class _Sentinel: - ... +class _Sentinel: ... def is_axis_compatible(ax1: AxisSelector, ax2: AxisSelector): @@ -140,23 +144,19 @@ def axis_spec_to_shape_dict(axis_spec: AxisSelection) -> dict[str, Optional[int] @typing.overload -def axis_spec_to_tuple(axis_spec: ShapeDict) -> tuple[Axis, ...]: - ... +def axis_spec_to_tuple(axis_spec: ShapeDict) -> tuple[Axis, ...]: ... @typing.overload -def axis_spec_to_tuple(axis_spec: AxisSpec) -> tuple[Axis, ...]: - ... +def axis_spec_to_tuple(axis_spec: AxisSpec) -> tuple[Axis, ...]: ... @typing.overload -def axis_spec_to_tuple(axis_spec: PartialShapeDict) -> tuple[AxisSelector, ...]: - ... +def axis_spec_to_tuple(axis_spec: PartialShapeDict) -> tuple[AxisSelector, ...]: ... @typing.overload -def axis_spec_to_tuple(axis_spec: AxisSelection) -> tuple[AxisSelector, ...]: - ... +def axis_spec_to_tuple(axis_spec: AxisSelection) -> tuple[AxisSelector, ...]: ... def axis_spec_to_tuple(axis_spec: AxisSelection) -> tuple[AxisSelector, ...]: @@ -230,23 +230,19 @@ def concat_axes(a1, a2): @typing.overload -def union_axes(a1: ShapeDict, a2: AxisSpec) -> ShapeDict: - ... +def union_axes(a1: ShapeDict, a2: AxisSpec) -> ShapeDict: ... @typing.overload -def union_axes(a1: AxisSpec, a2: ShapeDict) -> ShapeDict: - ... +def union_axes(a1: AxisSpec, a2: ShapeDict) -> ShapeDict: ... @typing.overload -def union_axes(a1: AxisSpec, a2: AxisSpec) -> AxisSpec: - ... +def union_axes(a1: AxisSpec, a2: AxisSpec) -> AxisSpec: ... @typing.overload -def union_axes(a1: AxisSelection, a2: AxisSelection) -> AxisSelection: - ... +def union_axes(a1: AxisSelection, a2: AxisSelection) -> AxisSelection: ... def union_axes(a1: AxisSelection, a2: AxisSelection) -> AxisSelection: @@ -372,23 +368,19 @@ def without_axes(axis_spec: AxisSelection, to_remove: AxisSelection, allow_misma @typing.overload -def unsize_axes(axis_spec: PartialShapeDict, to_unsize: AxisSelection) -> PartialShapeDict: - ... +def unsize_axes(axis_spec: PartialShapeDict, to_unsize: AxisSelection) -> PartialShapeDict: ... @typing.overload -def unsize_axes(axis_spec: AxisSelection, to_unsize: AxisSelection) -> AxisSelection: - ... +def unsize_axes(axis_spec: AxisSelection, to_unsize: AxisSelection) -> AxisSelection: ... @typing.overload -def unsize_axes(axis_spec: PartialShapeDict) -> PartialShapeDict: - ... +def unsize_axes(axis_spec: PartialShapeDict) -> PartialShapeDict: ... @typing.overload -def unsize_axes(axis_spec: AxisSelection) -> AxisSelection: - ... +def unsize_axes(axis_spec: AxisSelection) -> AxisSelection: ... def unsize_axes(axis_spec: AxisSelection, to_unsize: Optional[AxisSelection] = None) -> AxisSelection: @@ -424,13 +416,11 @@ def unsize_axes(axis_spec: AxisSelection, to_unsize: Optional[AxisSelection] = N @overload -def replace_axis(axis_spec: AxisSpec, old: AxisSelector, new: AxisSpec) -> AxisSpec: - ... +def replace_axis(axis_spec: AxisSpec, old: AxisSelector, new: AxisSpec) -> AxisSpec: ... @overload -def replace_axis(axis_spec: AxisSelection, old: AxisSelector, new: AxisSelection) -> AxisSelection: - ... +def replace_axis(axis_spec: AxisSelection, old: AxisSelector, new: AxisSelection) -> AxisSelection: ... def replace_axis(axis_spec: AxisSelection, old: AxisSelector, new: AxisSelection) -> AxisSelection: @@ -466,13 +456,11 @@ def replace_axis(axis_spec: AxisSelection, old: AxisSelector, new: AxisSelection @overload -def intersect_axes(ax1: ShapeDict, ax2: AxisSelection) -> ShapeDict: - ... +def intersect_axes(ax1: ShapeDict, ax2: AxisSelection) -> ShapeDict: ... @overload -def intersect_axes(ax1: tuple[AxisSelector, ...], ax2: AxisSpec) -> tuple[Axis, ...]: - ... +def intersect_axes(ax1: tuple[AxisSelector, ...], ax2: AxisSpec) -> tuple[Axis, ...]: ... @overload @@ -550,13 +538,11 @@ def axis_size(ax: AxisSpec) -> int: @typing.overload -def resolve_axis(axis_spec: AxisSpec, axis_selection: AxisSelector) -> Axis: - ... +def resolve_axis(axis_spec: AxisSpec, axis_selection: AxisSelector) -> Axis: ... @typing.overload -def resolve_axis(axis_spec: AxisSpec, axis_selection: AxisSelection) -> AxisSpec: - ... +def resolve_axis(axis_spec: AxisSpec, axis_selection: AxisSelection) -> AxisSpec: ... def resolve_axis(axis_spec: AxisSpec, axis_selection: AxisSelection) -> AxisSpec: diff --git a/src/haliax/core.py b/src/haliax/core.py index 4ecd35b..cd2c636 100644 --- a/src/haliax/core.py +++ b/src/haliax/core.py @@ -1,3 +1,8 @@ +# Copyright 2025 The Levanter Authors +# +# SPDX-License-Identifier: Apache-2.0 + + from __future__ import annotations import contextlib @@ -129,7 +134,7 @@ NamedArrayAxesSpec = Union[ def _parse_namedarray_axes( - item: NamedArrayAxesSpec | typing.Annotated["NamedArray", NamedArrayAxes] + item: NamedArrayAxesSpec | typing.Annotated["NamedArray", NamedArrayAxes], ) -> NamedArrayAxes: origin = typing.get_origin(item) if origin is typing.Annotated: @@ -345,20 +350,16 @@ class NamedArray(metaclass=NamedArrayMeta): return tuple(result) @overload - def resolve_axis(self, axis: AxisSelector) -> Axis: - ... + def resolve_axis(self, axis: AxisSelector) -> Axis: ... @overload - def resolve_axis(self, axis: tuple[AxisSelector, ...]) -> tuple[Axis, ...]: - ... + def resolve_axis(self, axis: tuple[AxisSelector, ...]) -> tuple[Axis, ...]: ... @overload - def resolve_axis(self, axis: PartialShapeDict) -> ShapeDict: - ... + def resolve_axis(self, axis: PartialShapeDict) -> ShapeDict: ... @overload - def resolve_axis(self, axes: AxisSelection) -> AxisSpec: - ... + def resolve_axis(self, axes: AxisSelection) -> AxisSpec: ... def resolve_axis(self, axes: AxisSelection) -> AxisSpec: # type: ignore[misc] """ @@ -417,8 +418,7 @@ class NamedArray(metaclass=NamedArrayMeta): ... @overload - def _lookup_indices(self, axis: AxisSelection) -> Tuple[Optional[int], ...]: - ... + def _lookup_indices(self, axis: AxisSelection) -> Tuple[Optional[int], ...]: ... def _lookup_indices(self, axis: AxisSelection) -> Union[Optional[int], Tuple[Optional[int], ...]]: """ @@ -438,12 +438,10 @@ class NamedArray(metaclass=NamedArrayMeta): ... @overload - def axis_indices(self, axis: Sequence[AxisSelector]) -> Tuple[Optional[int], ...]: - ... + def axis_indices(self, axis: Sequence[AxisSelector]) -> Tuple[Optional[int], ...]: ... @overload - def axis_indices(self, axis: AxisSelection) -> Tuple[Optional[int], ...]: - ... + def axis_indices(self, axis: AxisSelection) -> Tuple[Optional[int], ...]: ... def axis_indices(self, axis: AxisSelection) -> Union[Optional[int], Tuple[Optional[int], ...]]: """ @@ -520,14 +518,12 @@ class NamedArray(metaclass=NamedArrayMeta): @typing.overload def slice( self, axis: AxisSelector, new_axis: Optional[AxisSelector] = None, start: int = 0, length: Optional[int] = None - ) -> "NamedArray": - ... + ) -> "NamedArray": ... @typing.overload def slice( self, start: Mapping[AxisSelector, int], length: Mapping[AxisSelector, Union[int, Axis]] - ) -> "NamedArray": - ... + ) -> "NamedArray": ... def slice(self, *args, **kwargs) -> "NamedArray": # pragma: no cover return haliax.slice(self, *args, **kwargs) @@ -655,8 +651,7 @@ class NamedArray(metaclass=NamedArrayMeta): @typing.overload def dot( self, axis: Optional[AxisSelection], *b, precision: PrecisionLike = None, dot_general=jax.lax.dot_general - ) -> "NamedArray": - ... + ) -> "NamedArray": ... @typing.overload def dot( @@ -665,8 +660,7 @@ class NamedArray(metaclass=NamedArrayMeta): axis: Optional[AxisSelection], precision: PrecisionLike = None, dot_general=jax.lax.dot_general, - ) -> "NamedArray": - ... + ) -> "NamedArray": ... def dot(self, *args, **kwargs) -> "NamedArray": if "axis" in kwargs or len(args) == 0: @@ -1310,7 +1304,6 @@ def _compute_new_axes_and_slices_for_index( return new_axes, ordered_slices - def split(a: NamedArray, axis: AxisSelector, new_axes: Sequence[Axis]) -> Sequence[NamedArray]: """ Splits an array along an axis into multiple arrays, one for each element of new_axes. @@ -1692,15 +1685,11 @@ def broadcast_to( extra_axis_names = [ax.name for ax in a.axes if ax.name not in axes_dict] if enforce_no_extra_axes and extra_axis_names: - raise ValueError( - f"Cannot broadcast {a.shape} to {axes_dict}: extra axes present {extra_axis_names}" - ) + raise ValueError(f"Cannot broadcast {a.shape} to {axes_dict}: extra axes present {extra_axis_names}") axes_names_in_a = {ax.name for ax in a.axes} to_add = tuple( - Axis(axis_name(ax), axes_dict[axis_name(ax)]) - for ax in axes_tuple - if axis_name(ax) not in axes_names_in_a + Axis(axis_name(ax), axes_dict[axis_name(ax)]) for ax in axes_tuple if axis_name(ax) not in axes_names_in_a ) all_axes = to_add + a.axes @@ -1734,15 +1723,13 @@ def _is_subsequence(needle, haystack): @overload def broadcast_arrays( *arrays: NamedArray, require_subset: bool = True, ensure_order: bool = True -) -> Tuple[NamedArray, ...]: - ... +) -> Tuple[NamedArray, ...]: ... @overload def broadcast_arrays( *arrays: Optional[NamedOrNumeric], require_subset: bool = True, ensure_order: bool = True -) -> Tuple[Optional[NamedOrNumeric], ...]: - ... +) -> Tuple[Optional[NamedOrNumeric], ...]: ... def broadcast_arrays( @@ -1770,22 +1757,19 @@ def broadcast_arrays( @overload def broadcast_arrays_and_return_axes( *arrays: NamedArray, require_subset: bool = True, ensure_order: bool = True -) -> Tuple[Tuple[NamedArray, ...], Tuple[Axis, ...]]: - ... +) -> Tuple[Tuple[NamedArray, ...], Tuple[Axis, ...]]: ... @overload def broadcast_arrays_and_return_axes( *arrays: NamedOrNumeric, require_subset: bool = True, ensure_order: bool = True -) -> Tuple[Tuple[NamedOrNumeric, ...], Tuple[Axis, ...]]: - ... +) -> Tuple[Tuple[NamedOrNumeric, ...], Tuple[Axis, ...]]: ... @overload def broadcast_arrays_and_return_axes( *arrays: Optional[NamedOrNumeric], require_subset: bool = True, ensure_order: bool = True -) -> Tuple[Tuple[Optional[NamedOrNumeric], ...], Tuple[Axis, ...]]: - ... +) -> Tuple[Tuple[Optional[NamedOrNumeric], ...], Tuple[Axis, ...]]: ... def broadcast_arrays_and_return_axes( @@ -1816,7 +1800,7 @@ def broadcast_arrays_and_return_axes( return (None,), () if isinstance(a, NamedArray): return (a,), a.axes - return (named(jnp.asarray(a), ()), ), () + return (named(jnp.asarray(a), ()),), () # sort the arrays by size, so that we use the biggest ones to broadcast the others # need to hold on to the order so we can return the arrays in the same order diff --git a/src/haliax/debug.py b/src/haliax/debug.py index c10d073..b3ed1a6 100644 --- a/src/haliax/debug.py +++ b/src/haliax/debug.py @@ -1,3 +1,8 @@ +# Copyright 2025 The Levanter Authors +# +# SPDX-License-Identifier: Apache-2.0 + + import dataclasses from typing import List, Tuple, Union, Sequence @@ -13,7 +18,6 @@ from haliax.util import is_jax_or_hax_array_like from ._src.util import IdentityMap - ArrayLike = Union[jnp.ndarray, NamedArray] diff --git a/src/haliax/field.py b/src/haliax/field.py index b420f88..6136fd5 100644 --- a/src/haliax/field.py +++ b/src/haliax/field.py @@ -1,3 +1,8 @@ +# Copyright 2025 The Levanter Authors +# +# SPDX-License-Identifier: Apache-2.0 + + from __future__ import annotations from typing import Any, Callable diff --git a/src/haliax/haxtyping.py b/src/haliax/haxtyping.py index 4f131ff..93a6d40 100644 --- a/src/haliax/haxtyping.py +++ b/src/haliax/haxtyping.py @@ -1,3 +1,8 @@ +# Copyright 2025 The Levanter Authors +# +# SPDX-License-Identifier: Apache-2.0 + + from __future__ import annotations from dataclasses import dataclass from typing import TYPE_CHECKING, Any @@ -13,15 +18,30 @@ class DTypeCategory: def __repr__(self) -> str: # pragma: no cover - trivial return self.name + if TYPE_CHECKING: # ── STATIC ONLY: re‑export jaxtyping’s aliases so mypy/Pyright/PyCharm see them from jaxtyping import ( - Float32 as f32, Float64 as f64, Float16 as f16, BFloat16 as bf16, - Int8 as i8, Int16 as i16, Int32 as i32, Int64 as i64, - UInt8 as u8, UInt16 as u16, UInt32 as u32, UInt64 as u64, - Bool as bool_, Complex64 as complex64, Complex128 as complex128, - Float as Float, Int as Int, UInt as UInt, + Float32 as f32, + Float64 as f64, + Float16 as f16, + BFloat16 as bf16, + Int8 as i8, + Int16 as i16, + Int32 as i32, + Int64 as i64, + UInt8 as u8, + UInt16 as u16, + UInt32 as u32, + UInt64 as u64, + Bool as bool_, + Complex64 as complex64, + Complex128 as complex128, + Float as Float, + Int as Int, + UInt as UInt, ) + # axes‑only helper from typing import Annotated as Named @@ -45,6 +65,7 @@ else: def _make_dtype_wrapper(dtype): """Factory for f32, i32, etc.""" + class _Wrapper: def __class_getitem__(cls, item): # two‑arg form: (BaseType, axes_spec) @@ -56,8 +77,7 @@ else: # Delegate non‑NamedArray to jaxtyping if base is not NamedArray: # e.g. use jt.Float32 for jnp.float32 - jaxt = getattr(jt, f"Float{dtype.itemsize*8}") \ - if hasattr(dtype, "itemsize") else jt.Float + jaxt = getattr(jt, f"Float{dtype.itemsize*8}") if hasattr(dtype, "itemsize") else jt.Float return jaxt[base, axes_spec] # Handle NamedArray path @@ -67,28 +87,25 @@ else: return _Wrapper # ── Build all dtype wrappers ───────────────────────────────────────────── - f32 = _make_dtype_wrapper(jnp.float32) - f64 = _make_dtype_wrapper(jnp.float64) - f16 = _make_dtype_wrapper(jnp.float16) + f32 = _make_dtype_wrapper(jnp.float32) + f64 = _make_dtype_wrapper(jnp.float64) + f16 = _make_dtype_wrapper(jnp.float16) bf16 = _make_dtype_wrapper(jnp.bfloat16) - i8 = _make_dtype_wrapper(jnp.int8) + i8 = _make_dtype_wrapper(jnp.int8) i16 = _make_dtype_wrapper(jnp.int16) i32 = _make_dtype_wrapper(jnp.int32) i64 = _make_dtype_wrapper(jnp.int64) - u8 = _make_dtype_wrapper(jnp.uint8) + u8 = _make_dtype_wrapper(jnp.uint8) u16 = _make_dtype_wrapper(jnp.uint16) u32 = _make_dtype_wrapper(jnp.uint32) u64 = _make_dtype_wrapper(jnp.uint64) - bool_ = _make_dtype_wrapper(jnp.bool_) - complex64 = _make_dtype_wrapper(jnp.complex64) + bool_ = _make_dtype_wrapper(jnp.bool_) + complex64 = _make_dtype_wrapper(jnp.complex64) complex128 = _make_dtype_wrapper(jnp.complex128) - - - def _make_category_wrapper(name: str, category): """Like _make_dtype_wrapper but matches any dtype in the JAX category.""" @@ -111,14 +128,12 @@ else: return _Wrapper - # Build the category wrappers Float = _make_category_wrapper("float", jnp.floating) Complex = _make_category_wrapper("complex", jnp.complexfloating) Int = _make_category_wrapper("int", jnp.signedinteger) UInt = _make_category_wrapper("uInt", jnp.unsignedinteger) - # ── Named: axes‑only helper ─────────────────────────────────────────────── class _NamedHelper: @classmethod @@ -131,8 +146,19 @@ else: __all__ = [ "Named", - "f32", "f64", "f16", "bf16", - "i8", "i16", "i32", "i64", - "u8", "u16", "u32", "u64", - "bool_", "complex64", "complex128", + "f32", + "f64", + "f16", + "bf16", + "i8", + "i16", + "i32", + "i64", + "u8", + "u16", + "u32", + "u64", + "bool_", + "complex64", + "complex128", ] diff --git a/src/haliax/hof.py b/src/haliax/hof.py index c4a4a1a..599e914 100644 --- a/src/haliax/hof.py +++ b/src/haliax/hof.py @@ -1,3 +1,8 @@ +# Copyright 2025 The Levanter Authors +# +# SPDX-License-Identifier: Apache-2.0 + + import inspect from functools import wraps @@ -76,9 +81,11 @@ def vmap( # axis_spec_bound_sig's job is to hold that mapping signature_default = signature.replace( parameters=[ - p - if p.kind in (inspect.Parameter.VAR_POSITIONAL, inspect.Parameter.VAR_KEYWORD) - else p.replace(default=default) + ( + p + if p.kind in (inspect.Parameter.VAR_POSITIONAL, inspect.Parameter.VAR_KEYWORD) + else p.replace(default=default) + ) for p in signature.parameters.values() ] ) diff --git a/src/haliax/jax_utils.py b/src/haliax/jax_utils.py index eb8edc7..d7a1caa 100644 --- a/src/haliax/jax_utils.py +++ b/src/haliax/jax_utils.py @@ -1,3 +1,8 @@ +# Copyright 2025 The Levanter Authors +# +# SPDX-License-Identifier: Apache-2.0 + + import functools as ft import typing import warnings @@ -16,7 +21,6 @@ from jaxtyping import PRNGKeyArray import haliax from haliax.types import PrecisionLike - try: # jax v0.5.1 or newer from jax._src.numpy import ( @@ -106,13 +110,11 @@ def _UNSPECIFIED(): @typing.overload -def named_call(f: F, name: Optional[str] = None) -> F: - ... +def named_call(f: F, name: Optional[str] = None) -> F: ... @typing.overload -def named_call(*, name: Optional[str] = None) -> Callable[[F], F]: - ... +def named_call(*, name: Optional[str] = None) -> Callable[[F], F]: ... def named_call(f=_UNSPECIFIED, name: Optional[str] = None): diff --git a/src/haliax/nn/__init__.py b/src/haliax/nn/__init__.py index 4ea2738..3933da9 100644 --- a/src/haliax/nn/__init__.py +++ b/src/haliax/nn/__init__.py @@ -1,3 +1,8 @@ +# Copyright 2025 The Levanter Authors +# +# SPDX-License-Identifier: Apache-2.0 + + import jax.nn as jnn import jax.numpy as jnp diff --git a/src/haliax/nn/activations.py b/src/haliax/nn/activations.py index f130411..2a8188d 100644 --- a/src/haliax/nn/activations.py +++ b/src/haliax/nn/activations.py @@ -1,3 +1,8 @@ +# Copyright 2025 The Levanter Authors +# +# SPDX-License-Identifier: Apache-2.0 + + import typing from jax import nn as jnn @@ -8,7 +13,6 @@ from ..core import NamedArray from ..types import Scalar from ..wrap import wrap_elemwise_unary - A = typing.TypeVar("A", Scalar, NamedArray, jnp.ndarray) diff --git a/src/haliax/nn/attention.py b/src/haliax/nn/attention.py index 60e6a28..8f780ca 100644 --- a/src/haliax/nn/attention.py +++ b/src/haliax/nn/attention.py @@ -1,3 +1,8 @@ +# Copyright 2025 The Levanter Authors +# +# SPDX-License-Identifier: Apache-2.0 + + import math from typing import List, Optional @@ -12,7 +17,6 @@ from haliax.axis import Axis, AxisSelection, AxisSelector, AxisSpec, axis_name, from haliax.core import NamedArray from haliax.types import PrecisionLike - # With attention, we usually distinguish between the mask and the bias, though the former is just a special case of the # latter. In practice, the mask is a boolean array that is applied using `where` to the logits, while the bias is a # float array that is added to the logits. The mask is usually used to prevent attention to certain positions, while @@ -155,7 +159,7 @@ def combine_masks_or(mask1: Optional[NamedArray], mask2: Optional[NamedArray]) - return mask1 | mask2.broadcast_axis(mask1.axes) -def causal_mask(QPos: Axis, KPos: Axis, q_start: int | NamedArray = 0, k_start: int | NamedArray= 0) -> NamedArray: +def causal_mask(QPos: Axis, KPos: Axis, q_start: int | NamedArray = 0, k_start: int | NamedArray = 0) -> NamedArray: """ Creates a materialized causal mask for attention. diff --git a/src/haliax/nn/conv.py b/src/haliax/nn/conv.py index b41e783..31876fb 100644 --- a/src/haliax/nn/conv.py +++ b/src/haliax/nn/conv.py @@ -1,3 +1,8 @@ +# Copyright 2025 The Levanter Authors +# +# SPDX-License-Identifier: Apache-2.0 + + import string from functools import cached_property from typing import Optional, Sequence, TypeVar @@ -24,7 +29,6 @@ from ..jax_utils import named_call from ..random import uniform from ..util import ensure_tuple - T = TypeVar("T") diff --git a/src/haliax/nn/dropout.py b/src/haliax/nn/dropout.py index 9c8f38a..b04f4ed 100644 --- a/src/haliax/nn/dropout.py +++ b/src/haliax/nn/dropout.py @@ -1,3 +1,8 @@ +# Copyright 2025 The Levanter Authors +# +# SPDX-License-Identifier: Apache-2.0 + + from typing import Optional import equinox as eqx diff --git a/src/haliax/nn/embedding.py b/src/haliax/nn/embedding.py index cc2733b..2141a9a 100644 --- a/src/haliax/nn/embedding.py +++ b/src/haliax/nn/embedding.py @@ -1,3 +1,8 @@ +# Copyright 2025 The Levanter Authors +# +# SPDX-License-Identifier: Apache-2.0 + + import dataclasses import warnings from typing import Optional diff --git a/src/haliax/nn/linear.py b/src/haliax/nn/linear.py index 1c8c825..9a6add3 100644 --- a/src/haliax/nn/linear.py +++ b/src/haliax/nn/linear.py @@ -1,3 +1,8 @@ +# Copyright 2025 The Levanter Authors +# +# SPDX-License-Identifier: Apache-2.0 + + import dataclasses import math from functools import partial diff --git a/src/haliax/nn/loss.py b/src/haliax/nn/loss.py index cd3b740..3bd9433 100644 --- a/src/haliax/nn/loss.py +++ b/src/haliax/nn/loss.py @@ -1,3 +1,8 @@ +# Copyright 2025 The Levanter Authors +# +# SPDX-License-Identifier: Apache-2.0 + + import typing import warnings from typing import Optional @@ -19,8 +24,7 @@ def cross_entropy_loss( reduction: Optional[ReductionFunction] | Unspecified = UNSPECIFIED, where: Optional[NamedArray] = None, reduction_axis: None = None, -) -> jnp.ndarray | NamedArray: - ... +) -> jnp.ndarray | NamedArray: ... @typing.overload @@ -31,8 +35,7 @@ def cross_entropy_loss( reduction: Optional[ReductionFunction] | Unspecified = UNSPECIFIED, where: Optional[NamedArray] = None, reduction_axis: AxisSelection = ..., -) -> NamedArray: - ... +) -> NamedArray: ... def cross_entropy_loss( @@ -63,8 +66,7 @@ def binary_cross_entropy_loss( reduction: Optional[ReductionFunction] | Unspecified = UNSPECIFIED, where: Optional[NamedArray] = None, reduction_axis: None = None, -) -> jnp.ndarray | NamedArray: - ... +) -> jnp.ndarray | NamedArray: ... @typing.overload @@ -74,8 +76,7 @@ def binary_cross_entropy_loss( reduction: Optional[ReductionFunction] | Unspecified = UNSPECIFIED, where: Optional[NamedArray] = None, reduction_axis: AxisSelection = ..., -) -> NamedArray: - ... +) -> NamedArray: ... def binary_cross_entropy_loss( diff --git a/src/haliax/nn/mlp.py b/src/haliax/nn/mlp.py index 640cda3..f158154 100644 --- a/src/haliax/nn/mlp.py +++ b/src/haliax/nn/mlp.py @@ -1,3 +1,8 @@ +# Copyright 2025 The Levanter Authors +# +# SPDX-License-Identifier: Apache-2.0 + + from typing import Callable, Optional, Sequence import equinox as eqx @@ -11,7 +16,6 @@ from ..quantization import DotGeneralOp from .activations import relu from .linear import Linear - DEFAULT_WIDTH_NAME = "mlp" diff --git a/src/haliax/nn/normalization.py b/src/haliax/nn/normalization.py index 28294e0..206eb5e 100644 --- a/src/haliax/nn/normalization.py +++ b/src/haliax/nn/normalization.py @@ -1,3 +1,8 @@ +# Copyright 2025 The Levanter Authors +# +# SPDX-License-Identifier: Apache-2.0 + + import dataclasses from abc import abstractmethod from typing import Optional, TypeVar @@ -15,7 +20,6 @@ from ..core import NamedArray from ..types import Scalar from ..wrap import unwrap_namedarrays, wrap_axiswise_call, wrap_reduction_call - A = TypeVar("A", Scalar, NamedArray, jnp.ndarray) @@ -93,6 +97,7 @@ class LayerNorm(LayerNormBase): Normalises the input along the specified axis (or axes), using the mean and variance of the input along that axis. """ + axis: AxisSpec = eqx.field(static=True) weight: Optional[NamedArray] bias: Optional[NamedArray] diff --git a/src/haliax/nn/pool.py b/src/haliax/nn/pool.py index 178ff17..5b416da 100644 --- a/src/haliax/nn/pool.py +++ b/src/haliax/nn/pool.py @@ -1,3 +1,8 @@ +# Copyright 2025 The Levanter Authors +# +# SPDX-License-Identifier: Apache-2.0 + + # Pooling operations, inspired by Flax from functools import reduce from typing import Callable, Literal, Optional @@ -12,7 +17,6 @@ from ..partitioning import auto_sharded from ..types import Scalar from ..util import ensure_tuple - Padding = Literal["SAME", "VALID"] | int | tuple[tuple[int, int], ...] DEFAULT_PADDING: Literal["VALID"] = "VALID" diff --git a/src/haliax/nn/scan.py b/src/haliax/nn/scan.py index 4a77f56..a982d12 100644 --- a/src/haliax/nn/scan.py +++ b/src/haliax/nn/scan.py @@ -1,9 +1,27 @@ +# Copyright 2025 The Levanter Authors +# +# SPDX-License-Identifier: Apache-2.0 + + import dataclasses import functools import re import warnings -from typing import Any, Callable, Concatenate, Dict, Generic, Optional, Protocol, Sequence, Type, TypeVar, cast, \ - overload, ParamSpec +from typing import ( + Any, + Callable, + Concatenate, + Dict, + Generic, + Optional, + Protocol, + Sequence, + Type, + TypeVar, + cast, + overload, + ParamSpec, +) import equinox as eqx import jax @@ -18,7 +36,6 @@ from .._src.scan import ScanCheckpointPolicy, ScanCheckpointSpec from .._src.state_dict import ModuleWithStateDictSerialization, StateDict, with_prefix from ..axis import Axis - M = TypeVar("M", bound=eqx.Module) M_co = TypeVar("M_co", bound=eqx.Module, covariant=True) M_contra = TypeVar("M_contra", bound=eqx.Module, contravariant=True) @@ -28,24 +45,23 @@ CarryT = TypeVar("CarryT") OutputT_co = TypeVar("OutputT_co", covariant=True) P = ParamSpec("P") + class FoldFunction(Protocol[M_contra, P, CarryT]): - def __call__(self, module: M_contra, carry: CarryT, *args: P.args, **kwargs: P.kwargs) -> CarryT: - ... + def __call__(self, module: M_contra, carry: CarryT, *args: P.args, **kwargs: P.kwargs) -> CarryT: ... class ScanFunction(Protocol[M_contra, CarryT, P, OutputT_co]): - def __call__(self, module: M_contra, carry: CarryT, *args: P.args, **kwargs: P.kwargs) -> tuple[CarryT, OutputT_co]: - ... + def __call__( + self, module: M_contra, carry: CarryT, *args: P.args, **kwargs: P.kwargs + ) -> tuple[CarryT, OutputT_co]: ... class VmapFunction(Protocol[M_contra, P, OutputT_co]): - def __call__(self, module: M_contra, *args: P.args, **kwargs: P.kwargs) -> OutputT_co: - ... + def __call__(self, module: M_contra, *args: P.args, **kwargs: P.kwargs) -> OutputT_co: ... class ModuleInit(Protocol[M_co]): - def __call__(self, *args, **kwargs) -> M_co: - ... + def __call__(self, *args, **kwargs) -> M_co: ... class BlockFoldable(Protocol[M]): @@ -68,47 +84,39 @@ class BlockFoldable(Protocol[M]): *, gradient_checkpointing: ScanCheckpointSpec = False, prevent_cse: bool = False, - ) -> ModuleInit[S]: - ... + ) -> ModuleInit[S]: ... - def scan(self, init: T, *extra_args, **extra_kwargs): - ... + def scan(self, init: T, *extra_args, **extra_kwargs): ... - def fold(self, init: T, *args, **kwargs) -> T: - ... + def fold(self, init: T, *args, **kwargs) -> T: ... @overload - def fold_via(self, fn: FoldFunction[M, P, CarryT]) -> Callable[Concatenate[CarryT, P], CarryT]: - ... + def fold_via(self, fn: FoldFunction[M, P, CarryT]) -> Callable[Concatenate[CarryT, P], CarryT]: ... @overload - def fold_via(self, fn: Callable[[M, CarryT], CarryT]) -> Callable[[CarryT], CarryT]: - ... + def fold_via(self, fn: Callable[[M, CarryT], CarryT]) -> Callable[[CarryT], CarryT]: ... - def fold_via(self, fn: Callable[..., CarryT]) -> Callable[Concatenate[CarryT, P], CarryT]: - ... + def fold_via(self, fn: Callable[..., CarryT]) -> Callable[Concatenate[CarryT, P], CarryT]: ... @overload - def scan_via(self, fn: ScanFunction[M, CarryT, P, OutputT_co]) -> Callable[Concatenate[CarryT, P], tuple[CarryT, OutputT_co]]: - ... + def scan_via( + self, fn: ScanFunction[M, CarryT, P, OutputT_co] + ) -> Callable[Concatenate[CarryT, P], tuple[CarryT, OutputT_co]]: ... @overload - def scan_via(self, fn: Callable[[M, CarryT], tuple[CarryT, OutputT_co]]) -> Callable[[CarryT], tuple[CarryT, OutputT_co]]: - ... + def scan_via( + self, fn: Callable[[M, CarryT], tuple[CarryT, OutputT_co]] + ) -> Callable[[CarryT], tuple[CarryT, OutputT_co]]: ... - def scan_via(self, fn: Callable[..., tuple[CarryT, OutputT_co]]) -> Callable[P, tuple[CarryT, OutputT_co]]: - ... + def scan_via(self, fn: Callable[..., tuple[CarryT, OutputT_co]]) -> Callable[P, tuple[CarryT, OutputT_co]]: ... @overload - def vmap_via(self, fn: VmapFunction[M, P, OutputT_co]) -> Callable[P, OutputT_co]: - ... + def vmap_via(self, fn: VmapFunction[M, P, OutputT_co]) -> Callable[P, OutputT_co]: ... @overload - def vmap_via(self, fn: Callable[[M], OutputT_co]) -> Callable[[], OutputT_co]: - ... + def vmap_via(self, fn: Callable[[M], OutputT_co]) -> Callable[[], OutputT_co]: ... - def vmap_via(self, fn: Callable[..., OutputT_co]) -> Callable[..., OutputT_co]: - ... + def vmap_via(self, fn: Callable[..., OutputT_co]) -> Callable[..., OutputT_co]: ... def unstacked(self) -> Sequence[M]: """ @@ -218,12 +226,10 @@ class BlockSeq(ModuleWithStateDictSerialization, Generic[M]): return do_fold(init, *args, **kwargs) @overload - def fold_via(self, fn: FoldFunction[M, P, CarryT]) -> Callable[Concatenate[CarryT, P], CarryT]: - ... + def fold_via(self, fn: FoldFunction[M, P, CarryT]) -> Callable[Concatenate[CarryT, P], CarryT]: ... @overload - def fold_via(self, fn: Callable[[M, CarryT], CarryT]) -> Callable[[CarryT], CarryT]: - ... + def fold_via(self, fn: Callable[[M, CarryT], CarryT]) -> Callable[[CarryT], CarryT]: ... def fold_via(self, fn: Callable[..., CarryT]): """Return a function that folds over the sequence using ``fn``. @@ -242,12 +248,14 @@ class BlockSeq(ModuleWithStateDictSerialization, Generic[M]): return do_fold @overload - def scan_via(self, fn: ScanFunction[M, CarryT, P, OutputT_co]) -> Callable[Concatenate[CarryT, P], tuple[CarryT, OutputT_co]]: - ... + def scan_via( + self, fn: ScanFunction[M, CarryT, P, OutputT_co] + ) -> Callable[Concatenate[CarryT, P], tuple[CarryT, OutputT_co]]: ... @overload - def scan_via(self, fn: Callable[[M, CarryT], tuple[CarryT, OutputT_co]]) -> Callable[[CarryT], tuple[CarryT, OutputT_co]]: - ... + def scan_via( + self, fn: Callable[[M, CarryT], tuple[CarryT, OutputT_co]] + ) -> Callable[[CarryT], tuple[CarryT, OutputT_co]]: ... def scan_via(self, fn: Callable[..., tuple[CarryT, OutputT_co]]): """Return a function that scans over the sequence using ``fn``. @@ -271,12 +279,10 @@ class BlockSeq(ModuleWithStateDictSerialization, Generic[M]): return do_scan @overload - def vmap_via(self, fn: VmapFunction[M, P, OutputT_co]) -> Callable[P, OutputT_co]: - ... + def vmap_via(self, fn: VmapFunction[M, P, OutputT_co]) -> Callable[P, OutputT_co]: ... @overload - def vmap_via(self, fn: Callable[[M], OutputT_co]) -> Callable[[], OutputT_co]: - ... + def vmap_via(self, fn: Callable[[M], OutputT_co]) -> Callable[[], OutputT_co]: ... def vmap_via(self, fn: Callable[..., OutputT_co]) -> Callable[..., OutputT_co]: """Return a function that applies each block independently using ``fn``. @@ -519,12 +525,10 @@ class Stacked(ModuleWithStateDictSerialization, Generic[M]): return do_fold(init, *args, **kwargs) @overload - def fold_via(self, fn: FoldFunction[M, P, CarryT]) -> Callable[Concatenate[CarryT, P], CarryT]: - ... + def fold_via(self, fn: FoldFunction[M, P, CarryT]) -> Callable[Concatenate[CarryT, P], CarryT]: ... @overload - def fold_via(self, fn: Callable[[M, CarryT], CarryT]) -> Callable[[CarryT], CarryT]: - ... + def fold_via(self, fn: Callable[[M, CarryT], CarryT]) -> Callable[[CarryT], CarryT]: ... def fold_via(self, fn: Callable[..., CarryT]): """Return a function that folds over the stack using ``fn``. @@ -537,17 +541,21 @@ class Stacked(ModuleWithStateDictSerialization, Generic[M]): return fn(block, carry, *args, **kwargs) def do_fold(init: CarryT, *args, **kwargs) -> CarryT: - return haliax.fold(do_block, self.Block, remat=self.gradient_checkpointing)(init, self.stacked, *args, **kwargs) + return haliax.fold(do_block, self.Block, remat=self.gradient_checkpointing)( + init, self.stacked, *args, **kwargs + ) return do_fold @overload - def scan_via(self, fn: ScanFunction[M, CarryT, P, OutputT_co]) -> Callable[Concatenate[CarryT, P], tuple[CarryT, OutputT_co]]: - ... + def scan_via( + self, fn: ScanFunction[M, CarryT, P, OutputT_co] + ) -> Callable[Concatenate[CarryT, P], tuple[CarryT, OutputT_co]]: ... @overload - def scan_via(self, fn: Callable[[M, CarryT], tuple[CarryT, OutputT_co]]) -> Callable[[CarryT], tuple[CarryT, OutputT_co]]: - ... + def scan_via( + self, fn: Callable[[M, CarryT], tuple[CarryT, OutputT_co]] + ) -> Callable[[CarryT], tuple[CarryT, OutputT_co]]: ... def scan_via(self, fn: Callable[..., tuple[CarryT, OutputT_co]]): """Return a function that scans over the stack using ``fn``. @@ -560,19 +568,18 @@ class Stacked(ModuleWithStateDictSerialization, Generic[M]): carry, output = fn(block, carry, *args, **kwargs) return carry, output - def do_scan(init: CarryT, *args, **kwargs) -> tuple[CarryT, OutputT_co]: - return haliax.scan(do_block, self.Block, remat=self.gradient_checkpointing)(init, self.stacked, *args, **kwargs) + return haliax.scan(do_block, self.Block, remat=self.gradient_checkpointing)( + init, self.stacked, *args, **kwargs + ) return do_scan @overload - def vmap_via(self, fn: VmapFunction[M, P, OutputT_co]) -> Callable[P, OutputT_co]: - ... + def vmap_via(self, fn: VmapFunction[M, P, OutputT_co]) -> Callable[P, OutputT_co]: ... @overload - def vmap_via(self, fn: Callable[[M], OutputT_co]) -> Callable[[], OutputT_co]: - ... + def vmap_via(self, fn: Callable[[M], OutputT_co]) -> Callable[[], OutputT_co]: ... def vmap_via(self, fn: Callable[..., OutputT_co]) -> Callable[..., OutputT_co]: """Return a function that applies each block independently using ``fn``. diff --git a/src/haliax/ops.py b/src/haliax/ops.py index 6859218..e64a34a 100644 --- a/src/haliax/ops.py +++ b/src/haliax/ops.py @@ -1,3 +1,8 @@ +# Copyright 2025 The Levanter Authors +# +# SPDX-License-Identifier: Apache-2.0 + + import typing from typing import Mapping, Optional, Union @@ -36,8 +41,7 @@ def where( condition: NamedOrNumeric | bool, x: NamedOrNumeric, y: NamedOrNumeric, -) -> NamedArray: - ... +) -> NamedArray: ... @typing.overload @@ -46,8 +50,7 @@ def where( *, fill_value: int, new_axis: Axis, -) -> tuple[NamedArray, ...]: - ... +) -> tuple[NamedArray, ...]: ... def where( @@ -225,8 +228,7 @@ def raw_array_or_scalar(x: NamedOrNumeric): @typing.overload def unique( array: NamedArray, Unique: Axis, *, axis: AxisSelector | None = None, fill_value: ArrayLike | None = None -) -> NamedArray: - ... +) -> NamedArray: ... @typing.overload @@ -237,8 +239,7 @@ def unique( return_index: typing.Literal[True], axis: AxisSelector | None = None, fill_value: ArrayLike | None = None, -) -> tuple[NamedArray, NamedArray]: - ... +) -> tuple[NamedArray, NamedArray]: ... @typing.overload @@ -249,8 +250,7 @@ def unique( return_inverse: typing.Literal[True], axis: AxisSelector | None = None, fill_value: ArrayLike | None = None, -) -> tuple[NamedArray, NamedArray]: - ... +) -> tuple[NamedArray, NamedArray]: ... @typing.overload @@ -261,8 +261,7 @@ def unique( return_counts: typing.Literal[True], axis: AxisSelector | None = None, fill_value: ArrayLike | None = None, -) -> tuple[NamedArray, NamedArray]: - ... +) -> tuple[NamedArray, NamedArray]: ... @typing.overload @@ -275,8 +274,7 @@ def unique( return_counts: bool = False, axis: AxisSelector | None = None, fill_value: ArrayLike | None = None, -) -> NamedArray | tuple[NamedArray, ...]: - ... +) -> NamedArray | tuple[NamedArray, ...]: ... def unique( diff --git a/src/haliax/partitioning.py b/src/haliax/partitioning.py index 6bb2133..678053b 100644 --- a/src/haliax/partitioning.py +++ b/src/haliax/partitioning.py @@ -1,3 +1,8 @@ +# Copyright 2025 The Levanter Authors +# +# SPDX-License-Identifier: Apache-2.0 + + import contextlib import dataclasses import functools @@ -22,6 +27,7 @@ try: # jax>=0.4.26 from jax.sharding import AbstractMesh, get_abstract_mesh except Exception: # pragma: no cover - older JAX versions AbstractMesh = Mesh # type: ignore[misc,assignment] + def get_abstract_mesh(): # type: ignore[dead-code] try: from jax.interpreters.pxla import thread_resources @@ -29,6 +35,8 @@ except Exception: # pragma: no cover - older JAX versions from jax.experimental.maps import thread_resources return thread_resources.env.physical_mesh + + from jaxtyping import PyTree import haliax.tree_util as htu @@ -40,7 +48,6 @@ from .jax_utils import Static, is_in_jit, is_jax_array_like, is_on_mac_metal from .tree_util import hashable_combine, hashable_partition from .util import StringHolderEnum - PhysicalAxisSpec = Union[(str), Sequence[str]] ResourceMapping = Mapping[(str), PhysicalAxisSpec] """Mapping from logical axis names to physical axis names""" @@ -221,9 +228,7 @@ def pspec_for( value = getattr(node, field.name) axis_names = field.metadata.get("axis_names") if field.metadata is not None else None if axis_names is not None and is_jax_array_like(value): - current_sharding = ( - getattr(value, "sharding", None) if preserve_existing_shardings else None - ) + current_sharding = getattr(value, "sharding", None) if preserve_existing_shardings else None if current_sharding is not None: updates[field.name] = None else: @@ -429,8 +434,7 @@ def named_jit( keep_unused: bool = False, backend: Optional[str] = None, inline: Optional[bool] = None, -) -> WrappedCallable[Args, R]: - ... +) -> WrappedCallable[Args, R]: ... @typing.overload @@ -445,8 +449,7 @@ def named_jit( keep_unused: bool = False, backend: Optional[str] = None, inline: Optional[bool] = None, -) -> typing.Callable[[Callable[Args, R]], WrappedCallable[Args, R]]: - ... +) -> typing.Callable[[Callable[Args, R]], WrappedCallable[Args, R]]: ... def named_jit( @@ -530,13 +533,11 @@ def named_jit( @typing.overload -def fsdp(fn: F, parameter_mapping: ResourceMapping, compute_mapping: ResourceMapping) -> F: - ... +def fsdp(fn: F, parameter_mapping: ResourceMapping, compute_mapping: ResourceMapping) -> F: ... @typing.overload -def fsdp(parameter_mapping: ResourceMapping, compute_mapping: ResourceMapping) -> typing.Callable[[F], F]: - ... +def fsdp(parameter_mapping: ResourceMapping, compute_mapping: ResourceMapping) -> typing.Callable[[F], F]: ... def fsdp(*args, **kwargs): diff --git a/src/haliax/quantization.py b/src/haliax/quantization.py index eaa76ee..f531cc8 100644 --- a/src/haliax/quantization.py +++ b/src/haliax/quantization.py @@ -1,3 +1,8 @@ +# Copyright 2025 The Levanter Authors +# +# SPDX-License-Identifier: Apache-2.0 + + # Support for FP8 # Much of this is lifted from FLAX # https://github.com/google/flax/blob/main/flax/linen/fp8_ops.py @@ -24,7 +29,6 @@ from ._src.fp8 import dot_general_with_precision, in_qdq, out_qdq from .axis import Axis from .hof import vmap - T = TypeVar("T") @@ -104,8 +108,7 @@ class DotGeneralOp(Protocol): dimension_numbers, precision: PrecisionLike = None, preferred_element_type: DTypeLike | None = None, - ) -> jnp.ndarray: - ... + ) -> jnp.ndarray: ... @staticmethod def default(): diff --git a/src/haliax/random.py b/src/haliax/random.py index 3ab8ad8..ef203ec 100644 --- a/src/haliax/random.py +++ b/src/haliax/random.py @@ -1,3 +1,8 @@ +# Copyright 2025 The Levanter Authors +# +# SPDX-License-Identifier: Apache-2.0 + + """Wrappers around jax.random functions.""" from typing import Optional diff --git a/src/haliax/specialized_fns.py b/src/haliax/specialized_fns.py index ea5914b..3a58116 100644 --- a/src/haliax/specialized_fns.py +++ b/src/haliax/specialized_fns.py @@ -1,3 +1,8 @@ +# Copyright 2025 The Levanter Authors +# +# SPDX-License-Identifier: Apache-2.0 + + from typing import Optional, Tuple import jax diff --git a/src/haliax/state_dict.py b/src/haliax/state_dict.py index 6863d00..a6c0323 100644 --- a/src/haliax/state_dict.py +++ b/src/haliax/state_dict.py @@ -1,3 +1,8 @@ +# Copyright 2025 The Levanter Authors +# +# SPDX-License-Identifier: Apache-2.0 + + from typing import Optional, TypeVar import equinox @@ -19,7 +24,6 @@ from ._src.state_dict import ( with_prefix, ) - T = TypeVar("T") diff --git a/src/haliax/tree_util.py b/src/haliax/tree_util.py index c72d276..74c443f 100644 --- a/src/haliax/tree_util.py +++ b/src/haliax/tree_util.py @@ -1,3 +1,8 @@ +# Copyright 2025 The Levanter Authors +# +# SPDX-License-Identifier: Apache-2.0 + + import dataclasses import functools from typing import Optional diff --git a/src/haliax/types.py b/src/haliax/types.py index 3606bc0..b6d09f4 100644 --- a/src/haliax/types.py +++ b/src/haliax/types.py @@ -1,3 +1,8 @@ +# Copyright 2025 The Levanter Authors +# +# SPDX-License-Identifier: Apache-2.0 + + from typing import Any, Callable, Literal, Protocol, Tuple, TypeAlias, Union import jax.numpy as jnp @@ -5,7 +10,6 @@ import numpy as np from jax.lax import Precision from jaxtyping import PyTree - DType: TypeAlias = np.dtype try: @@ -14,8 +18,7 @@ except ImportError: # Cribbed from jax.typing, for older versions of JAX class SupportsDType(Protocol): @property - def dtype(self) -> DType: - ... + def dtype(self) -> DType: ... DTypeLike = Union[ str, # like 'float32', 'int32' diff --git a/src/haliax/util.py b/src/haliax/util.py index a175931..33572de 100644 --- a/src/haliax/util.py +++ b/src/haliax/util.py @@ -1,3 +1,8 @@ +# Copyright 2025 The Levanter Authors +# +# SPDX-License-Identifier: Apache-2.0 + + import functools from typing import Sequence, Tuple, TypeAlias, TypeVar, Union @@ -5,7 +10,6 @@ import equinox from haliax.jax_utils import is_jax_array_like - T = TypeVar("T") Unspecified: TypeAlias = type("NotSpecified", (), {}) # type: ignore diff --git a/src/haliax/wrap.py b/src/haliax/wrap.py index fc073ee..8a34679 100644 --- a/src/haliax/wrap.py +++ b/src/haliax/wrap.py @@ -1,3 +1,8 @@ +# Copyright 2025 The Levanter Authors +# +# SPDX-License-Identifier: Apache-2.0 + + from typing import Optional, Protocol import jax @@ -140,13 +145,11 @@ class ReductionFunction(Protocol): axis: Optional[AxisSelection] = None, where: Optional[NamedArray] = None, **kwargs, - ) -> NamedArray: - ... + ) -> NamedArray: ... class SimpleReductionFunction(Protocol): - def __call__(self, array: NamedArray, axis: Optional[AxisSelector] = None, **kwargs) -> NamedArray: - ... + def __call__(self, array: NamedArray, axis: Optional[AxisSelector] = None, **kwargs) -> NamedArray: ... __all__ = [ diff --git a/tests/core_test.py b/tests/core_test.py index 201f16e..a43aefe 100644 --- a/tests/core_test.py +++ b/tests/core_test.py @@ -1,3 +1,8 @@ +# Copyright 2025 The Levanter Authors +# +# SPDX-License-Identifier: Apache-2.0 + + import jax import jax.numpy as jnp import numpy as np @@ -252,9 +257,7 @@ def test_searchsorted(): unsorted = hax.named([5, 1, 3, 7, 4], axis=A) sorter = hax.argsort(unsorted, axis=A) result = hax.searchsorted(unsorted, v, sorter=sorter, side="right") - assert jnp.all( - result.array == jnp.searchsorted(unsorted.array, v.array, sorter=sorter.array, side="right") - ) + assert jnp.all(result.array == jnp.searchsorted(unsorted.array, v.array, sorter=sorter.array, side="right")) assert result.axes == (V,) diff --git a/tests/test_attention.py b/tests/test_attention.py index 11b9e77..e9567ad 100644 --- a/tests/test_attention.py +++ b/tests/test_attention.py @@ -1,3 +1,8 @@ +# Copyright 2025 The Levanter Authors +# +# SPDX-License-Identifier: Apache-2.0 + + import numpy as np from jax.random import PRNGKey diff --git a/tests/test_axis.py b/tests/test_axis.py index bb11f6a..8461421 100644 --- a/tests/test_axis.py +++ b/tests/test_axis.py @@ -1,3 +1,8 @@ +# Copyright 2025 The Levanter Authors +# +# SPDX-License-Identifier: Apache-2.0 + + import pytest import haliax diff --git a/tests/test_conv.py b/tests/test_conv.py index e460412..0926cd4 100644 --- a/tests/test_conv.py +++ b/tests/test_conv.py @@ -1,3 +1,8 @@ +# Copyright 2025 The Levanter Authors +# +# SPDX-License-Identifier: Apache-2.0 + + import equinox as eqx import jax import jax.numpy as jnp diff --git a/tests/test_debug.py b/tests/test_debug.py index 1d7867f..a7fc73a 100644 --- a/tests/test_debug.py +++ b/tests/test_debug.py @@ -1,3 +1,8 @@ +# Copyright 2025 The Levanter Authors +# +# SPDX-License-Identifier: Apache-2.0 + + import equinox as eqx import jax.numpy as jnp import pytest diff --git a/tests/test_dot.py b/tests/test_dot.py index 1406a3e..b38164a 100644 --- a/tests/test_dot.py +++ b/tests/test_dot.py @@ -1,3 +1,8 @@ +# Copyright 2025 The Levanter Authors +# +# SPDX-License-Identifier: Apache-2.0 + + # these test if the rearrange logic works for partial orders import pytest from jax import numpy as jnp diff --git a/tests/test_dtype_typing.py b/tests/test_dtype_typing.py index ef52e58..bc1af31 100644 --- a/tests/test_dtype_typing.py +++ b/tests/test_dtype_typing.py @@ -1,3 +1,8 @@ +# Copyright 2025 The Levanter Authors +# +# SPDX-License-Identifier: Apache-2.0 + + from __future__ import annotations import typing diff --git a/tests/test_einsum.py b/tests/test_einsum.py index c059b10..2e5693b 100644 --- a/tests/test_einsum.py +++ b/tests/test_einsum.py @@ -1,3 +1,8 @@ +# Copyright 2025 The Levanter Authors +# +# SPDX-License-Identifier: Apache-2.0 + + import jax.numpy as jnp import pytest diff --git a/tests/test_field.py b/tests/test_field.py index e5b9cf1..ad95317 100644 --- a/tests/test_field.py +++ b/tests/test_field.py @@ -1,3 +1,8 @@ +# Copyright 2025 The Levanter Authors +# +# SPDX-License-Identifier: Apache-2.0 + + import jax.numpy as jnp import equinox as eqx import pytest diff --git a/tests/test_fp8.py b/tests/test_fp8.py index fec3059..738189c 100644 --- a/tests/test_fp8.py +++ b/tests/test_fp8.py @@ -1,3 +1,8 @@ +# Copyright 2025 The Levanter Authors +# +# SPDX-License-Identifier: Apache-2.0 + + import chex import equinox as eqx import jax.numpy as jnp diff --git a/tests/test_hof.py b/tests/test_hof.py index e0e3415..fa6218b 100644 --- a/tests/test_hof.py +++ b/tests/test_hof.py @@ -1,3 +1,8 @@ +# Copyright 2025 The Levanter Authors +# +# SPDX-License-Identifier: Apache-2.0 + + import equinox as eqx import jax.numpy as jnp from jax.random import PRNGKey diff --git a/tests/test_int8.py b/tests/test_int8.py index 01ff5c1..bb2b85a 100644 --- a/tests/test_int8.py +++ b/tests/test_int8.py @@ -1,3 +1,8 @@ +# Copyright 2025 The Levanter Authors +# +# SPDX-License-Identifier: Apache-2.0 + + import jax.random as jrandom from chex import assert_trees_all_close diff --git a/tests/test_moe_linear.py b/tests/test_moe_linear.py index f8d85e7..d34b76a 100644 --- a/tests/test_moe_linear.py +++ b/tests/test_moe_linear.py @@ -1,3 +1,8 @@ +# Copyright 2025 The Levanter Authors +# +# SPDX-License-Identifier: Apache-2.0 + + import jax import jax.random as jrandom from jax import numpy as jnp diff --git a/tests/test_namedarray_typing.py b/tests/test_namedarray_typing.py index 00a0ee3..805105c 100644 --- a/tests/test_namedarray_typing.py +++ b/tests/test_namedarray_typing.py @@ -1,3 +1,8 @@ +# Copyright 2025 The Levanter Authors +# +# SPDX-License-Identifier: Apache-2.0 + + from __future__ import annotations import typing @@ -42,7 +47,7 @@ def test_namedarray_runtime_check(): Embed = Axis("embed", 3) arr = NamedArray(jnp.zeros((Batch.size, Embed.size)), (Batch, Embed)) assert arr.matches_axes(NamedArray["batch", "embed"]) - assert arr.matches_axes(Named[NamedArray,"batch embed"]) # type: ignore + assert arr.matches_axes(Named[NamedArray, "batch embed"]) # type: ignore assert arr.matches_axes(NamedArray["batch embed ..."]) assert arr.matches_axes(NamedArray[{"batch", "embed"}]) assert arr.matches_axes(NamedArray[{"batch", "embed", ...}]) diff --git a/tests/test_nn.py b/tests/test_nn.py index a53381c..2915898 100644 --- a/tests/test_nn.py +++ b/tests/test_nn.py @@ -1,3 +1,8 @@ +# Copyright 2025 The Levanter Authors +# +# SPDX-License-Identifier: Apache-2.0 + + from typing import Callable import equinox as eqx diff --git a/tests/test_ops.py b/tests/test_ops.py index 4547766..a7a561d 100644 --- a/tests/test_ops.py +++ b/tests/test_ops.py @@ -1,3 +1,8 @@ +# Copyright 2025 The Levanter Authors +# +# SPDX-License-Identifier: Apache-2.0 + + from typing import Callable import typing diff --git a/tests/test_parsing.py b/tests/test_parsing.py index ba9380b..24b4f42 100644 --- a/tests/test_parsing.py +++ b/tests/test_parsing.py @@ -1,3 +1,8 @@ +# Copyright 2025 The Levanter Authors +# +# SPDX-License-Identifier: Apache-2.0 + + import pytest from haliax._src.parsing import parse_einsum, parse_rearrangement diff --git a/tests/test_partitioning.py b/tests/test_partitioning.py index ef4026b..4f8ceb2 100644 --- a/tests/test_partitioning.py +++ b/tests/test_partitioning.py @@ -1,3 +1,8 @@ +# Copyright 2025 The Levanter Authors +# +# SPDX-License-Identifier: Apache-2.0 + + import equinox as eqx import jax import jax.numpy as jnp @@ -302,7 +307,7 @@ def test_named_jit_with_donation_nested_pytrees(): def test_jit_lower_doesnt_blow_up(): - with ((axis_mapping(resource_map))): + with axis_mapping(resource_map): class MyModule(eqx.Module): array: jnp.ndarray @@ -330,8 +335,9 @@ def test_cross_device_sharding(): with jax.default_device(cpu_device): x = hax.ones((Dim1, Dim2)) - with axis_mapping(resource_map), Mesh( - np.array(jax.devices()).reshape(-1, 1), (ResourceAxis.DATA, ResourceAxis.MODEL) + with ( + axis_mapping(resource_map), + Mesh(np.array(jax.devices()).reshape(-1, 1), (ResourceAxis.DATA, ResourceAxis.MODEL)), ): x = hax.shard(x, resource_map) z = hax.ones((Dim1, Dim3)) diff --git a/tests/test_pool.py b/tests/test_pool.py index f086247..4c883e5 100644 --- a/tests/test_pool.py +++ b/tests/test_pool.py @@ -1,3 +1,8 @@ +# Copyright 2025 The Levanter Authors +# +# SPDX-License-Identifier: Apache-2.0 + + import equinox as eqx import jax import jax.numpy as jnp @@ -6,7 +11,6 @@ import haliax import haliax as hax from haliax.nn.pool import max_pool, mean_pool - # Tests largely cribbed from equinox diff --git a/tests/test_random.py b/tests/test_random.py index 925934d..4273e33 100644 --- a/tests/test_random.py +++ b/tests/test_random.py @@ -1,3 +1,8 @@ +# Copyright 2025 The Levanter Authors +# +# SPDX-License-Identifier: Apache-2.0 + + from typing import Callable import jax @@ -7,7 +12,6 @@ from jaxtyping import PRNGKeyArray import haliax as hax from haliax.axis import axis_spec_to_shape_dict - Height = hax.Axis("Height", 4) Width = hax.Axis("Width", 8) Digit = hax.Axis("Digit", 10) diff --git a/tests/test_rearrange.py b/tests/test_rearrange.py index 2dd2d81..1c4dd37 100644 --- a/tests/test_rearrange.py +++ b/tests/test_rearrange.py @@ -1,3 +1,8 @@ +# Copyright 2025 The Levanter Authors +# +# SPDX-License-Identifier: Apache-2.0 + + import pytest from jax.random import PRNGKey @@ -5,7 +10,6 @@ import haliax as hax from haliax import Axis from haliax._src.rearrange import einops_rearrange - # some axes H, W, C, D, B = hax.make_axes(H=6, W=4, C=3, D=2, B=5) Q = hax.Axis("Q", B.size * H.size) diff --git a/tests/test_scan.py b/tests/test_scan.py index 05ac7a0..6503842 100644 --- a/tests/test_scan.py +++ b/tests/test_scan.py @@ -1,3 +1,8 @@ +# Copyright 2025 The Levanter Authors +# +# SPDX-License-Identifier: Apache-2.0 + + import equinox as eqx import jax import pytest @@ -734,6 +739,7 @@ def test_vmap_via_blockseq_multi_args(): def test_vmap_via_consistency(): """Test that vmap_via gives the same results as vmap for Stacked.""" + class Module(eqx.Module): w: hax.NamedArray diff --git a/tests/test_scatter_gather.py b/tests/test_scatter_gather.py index 7ab0684..6d7d178 100644 --- a/tests/test_scatter_gather.py +++ b/tests/test_scatter_gather.py @@ -1,9 +1,13 @@ +# Copyright 2025 The Levanter Authors +# +# SPDX-License-Identifier: Apache-2.0 + + import jax.numpy as jnp import haliax as hax from haliax import Axis, dslice - # ----------------------------------------------------------------------------- # Helper for reference via take_along_axis # ----------------------------------------------------------------------------- diff --git a/tests/test_specialized_fns.py b/tests/test_specialized_fns.py index 3b13bef..4996e23 100644 --- a/tests/test_specialized_fns.py +++ b/tests/test_specialized_fns.py @@ -1,3 +1,8 @@ +# Copyright 2025 The Levanter Authors +# +# SPDX-License-Identifier: Apache-2.0 + + import jax import jax.numpy as jnp diff --git a/tests/test_state_dict.py b/tests/test_state_dict.py index 2dda82a..c72df79 100644 --- a/tests/test_state_dict.py +++ b/tests/test_state_dict.py @@ -1,3 +1,8 @@ +# Copyright 2025 The Levanter Authors +# +# SPDX-License-Identifier: Apache-2.0 + + import dataclasses from typing import Any diff --git a/tests/test_tree_util.py b/tests/test_tree_util.py index 91d911e..a76c3c9 100644 --- a/tests/test_tree_util.py +++ b/tests/test_tree_util.py @@ -1,3 +1,8 @@ +# Copyright 2025 The Levanter Authors +# +# SPDX-License-Identifier: Apache-2.0 + + import dataclasses import equinox as eqx diff --git a/tests/test_utils.py b/tests/test_utils.py index 087b340..2e6c396 100644 --- a/tests/test_utils.py +++ b/tests/test_utils.py @@ -1,9 +1,13 @@ +# Copyright 2025 The Levanter Authors +# +# SPDX-License-Identifier: Apache-2.0 + + from typing import TypeVar import jax import pytest - T = TypeVar("T") diff --git a/tests/test_visualize_sharding.py b/tests/test_visualize_sharding.py index 18f6c63..a8f11a8 100644 --- a/tests/test_visualize_sharding.py +++ b/tests/test_visualize_sharding.py @@ -1,3 +1,8 @@ +# Copyright 2025 The Levanter Authors +# +# SPDX-License-Identifier: Apache-2.0 + + import numpy as np import jax import jax.numpy as jnp commit f302d29f5f1864616ec4043fa7af8344e04cb9b7 Date: 2025-09-15T11:46:40-07:00 Add named nonzero operation (#209) diff --git a/.agents/projects/api_parity.md b/.agents/projects/api_parity.md index 19e3cf1..5df6e89 100644 --- a/.agents/projects/api_parity.md +++ b/.agents/projects/api_parity.md @@ -107,7 +107,7 @@ APIs that don't translate well to named tensors are intentionally omitted here. - [x] `nanstd` - [x] `nansum` - [x] `nanvar` -- [ ] `nonzero` +- [x] `nonzero` - [ ] `ogrid` - [x] `packbits` - [ ] `partition` diff --git a/docs/api.md b/docs/api.md index a0dd228..17156cc 100644 --- a/docs/api.md +++ b/docs/api.md @@ -283,6 +283,7 @@ These are all more or less directly from JAX's NumPy API. ::: haliax.pad ::: haliax.searchsorted ::: haliax.top_k +::: haliax.nonzero ::: haliax.trace ::: haliax.tril ::: haliax.triu diff --git a/src/haliax/__init__.py b/src/haliax/__init__.py index 8052b99..c44c4af 100644 --- a/src/haliax/__init__.py +++ b/src/haliax/__init__.py @@ -84,6 +84,7 @@ from .ops import ( trace, tril, triu, + nonzero, unique, unique_values, unique_counts, @@ -1199,6 +1200,7 @@ __all__ = [ "map", "vmap", "trace", + "nonzero", "where", "unique", "unique_values", diff --git a/src/haliax/ops.py b/src/haliax/ops.py index e64a34a..993b7cc 100644 --- a/src/haliax/ops.py +++ b/src/haliax/ops.py @@ -108,6 +108,30 @@ def where( return NamedArray(raw, condition.axes) +def nonzero(array: NamedArray, *, size: Axis, fill_value: int = 0) -> tuple[NamedArray, ...]: + """Like :func:`jax.numpy.nonzero`, but with named axes. + + Args: + array: The input array to test for nonzero values. Must be a :class:`NamedArray`. + size: Axis specifying the size of the output axis. This is required because + JAX requires the size of the result at tracing time. + fill_value: Value used to fill the output when fewer than ``size`` elements are + nonzero. Defaults to ``0``. + + Returns: + A tuple of :class:`NamedArray` objects, one for each axis of ``array``. Each + returned array has ``size`` as its only axis and contains the indices of the + nonzero elements along the corresponding input axis. + """ + + if not isinstance(array, NamedArray): + raise ValueError("array must be a NamedArray") + + return tuple( + NamedArray(idx, (size,)) for idx in jnp.nonzero(array.array, size=size.size, fill_value=fill_value) + ) + + def clip(array: NamedOrNumeric, a_min: NamedOrNumeric, a_max: NamedOrNumeric) -> NamedArray: """Like jnp.clip, but with named axes. This version currently only accepts the three argument form.""" (array, a_min, a_max), axes = broadcast_arrays_and_return_axes(array, a_min, a_max) diff --git a/tests/test_ops.py b/tests/test_ops.py index a7a561d..f6dd0cc 100644 --- a/tests/test_ops.py +++ b/tests/test_ops.py @@ -161,6 +161,29 @@ def test_where(use_jit): assert jnp.all(unnamed_8 == named8.array) +@pytest.mark.parametrize("use_jit", [False, True]) +def test_nonzero(use_jit): + Height = Axis("Height", 3) + Width = Axis("Width", 4) + + data = jnp.array([[0, 1, 0, 2], [3, 0, 4, 0], [0, 0, 5, 6]]) + named = hax.named(data, (Height, Width)) + + Nonzero = Axis("Nonzero", Height.size * Width.size) + + hax_nonzero: Callable = hax.nonzero + if use_jit: + hax_nonzero = hax.named_jit(hax_nonzero) + + i, j = hax_nonzero(named, size=Nonzero, fill_value=-1) + ui, uj = jnp.nonzero(data, size=Nonzero.size, fill_value=-1) + + assert i.axes == (Nonzero,) + assert j.axes == (Nonzero,) + assert jnp.all(i.array == ui) + assert jnp.all(j.array == uj) + + def test_clip(): Height = Axis("Height", 10) Width = Axis("Width", 3) commit 1fb23ee2591b6d4a4ca3189c99d5b5a3af711261 Date: 2025-09-15T17:31:27-07:00 Clarify FFT axis examples and sequence handling (#211) diff --git a/.agents/projects/api_parity.md b/.agents/projects/api_parity.md index 5df6e89..8222729 100644 --- a/.agents/projects/api_parity.md +++ b/.agents/projects/api_parity.md @@ -161,24 +161,19 @@ APIs that don't translate well to named tensors are intentionally omitted here. - [ ] `vstack` ## fft -- [ ] `fft` -- [ ] `fft2` -- [ ] `fftfreq` -- [ ] `fftn` -- [ ] `fftshift` -- [ ] `hfft` -- [ ] `ifft` -- [ ] `ifft2` -- [ ] `ifftn` -- [ ] `ifftshift` -- [ ] `ihfft` -- [ ] `irfft` -- [ ] `irfft2` -- [ ] `irfftn` -- [ ] `rfft` -- [ ] `rfft2` -- [ ] `rfftfreq` -- [ ] `rfftn` +Multi-dimensional transforms like `fftn` or `rfft2` are handled by passing a +mapping of axes to :func:`haliax.fft` and friends. + +- [x] `fft` +- [x] `fftfreq` +- [x] `fftshift` +- [x] `hfft` +- [x] `ifft` +- [x] `ifftshift` +- [x] `ihfft` +- [x] `irfft` +- [x] `rfft` +- [x] `rfftfreq` ## linalg - [ ] `cholesky` diff --git a/.playbooks/wrap-non-named.md b/.playbooks/wrap-non-named.md index 756fd0b..eef61c1 100644 --- a/.playbooks/wrap-non-named.md +++ b/.playbooks/wrap-non-named.md @@ -45,6 +45,14 @@ def sum(a, axis=None): ## Harder Cases Some functions need bespoke handling. For example `jnp.unique` returns several arrays and may change shape unpredictably. There is no generic helper, so you will need to manually map between `NamedArray` axes and the outputs. Use the lower level utilities in `haliax.wrap` for broadcasting and axis lookup. +## Axis-aware functions +For JAX functions that accept an ``axis`` or ``axes`` argument, prefer a single +``axis`` parameter of type :class:`haliax.AxisSelection` that also accepts an +ordered mapping of axes to sizes. A mapping dispatches to the corresponding +``n``‑dimensional JAX primitive (e.g. :func:`jax.numpy.fft.fftn`) and allows +resizing the transformed axes by specifying integer lengths or ``Axis`` +instances. + ## Testing Add tests to ensure that named and unnamed calls produce the same results and that axis names are preserved or removed correctly. diff --git a/docs/api.md b/docs/api.md index 17156cc..8af4663 100644 --- a/docs/api.md +++ b/docs/api.md @@ -289,6 +289,49 @@ These are all more or less directly from JAX's NumPy API. ::: haliax.triu ::: haliax.where +### FFT + +All FFT helpers accept an ``axis`` argument which may be a single axis, its +name, or an ordered mapping from axes to output sizes. Passing a mapping +dispatches to the ``n``‑dimensional variants in :mod:`jax.numpy.fft`. + +For example:: + + import jax.numpy as jnp + import haliax as hax + + T = hax.Axis("time", 8) + signal = hax.arange(T, dtype=jnp.float32) + + # operate along a single axis specified by name + hax.fft(signal, axis="time") + + # resize by passing an Axis object + hax.fft(signal, axis=hax.Axis("time", 16)) + + X, Y = hax.make_axes(X=4, Y=6) + image = hax.arange((X, Y), dtype=jnp.float32) + + # transform across several axes in order by passing a sequence + hax.fft(image, axis=("X", "Y")) + + # selectively resize axes by providing a mapping + hax.fft(image, axis={"X": None, "Y": hax.Axis("Y", 10)}) + + # mappings can cover just a subset of axes when only partial resizing is needed + hax.fft(image, axis={"Y": 10}) + +::: haliax.fft +::: haliax.ifft +::: haliax.hfft +::: haliax.ihfft +::: haliax.rfft +::: haliax.irfft +::: haliax.fftfreq +::: haliax.rfftfreq +::: haliax.fftshift +::: haliax.ifftshift + ## Named Array Reference diff --git a/src/haliax/__init__.py b/src/haliax/__init__.py index c44c4af..b0fab19 100644 --- a/src/haliax/__init__.py +++ b/src/haliax/__init__.py @@ -96,6 +96,18 @@ from .ops import ( bincount, where, ) +from .fft import ( + fft, + fftfreq, + fftshift, + hfft, + ifft, + ifftshift, + ihfft, + irfft, + rfft, + rfftfreq, +) from .partitioning import auto_sharded, axis_mapping, fsdp, named_jit, shard, shard_with_axis_mapping from .specialized_fns import top_k from .types import Scalar @@ -1214,6 +1226,16 @@ __all__ = [ "clip", "tril", "triu", + "fft", + "ifft", + "hfft", + "ihfft", + "rfft", + "irfft", + "fftfreq", + "rfftfreq", + "fftshift", + "ifftshift", "add", "arctan2", "bitwise_and", diff --git a/src/haliax/fft.py b/src/haliax/fft.py new file mode 100644 index 0000000..34d45a0 --- /dev/null +++ b/src/haliax/fft.py @@ -0,0 +1,365 @@ +"""Named wrappers around :mod:`jax.numpy.fft`. + +These functions mirror the behaviour of their :mod:`jax.numpy.fft` counterparts +while accepting named axes. Instead of separate ``fftn``/``fft2`` variants we +provide a single ``fft`` family of functions whose ``axis`` argument controls +which axes are transformed. + +The ``axis`` parameter can be one of: + +* ``None`` – operate on the last axis. +* ``str`` – name of an existing axis in the input. +* :class:`~haliax.Axis` – specifies both the axis to transform (by name) and the + desired FFT length. The output axis is replaced by the provided ``Axis``. +* ``dict`` – mapping from axis selectors (names or ``Axis`` objects) to optional + sizes. A value of ``None`` uses the existing axis length. The mapping order + determines the order of transforms and dispatches to the ``n``‑dimensional + variants in :mod:`jax.numpy.fft`. + +Example +------- + +```python +X, Y = hax.make_axes(X=4, Y=6) +arr = hax.arange((X, Y)) + +# 1D transform along ``Y`` +hax.fft(arr, axis="Y") + +# 2D transform across both axes +hax.fft(arr, axis={"X": None, "Y": None}) + +# Resize the ``Y`` axis before transforming +hax.fft(arr, axis={"Y": Axis("Y", 8)}) +``` +""" + +from __future__ import annotations + +from typing import Mapping, MutableSequence, Sequence + +import jax.numpy.fft as jfft + +from .axis import Axis, AxisSelector, AxisSelection +from .core import NamedArray + + +AxisSizeLike = int | Axis | None +AxisMapping = Mapping[AxisSelector, AxisSizeLike] + + +def _single_axis(a: NamedArray, axis: AxisSelector | None): + if axis is None: + idx = a.ndim - 1 + ax = a.axes[idx] + n = None + elif isinstance(axis, Axis): + idx = a.axis_indices(axis.name) + if idx is None: + raise ValueError(f"Axis {axis} not found in {a.axes}") + ax = axis + n = axis.size + else: + idx = a.axis_indices(axis) + if idx is None: + raise ValueError(f"Axis {axis} not found in {a.axes}") + ax = a.axes[idx] + n = None + return idx, ax, n + + +def _multi_axis(a: NamedArray, axis: AxisMapping): + axes_idx: MutableSequence[int] = [] + sizes: MutableSequence[int] = [] + new_axes = list(a.axes) + for key, val in axis.items(): + idx = a.axis_indices(key) + if idx is None: + raise ValueError(f"Axis {key} not found in {a.axes}") + ax = a.axes[idx] + if isinstance(val, Axis): + size = val.size + new_axes[idx] = val + elif val is None: + size = ax.size + else: + size = int(val) + new_axes[idx] = ax.resize(size) + axes_idx.append(idx) + sizes.append(size) + return list(axes_idx), list(sizes), new_axes + + +def fft( + a: NamedArray, + axis: AxisSelector | Sequence[AxisSelector] | AxisMapping | None = None, + norm: str | None = None, +) -> NamedArray: + """Named version of :func:`jax.numpy.fft.fft`. + + See module level documentation for the behaviour of the ``axis`` argument. + """ + + if isinstance(axis, Mapping): + axes_idx, sizes, new_axes = _multi_axis(a, axis) + out = jfft.fftn(a.array, s=tuple(sizes), axes=tuple(axes_idx), norm=norm) + return NamedArray(out, tuple(new_axes)) + elif isinstance(axis, Sequence) and not isinstance(axis, (str, Axis)): + axes_idx, sizes, new_axes = _multi_axis(a, {ax: None for ax in axis}) + out = jfft.fftn(a.array, s=tuple(sizes), axes=tuple(axes_idx), norm=norm) + return NamedArray(out, tuple(new_axes)) + else: + idx, new_axis, n = _single_axis(a, axis) # type: ignore[arg-type] + out = jfft.fft(a.array, n=n, axis=idx, norm=norm) + axes = list(a.axes) + axes[idx] = new_axis + return NamedArray(out, tuple(axes)) + + +def ifft( + a: NamedArray, + axis: AxisSelector | Sequence[AxisSelector] | AxisMapping | None = None, + norm: str | None = None, +) -> NamedArray: + """Named version of :func:`jax.numpy.fft.ifft`.""" + + if isinstance(axis, Mapping): + axes_idx, sizes, new_axes = _multi_axis(a, axis) + out = jfft.ifftn(a.array, s=tuple(sizes), axes=tuple(axes_idx), norm=norm) + return NamedArray(out, tuple(new_axes)) + elif isinstance(axis, Sequence) and not isinstance(axis, (str, Axis)): + axes_idx, sizes, new_axes = _multi_axis(a, {ax: None for ax in axis}) + out = jfft.ifftn(a.array, s=tuple(sizes), axes=tuple(axes_idx), norm=norm) + return NamedArray(out, tuple(new_axes)) + else: + idx, new_axis, n = _single_axis(a, axis) # type: ignore[arg-type] + out = jfft.ifft(a.array, n=n, axis=idx, norm=norm) + axes = list(a.axes) + axes[idx] = new_axis + return NamedArray(out, tuple(axes)) + + +def rfft( + a: NamedArray, + axis: AxisSelector | Sequence[AxisSelector] | AxisMapping | None = None, + norm: str | None = None, +) -> NamedArray: + """Named version of :func:`jax.numpy.fft.rfft`.""" + + if isinstance(axis, Mapping): + axes_idx, sizes, new_axes = _multi_axis(a, axis) + out = jfft.rfftn(a.array, s=tuple(sizes), axes=tuple(axes_idx), norm=norm) + last_idx = axes_idx[-1] + last_in = sizes[-1] + new_axes[last_idx] = new_axes[last_idx].resize(last_in // 2 + 1) + return NamedArray(out, tuple(new_axes)) + elif isinstance(axis, Sequence) and not isinstance(axis, (str, Axis)): + axes_idx, sizes, new_axes = _multi_axis(a, {ax: None for ax in axis}) + out = jfft.rfftn(a.array, s=tuple(sizes), axes=tuple(axes_idx), norm=norm) + last_idx = axes_idx[-1] + last_in = sizes[-1] + new_axes[last_idx] = new_axes[last_idx].resize(last_in // 2 + 1) + return NamedArray(out, tuple(new_axes)) + else: + idx, ax, n = _single_axis(a, axis) # type: ignore[arg-type] + out = jfft.rfft(a.array, n=n, axis=idx, norm=norm) + length = n if n is not None else ax.size + new_axis = ax.resize(length // 2 + 1) + axes = list(a.axes) + axes[idx] = new_axis + return NamedArray(out, tuple(axes)) + + +def _single_axis_irfft(a: NamedArray, axis: AxisSelector | None): + if axis is None: + idx = a.ndim - 1 + in_ax = a.axes[idx] + length = (in_ax.size - 1) * 2 + out_ax = in_ax.resize(length) + n = None + elif isinstance(axis, Axis): + idx = a.axis_indices(axis.name) + if idx is None: + raise ValueError(f"Axis {axis} not found in {a.axes}") + out_ax = axis + n = axis.size + else: + idx = a.axis_indices(axis) + if idx is None: + raise ValueError(f"Axis {axis} not found in {a.axes}") + in_ax = a.axes[idx] + length = (in_ax.size - 1) * 2 + out_ax = in_ax.resize(length) + n = None + return idx, out_ax, n + + +def _multi_axis_irfft(a: NamedArray, axis: AxisMapping): + axes_idx: MutableSequence[int] = [] + sizes: MutableSequence[int] = [] + new_axes = list(a.axes) + items = list(axis.items()) + for i, (key, val) in enumerate(items): + idx = a.axis_indices(key) + if idx is None: + raise ValueError(f"Axis {key} not found in {a.axes}") + ax = a.axes[idx] + if isinstance(val, Axis): + size = val.size + new_axes[idx] = val + elif val is None: + if i == len(items) - 1: + size = (ax.size - 1) * 2 + else: + size = ax.size + new_axes[idx] = ax.resize(size) + else: + size = int(val) + new_axes[idx] = ax.resize(size) + axes_idx.append(idx) + sizes.append(size) + return list(axes_idx), list(sizes), new_axes + + +def irfft( + a: NamedArray, + axis: AxisSelector | Sequence[AxisSelector] | AxisMapping | None = None, + norm: str | None = None, +) -> NamedArray: + """Named version of :func:`jax.numpy.fft.irfft`.""" + + if isinstance(axis, Mapping): + axes_idx, sizes, new_axes = _multi_axis_irfft(a, axis) + out = jfft.irfftn(a.array, s=tuple(sizes), axes=tuple(axes_idx), norm=norm) + return NamedArray(out, tuple(new_axes)) + elif isinstance(axis, Sequence) and not isinstance(axis, (str, Axis)): + axes_idx, sizes, new_axes = _multi_axis_irfft(a, {ax: None for ax in axis}) + out = jfft.irfftn(a.array, s=tuple(sizes), axes=tuple(axes_idx), norm=norm) + return NamedArray(out, tuple(new_axes)) + else: + idx, out_ax, n = _single_axis_irfft(a, axis) # type: ignore[arg-type] + out = jfft.irfft(a.array, n=n, axis=idx, norm=norm) + axes = list(a.axes) + axes[idx] = out_ax + return NamedArray(out, tuple(axes)) + + +def hfft( + a: NamedArray, + axis: AxisSelector | Sequence[AxisSelector] | AxisMapping | None = None, + norm: str | None = None, +) -> NamedArray: + """Named version of :func:`jax.numpy.fft.hfft`. + + Only a single axis is supported; passing a dictionary with more than one + entry will raise an error. + """ + + if isinstance(axis, Mapping): + if len(axis) != 1: + raise ValueError("hfft only supports a single axis") + key, val = next(iter(axis.items())) + if isinstance(val, Axis): + axis = val + elif val is None: + axis = key + else: + name = key.name if isinstance(key, Axis) else key + axis = Axis(name, int(val)) + + idx, out_ax, n = _single_axis_irfft(a, axis) # type: ignore[arg-type] + out = jfft.hfft(a.array, n=n, axis=idx, norm=norm) + axes = list(a.axes) + axes[idx] = out_ax + return NamedArray(out, tuple(axes)) + + +def ihfft( + a: NamedArray, + axis: AxisSelector | Sequence[AxisSelector] | AxisMapping | None = None, + norm: str | None = None, +) -> NamedArray: + """Named version of :func:`jax.numpy.fft.ihfft`. + + Only a single axis is supported; passing a dictionary with more than one + entry will raise an error. + """ + + if isinstance(axis, Mapping): + if len(axis) != 1: + raise ValueError("ihfft only supports a single axis") + key, val = next(iter(axis.items())) + if isinstance(val, Axis): + axis = val + elif val is None: + axis = key + else: + name = key.name if isinstance(key, Axis) else key + axis = Axis(name, int(val)) + + idx, ax, n = _single_axis(a, axis) # type: ignore[arg-type] + out = jfft.ihfft(a.array, n=n, axis=idx, norm=norm) + length = n if n is not None else ax.size // 2 + 1 + new_axis = ax.resize(length) + axes = list(a.axes) + axes[idx] = new_axis + return NamedArray(out, tuple(axes)) + + +def fftshift(x: NamedArray, axes: AxisSelection | None = None) -> NamedArray: + """Named version of :func:`jax.numpy.fft.fftshift`.""" + + if axes is None: + out = jfft.fftshift(x.array) + else: + idxs = x.axis_indices(axes) + if isinstance(idxs, tuple): + if any(i is None for i in idxs): + raise ValueError(f"Axis {axes} not found in {x.axes}") + elif idxs is None: + raise ValueError(f"Axis {axes} not found in {x.axes}") + out = jfft.fftshift(x.array, axes=idxs) + return NamedArray(out, x.axes) + + +def ifftshift(x: NamedArray, axes: AxisSelection | None = None) -> NamedArray: + """Named version of :func:`jax.numpy.fft.ifftshift`.""" + + if axes is None: + out = jfft.ifftshift(x.array) + else: + idxs = x.axis_indices(axes) + if isinstance(idxs, tuple): + if any(i is None for i in idxs): + raise ValueError(f"Axis {axes} not found in {x.axes}") + elif idxs is None: + raise ValueError(f"Axis {axes} not found in {x.axes}") + out = jfft.ifftshift(x.array, axes=idxs) + return NamedArray(out, x.axes) + + +def fftfreq(axis: Axis, d: float = 1.0) -> NamedArray: + """Named version of :func:`jax.numpy.fft.fftfreq`.""" + + return NamedArray(jfft.fftfreq(axis.size, d), (axis,)) + + +def rfftfreq(axis: Axis, d: float = 1.0) -> NamedArray: + """Named version of :func:`jax.numpy.fft.rfftfreq`.""" + + new_axis = axis.resize(axis.size // 2 + 1) + return NamedArray(jfft.rfftfreq(axis.size, d), (new_axis,)) + + +__all__ = [ + "fft", + "ifft", + "rfft", + "irfft", + "hfft", + "ihfft", + "fftfreq", + "rfftfreq", + "fftshift", + "ifftshift", +] diff --git a/tests/test_fft.py b/tests/test_fft.py new file mode 100644 index 0000000..de04407 --- /dev/null +++ b/tests/test_fft.py @@ -0,0 +1,81 @@ +import jax.numpy as jnp +import jax.numpy.fft as jfft + +import haliax as hax +from haliax import Axis + + +def test_fft_axis_options(): + N = Axis("n", 8) + x = hax.arange(N, dtype=jnp.float32) + + # string axis + assert jnp.allclose(hax.fft(x, axis="n").array, jfft.fft(x.array)) + + # Axis object with resize + N2 = Axis("n", 16) + f = hax.fft(x, axis=N2) + assert f.axes[0] == N2 + assert jnp.allclose(f.array, jfft.fft(x.array, n=16)) + + r = hax.rfft(x) + assert r.axes[0].size == 5 + assert jnp.allclose(r.array, jfft.rfft(x.array)) + + ir = hax.irfft(r) + assert ir.axes[0].size == 8 + assert jnp.allclose(ir.array, jfft.irfft(jfft.rfft(x.array))) + + h = hax.hfft(r) + assert h.axes[0].size == 8 + assert jnp.allclose(h.array, jfft.hfft(jfft.rfft(x.array))) + + ih = hax.ihfft(x) + assert ih.axes[0].size == 5 + assert jnp.allclose(ih.array, jfft.ihfft(x.array)) + + +def test_fft_freq_and_shift(): + N = Axis("n", 8) + x = hax.arange(N) + + f = hax.fftfreq(N) + assert f.axes == (N,) + assert jnp.allclose(f.array, jfft.fftfreq(8)) + + rf = hax.rfftfreq(N) + assert rf.axes[0].size == 5 + assert jnp.allclose(rf.array, jfft.rfftfreq(8)) + + shifted = hax.fftshift(x) + assert jnp.allclose(shifted.array, jfft.fftshift(x.array)) + unshifted = hax.ifftshift(shifted) + assert jnp.allclose(unshifted.array, x.array) + + +def test_fft_multi_axis(): + X = Axis("x", 4) + Y = Axis("y", 6) + Z = Axis("z", 8) + arr = hax.arange((X, Y, Z), dtype=jnp.float32) + + f = hax.fft(arr, axis={"y": None, "z": None}) + assert jnp.allclose(f.array, jfft.fftn(arr.array, axes=(1, 2))) + + f_seq = hax.fft(arr, axis=("y", "z")) + assert jnp.allclose(f_seq.array, jfft.fftn(arr.array, axes=(1, 2))) + assert f_seq.axes == f.axes + + rf = hax.rfft(arr, axis={"y": None, "z": None}) + assert rf.axes[2].size == 5 + assert jnp.allclose(rf.array, jfft.rfftn(arr.array, axes=(1, 2))) + + irf = hax.irfft(rf, axis={"y": None, "z": Z}) + assert jnp.allclose( + irf.array, jfft.irfftn(jfft.rfftn(arr.array, axes=(1, 2)), s=(Y.size, Z.size), axes=(1, 2)) + ) + + # resizing via dict values + f2 = hax.fft(arr, axis={"y": 4, "z": None}) + assert f2.axes[1].size == 4 + assert jnp.allclose(f2.array, jfft.fftn(arr.array, s=(4, 8), axes=(1, 2))) commit ec70acb495442560aded5aca6d7d3e30459716c5 Date: 2025-09-15T17:54:14-07:00 Expand primer coverage of axis helper types (#212) diff --git a/docs/api.md b/docs/api.md index 8af4663..9cc9783 100644 --- a/docs/api.md +++ b/docs/api.md @@ -6,19 +6,89 @@ arrays (see [haliax.zeros][] and [haliax.ones][]) as well as things like reducti ## Axis Types -There are four types related to [haliax.Axis][] you will see in the API reference: - -* [haliax.Axis][]: This is the main type for representing axes. It is a dataclass with a name and a size. -* [haliax.AxisSelector][]: This is a type alias for either [haliax.Axis][] or a `str`. This type is used when we want - one axis and the size can be inferred from the inputs. -* [haliax.AxisSpec][]: This is a type alias for either [haliax.Axis][] or a tuple/list of [haliax.Axis][]. This type is - used when we want one or more axes and the sizes cannot be inferred from the inputs, for instance when creating arrays. -* [haliax.AxisSelection][]: This is a type alias for either [haliax.AxisSelector][] or a tuple/list of [haliax.AxisSelector][]. - This type is used when we want one or more axes and the sizes can be inferred from the inputs, for instance when - reducing an array. - -Occasionally, an axis size can be inferred in some circumstances but not others. When this happens, we still use -`AxisSelector` but document the behavior in the docstring. A RuntimeError will be raised if the size cannot be inferred. +If you already speak NumPy or `jax.numpy`, think of Haliax as swapping positional axes (`axis=0`) for named axes +(`axis="batch"`). The type hints in this section describe the different ways those named axes can be provided to the API. +They appear throughout the documentation and in signatures so that you can quickly tell which forms are accepted. + +| Name | Accepts | When to use it | Example | +| --- | --- | --- | --- | +| [`Axis`][haliax.Axis] | `Axis(name: str, size: int)` | Define a named dimension with an explicit size | `Batch = Axis("batch", 32)` | +| [`AxisSelector`][haliax.AxisSelector] | `Axis` or `str` | Refer to an existing axis whose size can be inferred from the arrays you pass in | `x.sum(axis="batch")` | +| [`AxisSpec`][haliax.AxisSpec] | `dict[str, int]`, `Axis`, or a sequence of `Axis` objects | Create or reshape arrays when the axis sizes must be provided | `hax.zeros((Batch, Feature))` | +| [`AxisSelection`][haliax.AxisSelection] | `dict[str, int | None]`, `AxisSpec`, or a sequence of `AxisSelector` values | Work with one or more existing axes (reductions, indexing helpers, flattening, …) | `x.sum(axis=("batch", Feature))` | + +### Axis + +An [`Axis`][haliax.Axis] is the fundamental building block: it is a tiny dataclass that stores a name and a size. You can +construct one directly or use [`haliax.make_axes`][] to generate several at a time. + +```python +import haliax as hax +from haliax import Axis + +Batch = Axis("batch", 32) +Feature = Axis("feature", 128) +x = hax.ones((Batch, Feature)) +print(Batch.name, Batch.size) +``` + +Using `Axis` objects keeps array creation explicit and gives reusable handles you can share between different tensors. +Equality compares both the name and size so you get guardrails when wiring pieces together. + +### AxisSelector + +An [`AxisSelector`][haliax.AxisSelector] accepts either an `Axis` object or just the axis name as a string. It is used +whenever a function can read the axis size from one of its arguments. This mirrors how NumPy lets you pass `axis=0` when +reducing an array: + +```python +total = x.sum(axis=Batch) # using the Axis handle +same_total = x.sum(axis="batch") # using only the name +``` + +Strings are convenient when you only care about the name, but `Axis` objects still work so you can keep using the handles +you created earlier. If an axis with that name is missing, Haliax raises a `ValueError`. + +### AxisSpec + +An [`AxisSpec`][haliax.AxisSpec] is used when Haliax needs full size information to create or reshape an array. You can +provide a shape dictionary (sometimes called a "shape dict") that maps names to sizes, or a sequence of `Axis` objects: + +```python +shape = {"batch": 32, "feature": 128} +y = hax.zeros(shape) # using a shape dict +z = hax.zeros((Batch, Feature)) # using the Axis objects directly +``` + +Both forms describe the same layout. Python dictionaries preserve insertion order, so the ordering in a shape dict matches +the order that axes appear in the array. Sequences must contain `Axis` objects (not plain strings) because Haliax cannot +otherwise know the axis sizes. + +### AxisSelection + +[`AxisSelection`][haliax.AxisSelection] generalizes the previous aliases so you can talk about several axes at once. It +shows up in reductions, indexing helpers, axis-mapping utilities, and anywhere you might have written `axis=(0, 1)` in +NumPy. You may supply: + +* a sequence mixing `Axis` objects and strings, e.g. `("batch", Feature)` when reducing two axes, +* an `AxisSpec`, which is handy when you already have a tuple of `Axis` objects, or +* a "partial shape dict" where the values are either sizes or `None` to indicate "any size". Dictionaries are useful when + you only care about a subset of axes or want to assert a particular size. + +```python +# Reduce over two axes using a tuple of selectors. +scalar = x.sum(axis=("batch", Feature)) + +# Ask for the axes by name and optionally pin sizes. +x.resolve_axis({"batch": None, "feature": None}) # returns {"batch": 32, "feature": 128} + +from haliax.axis import selects_axis +assert selects_axis((Batch, "feature"), {"batch": None, "feature": 128}) +``` + +Occasionally, an axis size can be inferred in some circumstances but not others. When this happens we still use +`AxisSelector` (or `AxisSelection` for multiple axes) but document the behavior in the docstring. A `RuntimeError` will be +raised if the size cannot be inferred. ::: haliax.Axis ::: haliax.AxisSelector diff --git a/docs/primer.md b/docs/primer.md index cc3a458..0106650 100644 --- a/docs/primer.md +++ b/docs/primer.md @@ -25,6 +25,75 @@ Most functions accept either axes or shape dicts interchangeably. A tensor with named axes is a [`NamedArray`][haliax.NamedArray]. Elementwise operations mirror `jax.numpy` but accept named axes. +### Ways to Describe Axes + +If you're used to `axis=0` style code in NumPy or JAX, think of Haliax as swapping those positional indices for names +like `axis="batch"`. The API hints refer to a few helper aliases; this table shows how they map back to familiar +concepts: + +| Name | Accepts | Typical use | Example | +| --- | --- | --- | --- | +| [`Axis`][haliax.Axis] | `Axis(name: str, size: int)` | Define a named dimension with a fixed size | `Batch = Axis("batch", 32)` | +| [`AxisSelector`][haliax.AxisSelector] | `Axis` or `str` | Refer to an existing axis when the size can be inferred from the argument | `x.sum(axis="batch")` | +| [`AxisSpec`][haliax.AxisSpec] | `dict[str, int]`, `Axis`, or a sequence of `Axis` objects | Supply complete shape information (array creation, reshaping) | `hax.zeros((Batch, Feature))` | +| [`AxisSelection`][haliax.AxisSelection] | `dict[str, int | None]`, `AxisSpec`, or a sequence of `AxisSelector` values | Work with one or more existing axes (reductions, indexing helpers, flattening, …) | `x.sum(axis=("batch", Feature))` | + +The following sections expand on each alias with quick references and NumPy-style parallels. + +#### `Axis`: reusable named dimensions + +An [`Axis`][haliax.Axis] stores a `name` and a `size`. Create them directly or let +[`haliax.make_axes`][] build a handful at once. Because axes compare by both name and size, they act as reusable handles and +catch many wiring mistakes early. + +```python +Batch = Axis("batch", 32) +Feature = Axis("feature", 128) +x = hax.ones((Batch, Feature)) +print(Batch.name, Batch.size) +``` + +#### `AxisSelector`: when the size is already known + +Many functions already see the array whose axes you're referencing (e.g. reductions). In those cases you can pass either the +`Axis` object or simply the axis name as a string. Haliax resolves the name against the array, similar to `axis=0` in NumPy. + +```python +total = x.sum(axis=Batch) # use the Axis handle +same_total = x.sum(axis="batch") # or just the name +``` + +If you reference an axis name that isn't present, Haliax raises a `ValueError`. + +#### `AxisSpec`: describing complete shapes + +When Haliax needs explicit sizes—creating arrays, reshaping, broadcasting to a new axis—you provide an [`AxisSpec`][haliax.AxisSpec]. +Shape dictionaries keep things close to standard Python, while sequences require actual `Axis` objects so the sizes stay explicit. + +```python +shape = {"batch": 32, "feature": 128} +y = hax.zeros(shape) # using a shape dict +z = hax.zeros((Batch, Feature)) # or a sequence of Axis objects +``` + +Python dictionaries preserve insertion order, so the layout in a shape dict matches the order of axes in the resulting array. + +#### `AxisSelection`: several axes at once + +[`AxisSelection`][haliax.AxisSelection] is the plural form used by reductions, indexing helpers, and flattening utilities. Supply a +tuple mixing `Axis` objects and strings, reuse an existing `AxisSpec`, or pass a partial shape dict where values are either +sizes or `None` for "any size". + +```python +scalar = x.sum(axis=("batch", Feature)) + +# Ask for the axes by name and optionally pin sizes. +x.resolve_axis({"batch": None, "feature": None}) # returns {"batch": 32, "feature": 128} +``` + +Partial shape dicts shine when you only care about a subset of axes or want assertions about their sizes. If the axis size +cannot be inferred from the provided arguments, Haliax raises a `RuntimeError`. + ## Indexing and Broadcasting Use axis names when slicing. Dictionaries are convenient for several axes: commit 3a752b0dc39495572a1098e19b436e46c67c8dbb Date: 2025-09-17T21:47:52-07:00 Handle numpy scalar indices without coercing tracer-like values (#213) diff --git a/src/haliax/core.py b/src/haliax/core.py index cd2c636..c2b49a8 100644 --- a/src/haliax/core.py +++ b/src/haliax/core.py @@ -1183,6 +1183,26 @@ def index(array: NamedArray, slices: Mapping[AxisSelector, NamedIndex]) -> Named def _compute_new_axes_and_slices_for_index( array, slices ) -> tuple[AxisSpec, list[py_slice | dslice | jnp.ndarray | int | list[int]]]: + def _is_integer_like_scalar_index(value: Any) -> bool: + if isinstance(value, (int, np.integer)): + return True + if not is_jax_array_like(value): + return False + shape = getattr(value, "shape", None) + if shape != (): + return False + dtype = getattr(value, "dtype", None) + if dtype is None: + return False + return jnp.issubdtype(dtype, jnp.integer) + + def _coerce_integer_like_index(value: Any): + if isinstance(value, np.integer): + return int(value) + if type(value) is np.ndarray and value.shape == () and jnp.issubdtype(value.dtype, jnp.integer): + return int(value.item()) + return value + ordered_slices: list = [py_slice(None, None, None)] * len(array.axes) # type: ignore kept_axes = [True] * len(array.axes) array_slice_indices = [] @@ -1205,8 +1225,8 @@ def _compute_new_axes_and_slices_for_index( kept_axes[axis_index] = False array_slice_indices.append(axis_index) index_axis_names.add(orig_axis.name) - elif isinstance(slice_, int): - ordered_slices[axis_index] = slice_ + elif _is_integer_like_scalar_index(slice_): + ordered_slices[axis_index] = _coerce_integer_like_index(slice_) kept_axes[axis_index] = False elif isinstance(slice_, NamedArray): ordered_slices[axis_index] = slice_ diff --git a/tests/core_test.py b/tests/core_test.py index a43aefe..c675628 100644 --- a/tests/core_test.py +++ b/tests/core_test.py @@ -548,6 +548,33 @@ def test_index_with_tracer(): assert jnp.all(jnp.equal(f(idx).array, named1.array[0, :, :])) +def test_index_with_numpy_integer_scalars(): + (H,) = hax.make_axes(H=6) + arr = hax.arange(H) + + np_int = np.int64(3) + result = arr[{H: np_int}] + assert isinstance(result, NamedArray) + assert result.axes == () + assert jnp.all(jnp.equal(result.array, arr.array[int(np_int)])) + + np_scalar_array = np.array(4, dtype=np.int32) + result = arr[{H: np_scalar_array}] + assert isinstance(result, NamedArray) + assert result.axes == () + assert jnp.all(jnp.equal(result.array, arr.array[int(np_scalar_array)])) + + class _FakeJaxScalar(np.ndarray): + def item(self, *args, **kwargs): # pragma: no cover - exercised via test assertions + raise AssertionError("item should not be called on tracer-like indices") + + fake_scalar = np.array(5, dtype=np.int32).view(_FakeJaxScalar) + result = arr[{H: fake_scalar}] + assert isinstance(result, NamedArray) + assert result.axes == () + assert jnp.all(jnp.equal(result.array, arr[{H: 5}].array)) + + def test_index_array_slices(): # fancier tests with array slices with named array args H, W, D, C, Q, I0 = hax.make_axes(H=10, W=20, D=30, C=40, Q=50, I0=10) commit 0c3b81f94bbec6488b6e9609f72d3abdeeafb783 Date: 2025-09-17T21:56:56-07:00 Add stable argsort option (#214) diff --git a/src/haliax/__init__.py b/src/haliax/__init__.py index b0fab19..128994c 100644 --- a/src/haliax/__init__.py +++ b/src/haliax/__init__.py @@ -715,7 +715,9 @@ def nanmean( where: Optional[NamedArray] = None, dtype: Optional[DTypeLike] = None, ) -> NamedArray: - return wrap_reduction_call(jnp.nanmean, array, axis, where, single_axis_only=False, supports_where=True, dtype=dtype) + return wrap_reduction_call( + jnp.nanmean, array, axis, where, single_axis_only=False, supports_where=True, dtype=dtype + ) def nanmin( @@ -734,7 +736,9 @@ def nanprod( where: Optional[NamedArray] = None, dtype: Optional[DTypeLike] = None, ) -> NamedArray: - return wrap_reduction_call(jnp.nanprod, array, axis, where, single_axis_only=False, supports_where=True, dtype=dtype) + return wrap_reduction_call( + jnp.nanprod, array, axis, where, single_axis_only=False, supports_where=True, dtype=dtype + ) def nanstd( @@ -745,7 +749,9 @@ def nanstd( ddof: int = 0, dtype: Optional[DTypeLike] = None, ) -> NamedArray: - return wrap_reduction_call(jnp.nanstd, array, axis, where, single_axis_only=False, supports_where=True, dtype=dtype, ddof=ddof) + return wrap_reduction_call( + jnp.nanstd, array, axis, where, single_axis_only=False, supports_where=True, dtype=dtype, ddof=ddof + ) def nansum( @@ -755,7 +761,9 @@ def nansum( where: Optional[NamedArray] = None, dtype: Optional[DTypeLike] = None, ) -> NamedArray: - return wrap_reduction_call(jnp.nansum, array, axis, where, single_axis_only=False, supports_where=True, dtype=dtype) + return wrap_reduction_call( + jnp.nansum, array, axis, where, single_axis_only=False, supports_where=True, dtype=dtype + ) def nanvar( @@ -766,7 +774,9 @@ def nanvar( ddof: int = 0, dtype: Optional[DTypeLike] = None, ) -> NamedArray: - return wrap_reduction_call(jnp.nanvar, array, axis, where, single_axis_only=False, supports_where=True, dtype=dtype, ddof=ddof) + return wrap_reduction_call( + jnp.nanvar, array, axis, where, single_axis_only=False, supports_where=True, dtype=dtype, ddof=ddof + ) # "Normalization" functions that use an axis but don't change the shape @@ -807,14 +817,17 @@ def sort(a: NamedArray, axis: AxisSelector) -> NamedArray: return wrap_axiswise_call(jnp.sort, a, axis, single_axis_only=True) -def argsort(a: NamedArray, axis: AxisSelector) -> NamedArray: +def argsort(a: NamedArray, axis: AxisSelector | None, *, stable: bool = False) -> NamedArray: """ Named version of [jax.numpy.argsort](https://jax.readthedocs.io/en/latest/_autosummary/jax.numpy.argsort.html). If `axis` is None, the returned array will be a 1D array of indices that would sort the flattened array, identical to `jax.numpy.argsort(a.array)`. + + Args: + stable: If ``True``, ensures that the indices of equal elements preserve their relative order. """ - return wrap_axiswise_call(jnp.argsort, a, axis, single_axis_only=True) + return wrap_axiswise_call(jnp.argsort, a, axis, single_axis_only=True, stable=stable) # elemwise binary ops diff --git a/src/haliax/core.py b/src/haliax/core.py index c2b49a8..4bccd34 100644 --- a/src/haliax/core.py +++ b/src/haliax/core.py @@ -623,8 +623,8 @@ class NamedArray(metaclass=NamedArrayMeta): def argmin(self, axis: Optional[AxisSelector]) -> "NamedArray": # pragma: no cover return haliax.argmin(self, axis=axis) - def argsort(self, axis: AxisSelector) -> "NamedArray": # pragma: no cover - return haliax.argsort(self, axis=axis) + def argsort(self, axis: AxisSelector | None, *, stable: bool = False) -> "NamedArray": # pragma: no cover + return haliax.argsort(self, axis=axis, stable=stable) def astype(self, dtype) -> "NamedArray": # pragma: no cover return NamedArray(self.array.astype(dtype), self.axes) diff --git a/src/haliax/fft.py b/src/haliax/fft.py index 34d45a0..f15cc58 100644 --- a/src/haliax/fft.py +++ b/src/haliax/fft.py @@ -1,3 +1,7 @@ +# Copyright 2025 The Levanter Authors +# +# SPDX-License-Identifier: Apache-2.0 + """Named wrappers around :mod:`jax.numpy.fft`. These functions mirror the behaviour of their :mod:`jax.numpy.fft` counterparts @@ -43,7 +47,6 @@ import jax.numpy.fft as jfft from .axis import Axis, AxisSelector, AxisSelection from .core import NamedArray - AxisSizeLike = int | Axis | None AxisMapping = Mapping[AxisSelector, AxisSizeLike] diff --git a/src/haliax/ops.py b/src/haliax/ops.py index 993b7cc..1b6397a 100644 --- a/src/haliax/ops.py +++ b/src/haliax/ops.py @@ -127,9 +127,7 @@ def nonzero(array: NamedArray, *, size: Axis, fill_value: int = 0) -> tuple[Name if not isinstance(array, NamedArray): raise ValueError("array must be a NamedArray") - return tuple( - NamedArray(idx, (size,)) for idx in jnp.nonzero(array.array, size=size.size, fill_value=fill_value) - ) + return tuple(NamedArray(idx, (size,)) for idx in jnp.nonzero(array.array, size=size.size, fill_value=fill_value)) def clip(array: NamedOrNumeric, a_min: NamedOrNumeric, a_max: NamedOrNumeric) -> NamedArray: diff --git a/tests/core_test.py b/tests/core_test.py index c675628..7689275 100644 --- a/tests/core_test.py +++ b/tests/core_test.py @@ -242,6 +242,25 @@ def test_cumsum_etc(): assert jnp.all(jnp.equal(hax.argsort(named1, axis=Width).array, jnp.argsort(named1.array, axis=1))) assert hax.argsort(named1, axis=Width).axes == (Height, Width, Depth) + assert jnp.all( + jnp.equal( + hax.argsort(named1, axis=Height, stable=True).array, + jnp.argsort(named1.array, axis=0, stable=True), + ) + ) + assert jnp.all( + jnp.equal( + hax.argsort(named1, axis=Width, stable=True).array, + jnp.argsort(named1.array, axis=1, stable=True), + ) + ) + assert jnp.all( + jnp.equal( + hax.argsort(named1, axis=None, stable=True), + jnp.argsort(named1.array, axis=None, stable=True), + ) + ) + def test_searchsorted(): A = hax.Axis("a", 5) diff --git a/tests/test_bitwise_ops.py b/tests/test_bitwise_ops.py index e209c12..e73f594 100644 --- a/tests/test_bitwise_ops.py +++ b/tests/test_bitwise_ops.py @@ -1,3 +1,7 @@ +# Copyright 2025 The Levanter Authors +# +# SPDX-License-Identifier: Apache-2.0 + import jax.numpy as jnp import haliax as hax from haliax import Axis diff --git a/tests/test_fft.py b/tests/test_fft.py index de04407..550f6ec 100644 --- a/tests/test_fft.py +++ b/tests/test_fft.py @@ -1,3 +1,7 @@ +# Copyright 2025 The Levanter Authors +# +# SPDX-License-Identifier: Apache-2.0 + import jax.numpy as jnp import jax.numpy.fft as jfft @@ -71,9 +75,7 @@ def test_fft_multi_axis(): assert jnp.allclose(rf.array, jfft.rfftn(arr.array, axes=(1, 2))) irf = hax.irfft(rf, axis={"y": None, "z": Z}) - assert jnp.allclose( - irf.array, jfft.irfftn(jfft.rfftn(arr.array, axes=(1, 2)), s=(Y.size, Z.size), axes=(1, 2)) - ) + assert jnp.allclose(irf.array, jfft.irfftn(jfft.rfftn(arr.array, axes=(1, 2)), s=(Y.size, Z.size), axes=(1, 2))) # resizing via dict values f2 = hax.fft(arr, axis={"y": 4, "z": None}) diff --git a/tests/test_nan_reductions.py b/tests/test_nan_reductions.py index 46b2269..c576fa6 100644 --- a/tests/test_nan_reductions.py +++ b/tests/test_nan_reductions.py @@ -1,3 +1,7 @@ +# Copyright 2025 The Levanter Authors +# +# SPDX-License-Identifier: Apache-2.0 + from typing import Any, Callable import jax.numpy as jnp commit 38473f19ac144e2b3fec04814f9f44d2cbc94e2a Date: 2025-09-17T22:37:07-07:00 Refine polynomial wrappers and typings (#215) diff --git a/.agents/projects/api_parity.md b/.agents/projects/api_parity.md index 8222729..56977c8 100644 --- a/.agents/projects/api_parity.md +++ b/.agents/projects/api_parity.md @@ -115,15 +115,15 @@ APIs that don't translate well to named tensors are intentionally omitted here. - [ ] `permute_dims` - [ ] `piecewise` - [ ] `place` -- [ ] `poly` -- [ ] `polyadd` -- [ ] `polyder` -- [ ] `polydiv` -- [ ] `polyfit` -- [ ] `polyint` -- [ ] `polymul` -- [ ] `polysub` -- [ ] `polyval` +- [x] `poly` +- [x] `polyadd` +- [x] `polyder` +- [x] `polydiv` +- [x] `polyfit` +- [x] `polyint` +- [x] `polymul` +- [x] `polysub` +- [x] `polyval` - [ ] `pow` - [ ] `promote_types` - [ ] `put` @@ -134,7 +134,7 @@ APIs that don't translate well to named tensors are intentionally omitted here. - [ ] `resize` - [ ] `result_type` - [ ] `rollaxis` -- [ ] `roots` +- [x] `roots` - [ ] `rot90` - [ ] `select` - [ ] `setdiff1d` @@ -148,7 +148,7 @@ APIs that don't translate well to named tensors are intentionally omitted here. - [ ] `tri` - [ ] `tril_indices` - [ ] `tril_indices_from` -- [ ] `trim_zeros` +- [x] `trim_zeros` - [ ] `triu_indices` - [ ] `triu_indices_from` - [ ] `union1d` @@ -156,7 +156,7 @@ APIs that don't translate well to named tensors are intentionally omitted here. - [ ] `unravel_index` - [ ] `unstack` - [ ] `unwrap` -- [ ] `vander` +- [x] `vander` - [ ] `vsplit` - [ ] `vstack` diff --git a/docs/api.md b/docs/api.md index 9cc9783..77e1577 100644 --- a/docs/api.md +++ b/docs/api.md @@ -340,6 +340,21 @@ These are all more or less directly from JAX's NumPy API. ::: haliax.subtract ::: haliax.true_divide +### Polynomial Operations + +::: haliax.poly +::: haliax.polyadd +::: haliax.polysub +::: haliax.polymul +::: haliax.polydiv +::: haliax.polyint +::: haliax.polyder +::: haliax.polyval +::: haliax.polyfit +::: haliax.roots +::: haliax.trim_zeros +::: haliax.vander + ### Other Operations ::: haliax.bincount diff --git a/src/haliax/__init__.py b/src/haliax/__init__.py index 128994c..d2f9f95 100644 --- a/src/haliax/__init__.py +++ b/src/haliax/__init__.py @@ -96,6 +96,22 @@ from .ops import ( bincount, where, ) + +from .poly import ( + poly, + polyadd, + polysub, + polymul, + polydiv, + polyint, + polyder, + polyval, + polyfit, + roots, + trim_zeros, + vander, +) + from .fft import ( fft, fftfreq, @@ -1239,6 +1255,18 @@ __all__ = [ "clip", "tril", "triu", + "poly", + "polyadd", + "polysub", + "polymul", + "polydiv", + "polyint", + "polyder", + "polyval", + "polyfit", + "roots", + "trim_zeros", + "vander", "fft", "ifft", "hfft", diff --git a/src/haliax/poly.py b/src/haliax/poly.py new file mode 100644 index 0000000..e25c3ea --- /dev/null +++ b/src/haliax/poly.py @@ -0,0 +1,304 @@ +"""Polynomial helpers for :mod:`haliax`. + +This module provides NamedArray-aware wrappers around :mod:`jax.numpy`'s +polynomial utilities. +""" + +from __future__ import annotations + +from typing import Literal, overload + +import jax.numpy as jnp +from jaxtyping import Array, ArrayLike + +from .axis import Axis, AxisSelector, axis_name +from .core import NamedArray, NamedOrNumeric +from .wrap import unwrap_namedarrays + +DEFAULT_POLY_AXIS_NAME = "degree" +"""Default name used for polynomial coefficient axes when none is provided.""" + + +def _poly_axis_from_input(p: NamedArray | ArrayLike, size: int) -> Axis: + if isinstance(p, NamedArray): + if p.ndim != 1: + raise ValueError("Polynomial coefficient arrays must be 1D") + return p.axes[0].resize(size) + else: + return Axis(DEFAULT_POLY_AXIS_NAME, size) + + +def poly(seq_of_zeros: NamedArray | ArrayLike) -> NamedArray: + """Named version of [jax.numpy.poly][]. + + If ``seq_of_zeros`` is not a [haliax.NamedArray][], the returned coefficient axis + is named ``degree``. + """ + + (roots,) = unwrap_namedarrays(seq_of_zeros) + result = jnp.poly(roots) + axis = _poly_axis_from_input(seq_of_zeros, result.shape[0]) + return NamedArray(result, (axis,)) + + +def polyadd(p1: NamedArray | ArrayLike, p2: NamedArray | ArrayLike) -> NamedArray: + """Named version of [jax.numpy.polyadd][]. + + If neither input is a [haliax.NamedArray][], the coefficient axis is named + ``degree``; otherwise the axis from the NamedArray input is reused (resized as + needed). + """ + + a1, a2 = unwrap_namedarrays(p1, p2) + result = jnp.polyadd(a1, a2) + axis = _poly_axis_from_input(p1 if isinstance(p1, NamedArray) else p2, result.shape[0]) + return NamedArray(result, (axis,)) + + +def polysub(p1: NamedArray | ArrayLike, p2: NamedArray | ArrayLike) -> NamedArray: + """Named version of [jax.numpy.polysub][]. + + If neither input is a [haliax.NamedArray][], the coefficient axis is named + ``degree``; otherwise the axis from the NamedArray input is reused (resized as + needed). + """ + + a1, a2 = unwrap_namedarrays(p1, p2) + result = jnp.polysub(a1, a2) + axis = _poly_axis_from_input(p1 if isinstance(p1, NamedArray) else p2, result.shape[0]) + return NamedArray(result, (axis,)) + + +def polymul(p1: NamedArray | ArrayLike, p2: NamedArray | ArrayLike) -> NamedArray: + """Named version of [jax.numpy.polymul][]. + + If neither input is a [haliax.NamedArray][], the coefficient axis is named + ``degree``; otherwise the axis from the NamedArray input is reused (resized as + needed). + """ + + a1, a2 = unwrap_namedarrays(p1, p2) + result = jnp.polymul(a1, a2) + axis = _poly_axis_from_input(p1 if isinstance(p1, NamedArray) else p2, result.shape[0]) + return NamedArray(result, (axis,)) + + +def polydiv(p1: NamedArray | ArrayLike, p2: NamedArray | ArrayLike) -> tuple[NamedArray, NamedArray]: + """Named version of [jax.numpy.polydiv][]. + + The quotient and remainder reuse the coefficient axis from the NamedArray input + when available; otherwise their coefficient axes are named ``degree``. + """ + + a1, a2 = unwrap_namedarrays(p1, p2) + q, r = jnp.polydiv(a1, a2) + base = p1 if isinstance(p1, NamedArray) else p2 + axis_q = _poly_axis_from_input(base, q.shape[0]) + axis_r = _poly_axis_from_input(base, r.shape[0]) + return NamedArray(q, (axis_q,)), NamedArray(r, (axis_r,)) + + +def polyint(p: NamedArray | ArrayLike, m: int = 1, k: ArrayLike | NamedArray | None = None) -> NamedArray: + """Named version of [jax.numpy.polyint][]. + + If ``p`` is not a [haliax.NamedArray][], the integrated polynomial uses a + coefficient axis named ``degree``. + """ + + (arr,) = unwrap_namedarrays(p) + k_arr = None + if k is not None: + (k_arr,) = unwrap_namedarrays(k) + result = jnp.polyint(arr, m=m, k=k_arr) + axis = _poly_axis_from_input(p, result.shape[0]) + return NamedArray(result, (axis,)) + + +def polyder(p: NamedArray | ArrayLike, m: int = 1) -> NamedArray: + """Named version of [jax.numpy.polyder][]. + + If ``p`` is not a [haliax.NamedArray][], the differentiated polynomial uses a + coefficient axis named ``degree``. + """ + + (arr,) = unwrap_namedarrays(p) + result = jnp.polyder(arr, m=m) + axis = _poly_axis_from_input(p, result.shape[0]) + return NamedArray(result, (axis,)) + + +def polyval(p: NamedArray | ArrayLike, x: NamedOrNumeric) -> NamedOrNumeric: + """Named version of [jax.numpy.polyval][]. + + When ``x`` is a [haliax.NamedArray][], the returned array reuses ``x``'s axes. + Otherwise a regular :mod:`jax.numpy` array is returned. + """ + + arr_p, arr_x = unwrap_namedarrays(p, x) + result = jnp.polyval(arr_p, arr_x) + if isinstance(x, NamedArray): + return NamedArray(result, x.axes) + else: + return result + + +@overload +def polyfit( + x: NamedArray | ArrayLike, + y: NamedArray | ArrayLike, + deg: int, + rcond: ArrayLike | None = ..., + full: Literal[False] = ..., + w: NamedArray | ArrayLike | None = ..., + cov: Literal[False] = ..., +) -> NamedArray: + ... + + +@overload +def polyfit( + x: NamedArray | ArrayLike, + y: NamedArray | ArrayLike, + deg: int, + rcond: ArrayLike | None = ..., + full: Literal[True] = ..., + w: NamedArray | ArrayLike | None = ..., + cov: Literal[False] = ..., +) -> tuple[NamedArray, Array, Array, Array, Array]: + ... + + +@overload +def polyfit( + x: NamedArray | ArrayLike, + y: NamedArray | ArrayLike, + deg: int, + rcond: ArrayLike | None = ..., + full: Literal[False] = ..., + w: NamedArray | ArrayLike | None = ..., + cov: Literal[True] = ..., +) -> tuple[NamedArray, NamedArray]: + ... + + +@overload +def polyfit( + x: NamedArray | ArrayLike, + y: NamedArray | ArrayLike, + deg: int, + rcond: ArrayLike | None = ..., + full: Literal[True] = ..., + w: NamedArray | ArrayLike | None = ..., + cov: Literal[True] = ..., +) -> tuple[NamedArray, Array, Array, Array, Array]: + ... + + +def polyfit( + x: NamedArray | ArrayLike, + y: NamedArray | ArrayLike, + deg: int, + rcond: ArrayLike | None = None, + full: bool = False, + w: NamedArray | ArrayLike | None = None, + cov: bool = False, +) -> NamedArray | tuple: + """Named version of [jax.numpy.polyfit][]. + + If neither ``x`` nor ``y`` is a [haliax.NamedArray][], the fitted coefficients + use a coefficient axis named ``degree``; otherwise the axis from the NamedArray + input is reused. When ``cov`` is ``True``, the returned covariance matrix is + wrapped in a [haliax.NamedArray][] whose row axis matches the coefficient + axis and whose column axis uses the same name with a ``"_cov"`` suffix. + """ + + x_arr, y_arr = unwrap_namedarrays(x, y) + rcond_arr = None + if rcond is not None: + (rcond_arr,) = unwrap_namedarrays(rcond) + w_arr = None + if w is not None: + (w_arr,) = unwrap_namedarrays(w) + result = jnp.polyfit(x_arr, y_arr, deg, rcond=rcond_arr, full=full, w=w_arr, cov=cov) + + def wrap_coeffs(coeffs): + base = x if isinstance(x, NamedArray) else y + axis = _poly_axis_from_input(base, coeffs.shape[0]) + return NamedArray(coeffs, (axis,)) + + if full: + coeffs = wrap_coeffs(result[0]) + return (coeffs,) + result[1:] + coeffs = wrap_coeffs(result if not cov else result[0]) + if cov: + cov_axis = coeffs.axes[0] + return coeffs, NamedArray(result[1], (cov_axis, cov_axis.alias(f"{cov_axis.name}_cov"))) + return coeffs + + +def roots(p: NamedArray | ArrayLike) -> NamedArray: + """Named version of [jax.numpy.roots][]. + + If ``p`` is not a [haliax.NamedArray][], the root axis is named ``degree``. + """ + + (arr,) = unwrap_namedarrays(p) + result = jnp.roots(arr) + axis = _poly_axis_from_input(p, result.shape[0]) + return NamedArray(result, (axis,)) + + +def trim_zeros(f: NamedArray | ArrayLike, trim: str = "fb") -> NamedArray: + """Named version of [jax.numpy.trim_zeros][]. + + If ``f`` is not a [haliax.NamedArray][], the trimmed coefficient axis is named + ``degree``. + """ + + (arr,) = unwrap_namedarrays(f) + result = jnp.trim_zeros(arr, trim=trim) + axis = _poly_axis_from_input(f, result.shape[0]) + return NamedArray(result, (axis,)) + + +def vander(x: NamedArray, degree: AxisSelector) -> NamedArray: + """Named version of [jax.numpy.vander][]. + + Args: + x: Input array of shape ``(n,)``. + degree: Axis for the polynomial degree in the output. If a string is + provided, an axis with that name and size ``n`` is created. + + Returns: + Vandermonde matrix with row axis from ``x`` and the provided degree axis. + """ + + if x.ndim != 1: + raise ValueError("vander only supports 1D input") + + if isinstance(degree, Axis): + N = degree.size + deg_axis = degree + else: + N = x.axes[0].size + deg_axis = Axis(axis_name(degree), N) + + result = jnp.vander(x.array, N=N) + return NamedArray(result, (x.axes[0], deg_axis)) + + +__all__ = [ + "DEFAULT_POLY_AXIS_NAME", + "poly", + "polyadd", + "polysub", + "polymul", + "polydiv", + "polyint", + "polyder", + "polyval", + "polyfit", + "roots", + "trim_zeros", + "vander", +] diff --git a/tests/test_poly_ops.py b/tests/test_poly_ops.py new file mode 100644 index 0000000..75b18cd --- /dev/null +++ b/tests/test_poly_ops.py @@ -0,0 +1,131 @@ +import jax.numpy as jnp +from typing import cast, no_type_check +import haliax as hax +from haliax import Axis +from haliax.core import NamedArray + + +def _assert_coefficients(coeffs: NamedArray, expected: jnp.ndarray, axis: Axis) -> None: + assert jnp.allclose(coeffs.array, expected) # type: ignore[union-attr] + assert coeffs.axes[0] == axis.resize(coeffs.array.shape[0]) # type: ignore[union-attr] + + +def _assert_covariance_matrix(cov: NamedArray, axis: Axis, expected: jnp.ndarray) -> None: + assert jnp.allclose(cov.array, expected) # type: ignore[union-attr] + assert cov.axes[0] == axis # type: ignore[union-attr] + assert cov.axes[1].name == f"{axis.name}_cov" # type: ignore[union-attr] + assert cov.axes[1].size == axis.size # type: ignore[union-attr] + + +def test_poly(): + R = Axis("R", 3) + roots = hax.named([1.0, 2.0, 3.0], (R,)) + coeffs = hax.poly(roots) + assert jnp.allclose(coeffs.array, jnp.poly(roots.array)) + assert coeffs.axes[0] == R.resize(coeffs.array.shape[0]) + + +def test_poly_arithmetic(): + C1 = Axis("C1", 4) + p = hax.named([1.0, 0.0, -2.0, 1.0], (C1,)) + C2 = Axis("C2", 2) + q = hax.named([1.0, -1.0], (C2,)) + + add = hax.polyadd(p, q) + assert jnp.allclose(add.array, jnp.polyadd(p.array, q.array)) + assert add.axes[0] == C1.resize(add.array.shape[0]) + + sub = hax.polysub(p, q) + assert jnp.allclose(sub.array, jnp.polysub(p.array, q.array)) + assert sub.axes[0] == C1.resize(sub.array.shape[0]) + + mul = hax.polymul(p, q) + assert jnp.allclose(mul.array, jnp.polymul(p.array, q.array)) + assert mul.axes[0] == C1.resize(mul.array.shape[0]) + + div_q, div_r = hax.polydiv(p, q) + exp_q, exp_r = jnp.polydiv(p.array, q.array) + assert jnp.allclose(div_q.array, exp_q) + assert jnp.allclose(div_r.array, exp_r) + assert div_q.axes[0] == C1.resize(div_q.array.shape[0]) + assert div_r.axes[0] == C1.resize(div_r.array.shape[0]) + + +def test_poly_int_der(): + C = Axis("C", 4) + p = hax.named([1.0, 0.0, -2.0, 1.0], (C,)) + + d = hax.polyder(p) + i = hax.polyint(p) + + assert jnp.allclose(d.array, jnp.polyder(p.array)) + assert jnp.allclose(i.array, jnp.polyint(p.array)) + assert d.axes[0] == C.resize(d.array.shape[0]) + assert i.axes[0] == C.resize(i.array.shape[0]) + + +@no_type_check +def test_polyval_polyfit(): + C = Axis("C", 4) + p = hax.named([1.0, 0.0, -2.0, 1.0], (C,)) + + X = Axis("X", 5) + x = hax.arange(X, dtype=jnp.float64) + y = hax.polyval(p, x) + + pv = cast(NamedArray, hax.polyval(p, x)) + assert jnp.allclose(pv.array, jnp.polyval(p.array, x.array)) + + fit = cast(NamedArray, hax.polyfit(x, y, 3)) + assert jnp.allclose(fit.array, p.array, atol=1e-5) + assert fit.axes[0] == X.resize(fit.array.shape[0]) + + full_fit = hax.polyfit(x, y, 3, full=True) + assert isinstance(full_fit, tuple) + coeffs_full = full_fit[0] + assert isinstance(coeffs_full, NamedArray) + coeffs_full = cast(NamedArray, coeffs_full) + exp_full = jnp.polyfit(x.array, y.array, 3, full=True) + _assert_coefficients(coeffs_full, exp_full[0], X) # type: ignore[union-attr] + for res, exp in zip(full_fit[1:], exp_full[1:]): + assert jnp.allclose(res, exp) + + cov_fit = hax.polyfit(x, y, 3, cov=True) + assert isinstance(cov_fit, tuple) + coeffs_cov = cov_fit[0] + cov = cov_fit[1] + assert isinstance(coeffs_cov, NamedArray) + assert isinstance(cov, NamedArray) + coeffs_cov = cast(NamedArray, coeffs_cov) + cov = cast(NamedArray, cov) + exp_coeffs, exp_cov = jnp.polyfit(x.array, y.array, 3, cov=True) + _assert_coefficients(coeffs_cov, exp_coeffs, X) # type: ignore[union-attr] + _assert_covariance_matrix(cov, coeffs_cov.axes[0], exp_cov) # type: ignore[union-attr] + + + +def test_poly_roots_trim_vander(): + C = Axis("C", 4) + p = hax.named([1.0, 0.0, -2.0, 1.0], (C,)) + + r = hax.roots(p) + assert jnp.allclose(r.array, jnp.roots(p.array)) + assert r.axes[0] == C.resize(r.array.shape[0]) + + C2 = Axis("C2", 4) + p2 = hax.named([0.0, 0.0, 1.0, 2.0], (C2,)) + t = hax.trim_zeros(p2) + assert jnp.allclose(t.array, jnp.trim_zeros(p2.array)) + assert t.axes[0] == C2.resize(t.array.shape[0]) + + X = Axis("X", 3) + x = hax.named([1.0, 2.0, 3.0], (X,)) + D = Axis("D", 3) + v = hax.vander(x, D) + assert jnp.allclose(v.array, jnp.vander(x.array, N=3)) + assert v.axes == (X, D) + + v2 = hax.vander(x, "E") + assert jnp.allclose(v2.array, jnp.vander(x.array)) + assert v2.axes[0] == X + assert v2.axes[1] == Axis("E", X.size) commit c5637f5c71244aca67e4249c5f5822f92a1b1409 Date: 2025-09-19T09:46:07-07:00 feat: Add Open Athena AI Foundation as author (#217) Adds Open Athena AI Foundation, Inc. to the list of authors in AUTHORS.md. Co-authored-by: google-labs-jules[bot] <161369871+google-labs-jules[bot]@users.noreply.github.com> diff --git a/AUTHORS.md b/AUTHORS.md index 8846e76..e310bf9 100644 --- a/AUTHORS.md +++ b/AUTHORS.md @@ -3,3 +3,4 @@ The Levanter Authors currently include: - The Board of Trustees of the Leland Stanford Junior University +- Open Athena AI Foundation, Inc. commit f41e7d40c63dc486b69c5d854270a9158fe3dd39 Date: 2025-09-19T09:46:29-07:00 Allow one_hot to handle scalar arrays (#216) diff --git a/src/haliax/nn/__init__.py b/src/haliax/nn/__init__.py index 3933da9..717b2fc 100644 --- a/src/haliax/nn/__init__.py +++ b/src/haliax/nn/__init__.py @@ -3,6 +3,8 @@ # SPDX-License-Identifier: Apache-2.0 +import numbers + import jax.nn as jnn import jax.numpy as jnp @@ -64,16 +66,25 @@ def one_hot(x: NamedArray | int, class_axis: Axis, *, dtype=None) -> NamedArray: # Disabling this to prevent a crash in XLA on GPU # return hax.auto_sharded(hax.named(array, x.axes + (class_axis,))) return hax.named(array, x.axes + (class_axis,)) - else: - assert isinstance(x, int) + + x_array = jnp.asarray(x) + if x_array.ndim != 0: + raise TypeError("one_hot expects a scalar integer or NamedArray, " f"but got array with shape {x_array.shape}") + + if isinstance(x, numbers.Integral): assert class_axis.size > x >= -class_axis.size + else: + if not (jnp.issubdtype(x_array.dtype, jnp.integer) or jnp.issubdtype(x_array.dtype, jnp.bool_)): + raise TypeError( + "one_hot expects an integer scalar or NamedArray, " f"but got value with dtype {x_array.dtype}" + ) - one = 1 - if dtype is not None: - one = dtype(one) + one = 1 + if dtype is not None: + one = dtype(one) - array = jnp.zeros(class_axis.size, dtype=dtype).at[x].set(one) - return hax.auto_sharded(haliax.named(array, class_axis)) + array = jnp.zeros(class_axis.size, dtype=dtype).at[x_array].set(one) + return hax.auto_sharded(haliax.named(array, class_axis)) __all__ = [ diff --git a/src/haliax/poly.py b/src/haliax/poly.py index e25c3ea..5408d7f 100644 --- a/src/haliax/poly.py +++ b/src/haliax/poly.py @@ -1,3 +1,7 @@ +# Copyright 2025 The Levanter Authors +# +# SPDX-License-Identifier: Apache-2.0 + """Polynomial helpers for :mod:`haliax`. This module provides NamedArray-aware wrappers around :mod:`jax.numpy`'s @@ -151,8 +155,7 @@ def polyfit( full: Literal[False] = ..., w: NamedArray | ArrayLike | None = ..., cov: Literal[False] = ..., -) -> NamedArray: - ... +) -> NamedArray: ... @overload @@ -164,8 +167,7 @@ def polyfit( full: Literal[True] = ..., w: NamedArray | ArrayLike | None = ..., cov: Literal[False] = ..., -) -> tuple[NamedArray, Array, Array, Array, Array]: - ... +) -> tuple[NamedArray, Array, Array, Array, Array]: ... @overload @@ -177,8 +179,7 @@ def polyfit( full: Literal[False] = ..., w: NamedArray | ArrayLike | None = ..., cov: Literal[True] = ..., -) -> tuple[NamedArray, NamedArray]: - ... +) -> tuple[NamedArray, NamedArray]: ... @overload @@ -190,8 +191,7 @@ def polyfit( full: Literal[True] = ..., w: NamedArray | ArrayLike | None = ..., cov: Literal[True] = ..., -) -> tuple[NamedArray, Array, Array, Array, Array]: - ... +) -> tuple[NamedArray, Array, Array, Array, Array]: ... def polyfit( diff --git a/tests/test_nn.py b/tests/test_nn.py index 2915898..30b4a80 100644 --- a/tests/test_nn.py +++ b/tests/test_nn.py @@ -64,6 +64,24 @@ def test_one_hot(): assert jnp.all(jnp.isclose(actual.array, expected)) +def test_one_hot_scalar_array(): + (c,) = hax.make_axes(c=3) + + scalar_value = jnp.array(1, dtype=jnp.int32) + actual = hax.nn.one_hot(scalar_value, c) + expected = jnp.array([0.0, 1.0, 0.0]) + + assert actual.axes == (c,) + assert jnp.all(jnp.isclose(actual.array, expected)) + + negative_scalar = jnp.array(-1, dtype=jnp.int32) + actual = hax.nn.one_hot(negative_scalar, c) + expected = jnp.array([0.0, 0.0, 1.0]) + + assert actual.axes == (c,) + assert jnp.all(jnp.isclose(actual.array, expected)) + + def test_one_hot_out_of_bound(): i, c = hax.make_axes(i=2, c=3) actual = hax.nn.one_hot(hax.NamedArray(jnp.array([-1, 3]), (i,)), c) diff --git a/tests/test_poly_ops.py b/tests/test_poly_ops.py index 75b18cd..7c7b81d 100644 --- a/tests/test_poly_ops.py +++ b/tests/test_poly_ops.py @@ -1,3 +1,7 @@ +# Copyright 2025 The Levanter Authors +# +# SPDX-License-Identifier: Apache-2.0 + import jax.numpy as jnp from typing import cast, no_type_check import haliax as hax @@ -103,7 +107,6 @@ def test_polyval_polyfit(): _assert_covariance_matrix(cov, coeffs_cov.axes[0], exp_cov) # type: ignore[union-attr] - def test_poly_roots_trim_vander(): C = Axis("C", 4) p = hax.named([1.0, 0.0, -2.0, 1.0], (C,)) commit 912e9733dbd44f3a9fd8be76b2bb7132fa52e6a1 Date: 2025-09-30T15:59:10-07:00 Deprecate `_get_mesh` (#218) * deprecate _get_mesh * precommit * wip * support jax 0.6.2 and 0.7.2 * cleanup * pre-commit * sigh diff --git a/pyproject.toml b/pyproject.toml index 29f202e..1b829ec 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -21,8 +21,7 @@ classifiers = [ "Intended Audience :: Science/Research", ] dependencies = [ - # we require that you install jax yourself, since the extras vary by system. - # jax = {version = ">=0.4.19,<0.5.0"} + "jax >= 0.6.2", "equinox>=0.10.6", "jaxtyping>=0.2.20", "jmp>=0.0.4", diff --git a/src/haliax/__init__.py b/src/haliax/__init__.py index d2f9f95..8a11c44 100644 --- a/src/haliax/__init__.py +++ b/src/haliax/__init__.py @@ -8,11 +8,8 @@ from typing import Optional, Sequence import jax import jax.numpy as jnp +from jax.typing import DTypeLike -try: - from jax.typing import DTypeLike -except ImportError: - from jax._src.typing import DTypeLike import haliax.debug as debug import haliax.nn as nn @@ -124,7 +121,7 @@ from .fft import ( rfft, rfftfreq, ) -from .partitioning import auto_sharded, axis_mapping, fsdp, named_jit, shard, shard_with_axis_mapping +from .partitioning import auto_sharded, axis_mapping, fsdp, named_jit, set_mesh, shard, shard_with_axis_mapping from .specialized_fns import top_k from .types import Scalar from .util import is_named_array @@ -1352,4 +1349,5 @@ __all__ = [ "NamedArrayAxes", "NamedArrayAxesSpec", "Named", + "set_mesh", ] diff --git a/src/haliax/_src/state_dict.py b/src/haliax/_src/state_dict.py index 7018d99..740b903 100644 --- a/src/haliax/_src/state_dict.py +++ b/src/haliax/_src/state_dict.py @@ -197,7 +197,7 @@ def from_state_dict(tree: T, state_dict: StateDict, prefix: Optional[str] = None array = state_dict[prefix] if isinstance(array, np.ndarray): - mesh = partitioning._get_mesh() + mesh = jax.sharding.get_abstract_mesh() # TODO: modernize this if jax.device_count() > 1: # this happens with the default mesh pspec = partitioning.pspec_for_axis(tree.axes) diff --git a/src/haliax/nn/linear.py b/src/haliax/nn/linear.py index 9a6add3..3c23f87 100644 --- a/src/haliax/nn/linear.py +++ b/src/haliax/nn/linear.py @@ -251,7 +251,7 @@ def _gmm(lhs, rhs, group_sizes, out_axes, sharded=False, ar=False): else: gmm_fn = shard_map( partial(gmm_sharded, ar=ar), - mesh=hax.partitioning._get_mesh(), + mesh=jax.sharding.get_abstract_mesh(), in_specs=( hax.partitioning.pspec_for_axis(lhs.axes), hax.partitioning.pspec_for_axis(rhs.axes), diff --git a/src/haliax/ops.py b/src/haliax/ops.py index 1b6397a..3dd97df 100644 --- a/src/haliax/ops.py +++ b/src/haliax/ops.py @@ -333,7 +333,7 @@ def unique( ) if axis is not None: - axis_index = array._lookup_indices(axis) + axis_index = array.axis_indices(axis) if axis_index is None: raise ValueError(f"Axis {axis} not found in array. Available axes: {array.axes}") out = jnp.unique(array.array, axis=axis_index, **kwargs) diff --git a/src/haliax/partitioning.py b/src/haliax/partitioning.py index 678053b..621f34a 100644 --- a/src/haliax/partitioning.py +++ b/src/haliax/partitioning.py @@ -10,31 +10,13 @@ import threading import typing import warnings from math import prod -from typing import Callable, ContextManager, Mapping, Optional, ParamSpec, Sequence, TypeVar, Union +from typing import Callable, ContextManager, Mapping, Optional, ParamSpec, Sequence, TypeVar, Union, cast import equinox as eqx import jax from equinox import is_array, module_update_wrapper from jax.lax import with_sharding_constraint -from jax.sharding import ( - Mesh, - NamedSharding, - PartitionSpec, - SingleDeviceSharding, -) - -try: # jax>=0.4.26 - from jax.sharding import AbstractMesh, get_abstract_mesh -except Exception: # pragma: no cover - older JAX versions - AbstractMesh = Mesh # type: ignore[misc,assignment] - - def get_abstract_mesh(): # type: ignore[dead-code] - try: - from jax.interpreters.pxla import thread_resources - except Exception: - from jax.experimental.maps import thread_resources - - return thread_resources.env.physical_mesh +from jax.sharding import AbstractMesh, NamedSharding, Mesh, PartitionSpec, SingleDeviceSharding, get_abstract_mesh from jaxtyping import PyTree @@ -50,6 +32,7 @@ from .util import StringHolderEnum PhysicalAxisSpec = Union[(str), Sequence[str]] ResourceMapping = Mapping[(str), PhysicalAxisSpec] +MeshLike = Union[Mesh, AbstractMesh] """Mapping from logical axis names to physical axis names""" F = typing.TypeVar("F", bound=typing.Callable) @@ -109,6 +92,71 @@ def current_thread_local_mapping(): return _mapping_holder.thread_data.resource_mapping +def _resolve_mesh(mesh: Optional[MeshLike] = None) -> Optional[MeshLike]: + """Inside jit, prefer an abstract mesh, outside jit prefer a concrete mesh.""" + + from jax._src.mesh import get_concrete_mesh + + if mesh is not None: + if is_in_jit() and isinstance(mesh, Mesh): + return mesh.abstract_mesh + return mesh + + if is_in_jit(): + abstract = get_abstract_mesh() + if not abstract or abstract.empty: + concrete = get_concrete_mesh() + if concrete is not None and not concrete.empty: + return concrete.abstract_mesh + + from jax.interpreters.pxla import thread_resources + + old_mesh = thread_resources.env.physical_mesh + if old_mesh is not None and not old_mesh.empty: + return old_mesh.abstract_mesh + + return abstract + else: + mesh = get_concrete_mesh() or get_abstract_mesh() + if mesh is not None and not mesh.empty: + return mesh + + from jax.interpreters.pxla import thread_resources + + old_mesh = thread_resources.env.physical_mesh + if old_mesh is not None and not old_mesh.empty: + return old_mesh + + return None + + +def mesh_context(mesh: MeshLike) -> ContextManager[None]: + """Context manager that normalizes mesh handling across JAX versions.""" + + set_mesh_fn = getattr(jax, "set_mesh", None) + use_mesh_fn = getattr(jax.sharding, "use_mesh", None) + + manager_factory: Optional[Callable[[MeshLike], ContextManager[None]]] = None + if set_mesh_fn is not None: + manager_factory = cast(Callable[[MeshLike], ContextManager[None]], set_mesh_fn) + elif use_mesh_fn is not None: + manager_factory = cast(Callable[[MeshLike], ContextManager[None]], use_mesh_fn) + + if manager_factory is None: + msg = "Haliax requires a version of JAX that provides either `jax.set_mesh` or `jax.sharding.use_mesh`." + raise RuntimeError(msg) + + context_manager = manager_factory(mesh) + + return context_manager + + +def set_mesh(mesh: MeshLike) -> ContextManager[None]: + """Compatibility wrapper around `mesh_context` matching the JAX 0.7 API.""" + + return mesh_context(mesh) + + def auto_sharded(x: T, mesh: Optional[Mesh] = None) -> T: """ Shard a PyTree using the global axis mapping. NamedArrays in the PyTree are sharded using the axis mapping @@ -143,11 +191,15 @@ def shard(x: T, mapping: Optional[ResourceMapping] = None, mesh: Optional[Mesh] assert not isinstance(mesh, dict) - if mesh is None: - mesh = _get_mesh() + resolved_mesh = _resolve_mesh(mesh) - if mesh.empty: - return x + if resolved_mesh is None: + if not is_in_jit(): + warnings.warn("No mesh found. Not sharding.", RuntimeWarning) + return x + + if isinstance(resolved_mesh, AbstractMesh) and resolved_mesh.empty: + return x if is_in_jit() and is_on_mac_metal(): warnings.warn("Sharding constraints are not supported in jit on metal", RuntimeWarning) @@ -162,16 +214,11 @@ def shard(x: T, mapping: Optional[ResourceMapping] = None, mesh: Optional[Mesh] # could use eqx.partition to avoid this, but eh return named - sharding = infer_resource_partitions(named, mapping, mesh=mesh, preserve_existing_shardings=False) - assert isinstance(sharding, NamedSharding) - in_sharding = getattr(named.array, "sharding", None) + pspec = pspec_for(named, mapping, preserve_existing_shardings=False) + assert isinstance(pspec, PartitionSpec) + sharding = NamedSharding(resolved_mesh, pspec) if is_in_jit(): return with_sharding_constraint(named, sharding) - # as a special case, SingleDeviceShardings are routed through jit - elif isinstance(in_sharding, SingleDeviceSharding) and in_sharding._device in sharding.device_set: - # TODO(dlwh): this should be unnecessary in JAX soon. Check after 2024-08-01 - sharded_array = jax.jit(lambda x: x, out_shardings=sharding)(named) - return sharded_array else: ret = jax.device_put(named, sharding) return ret @@ -189,7 +236,6 @@ def pspec_for( tree: PyTree, resource_mapping: Optional[ResourceMapping] = None, preserve_existing_shardings: bool = True, - use_auto_sharding: bool = True, ) -> PyTree: """Infer the :class:`PartitionSpec` for a module. @@ -276,7 +322,6 @@ def infer_resource_partitions( tree: PyTree, resource_mapping: Optional[ResourceMapping] = None, preserve_existing_shardings: bool = True, - use_auto_sharding: bool = True, mesh: Optional[Mesh] = None, ) -> PyTree: """ @@ -291,11 +336,12 @@ def infer_resource_partitions( tree, resource_mapping=resource_mapping, preserve_existing_shardings=preserve_existing_shardings, - use_auto_sharding=use_auto_sharding, ) - mesh = mesh or _get_mesh() - assert not isinstance(mesh, dict) + resolved_mesh = _resolve_mesh(mesh) + if resolved_mesh is None: + raise ValueError("No mesh found") + assert not isinstance(resolved_mesh, dict) def to_sharding(node: typing.Any, spec: typing.Any): if spec is None: @@ -306,7 +352,7 @@ def infer_resource_partitions( else: return None else: - return NamedSharding(mesh, spec) + return NamedSharding(resolved_mesh, spec) return htu.tree_map(to_sharding, tree, pspecs) @@ -407,7 +453,7 @@ class _NamedJitWrapper(eqx.Module): if out_axis_resources is not None: # TODO: when AUTO is fixed (or eval_shape can give shardings), use it here out_resources = infer_resource_partitions( - output_shape, out_axis_resources, preserve_existing_shardings=False, use_auto_sharding=False + output_shape, out_axis_resources, preserve_existing_shardings=False ) my_pjit_args["out_shardings"] = out_resources @@ -642,7 +688,7 @@ def physical_axis_name(axis: AxisSelector, mapping: Optional[ResourceMapping] = def physical_axis_size(axis: AxisSelector, mapping: Optional[ResourceMapping] = None) -> Optional[int]: """Get the physical axis size for a logical axis. This is the product of the size of all physical axes that this logical axis is mapped to.""" - mesh = _get_mesh() + mesh = _resolve_mesh() if mesh is None: raise ValueError("No mesh found") @@ -659,10 +705,14 @@ def physical_axis_size(axis: AxisSelector, mapping: Optional[ResourceMapping] = def sharding_for_axis( - axis: AxisSelection, mapping: Optional[ResourceMapping] = None, mesh: Optional[Mesh] = None + axis: AxisSelection, mapping: Optional[ResourceMapping] = None, mesh: Optional[MeshLike] = None ) -> NamedSharding: """Get the sharding for a single axis""" - return NamedSharding(mesh or _get_mesh(), pspec_for_axis(axis, mapping)) + resolved_mesh = _resolve_mesh(mesh) + if resolved_mesh is None: + raise ValueError("No mesh found") + + return NamedSharding(resolved_mesh, pspec_for_axis(axis, mapping)) def pspec_for_axis(axis: AxisSelection, mapping: Optional[ResourceMapping] = None) -> PartitionSpec: @@ -681,28 +731,17 @@ def round_axis_for_partitioning(axis: Axis, mapping: Optional[ResourceMapping] = return Axis(axis.name, new_size) -def _get_mesh() -> Mesh | AbstractMesh: - """Return the current mesh. - - On newer versions of JAX this prefers ``get_abstract_mesh`` which does not - capture concrete devices. If no abstract mesh is currently active we fall - back to the concrete mesh used by ``Mesh``'s context manager so existing - code continues to work. - """ +def _get_mesh() -> Mesh | None: + """Deprecated helper that simply proxies to :func:`get_abstract_mesh`.""" - try: # jax>=0.4.26 - mesh = get_abstract_mesh() - if not getattr(mesh, "empty", False): - return mesh - except Exception: # pragma: no cover - older JAX versions - pass - - try: - from jax.interpreters.pxla import thread_resources - except Exception: # pragma: no cover - jax<0.4 - from jax.experimental.maps import thread_resources + warnings.warn( + "`_get_mesh` is deprecated; use `jax's get_abstract_mesh or get_concrete_mesh` instead", + DeprecationWarning, + stacklevel=2, + ) - return thread_resources.env.physical_mesh + mesh = _resolve_mesh() + return mesh def _is_jit_tracer(x) -> bool: diff --git a/tests/test_moe_linear.py b/tests/test_moe_linear.py index d34b76a..4fa84f1 100644 --- a/tests/test_moe_linear.py +++ b/tests/test_moe_linear.py @@ -66,8 +66,9 @@ def test_moe_linear_gmm_matches_ragged_dot_general(): x = hax.random.normal(jrandom.PRNGKey(1), (B, In)) group_sizes = hax.named(jnp.array([2, 1], dtype=jnp.int32), (E,)) - with jax.sharding.Mesh(jax.devices(), ("data",)): - actual = moe(x, group_sizes) + mesh = jax.sharding.Mesh(jax.devices(), ("data",)) + with hax.partitioning.set_mesh(mesh): + actual = hax.named_jit(moe)(x, group_sizes) expected = _expected_moe_linear_output(moe, x, group_sizes) diff --git a/tests/test_partitioning.py b/tests/test_partitioning.py index 4f8ceb2..b3e95c1 100644 --- a/tests/test_partitioning.py +++ b/tests/test_partitioning.py @@ -15,8 +15,8 @@ from haliax import Axis, NamedArray from haliax.partitioning import ( ResourceAxis, axis_mapping, - infer_resource_partitions, named_jit, + set_mesh, pspec_for, ) from test_utils import skip_if_not_enough_devices @@ -38,19 +38,6 @@ resource_map = { } -def test_infer_named_axes(): - mesh = Mesh(np.array(jax.devices()).reshape(-1, 1), (ResourceAxis.DATA, ResourceAxis.MODEL)) - with axis_mapping(resource_map), mesh: - mod = MyModule(named=hax.ones((Dim1, Dim2, Dim3)), unnamed1=jnp.ones(Dim2.size), static_field=1) - - axes: MyModule = infer_resource_partitions(mod, preserve_existing_shardings=False) - - spec = PartitionSpec(None, ResourceAxis.DATA, ResourceAxis.MODEL) - - assert axes.named == NamedSharding(mesh, spec) - assert axes.unnamed1.is_fully_replicated - - def test_pspec_for_named_axes(): mesh = Mesh(np.array(jax.devices()).reshape(-1, 1), (ResourceAxis.DATA, ResourceAxis.MODEL)) with axis_mapping(resource_map), mesh: @@ -109,7 +96,7 @@ class MyModuleInit(eqx.Module): def test_pjit_class_init(): with axis_mapping(resource_map): devices = jax.devices() - with Mesh(np.array(devices).reshape(-1, 2), (ResourceAxis.DATA, ResourceAxis.MODEL)): + with Mesh(np.array(devices).reshape(-1, 2), (ResourceAxis.DATA, ResourceAxis.MODEL)) as mesh, set_mesh(mesh): mod = named_jit(MyModuleInit)() assert mod.named.array.shape == (Dim2.size, Dim3.size) @@ -129,7 +116,7 @@ def test_pjit_class_nested_init(): self.inner = MyModuleInit() devices = jax.devices() - with Mesh(np.array(devices).reshape(-1, 2), (ResourceAxis.DATA, ResourceAxis.MODEL)): + with Mesh(np.array(devices).reshape(-1, 2), (ResourceAxis.DATA, ResourceAxis.MODEL)) as mesh, set_mesh(mesh): mod2 = named_jit(Mod2)() mod = mod2.inner @@ -150,7 +137,8 @@ def test_pjit_class_init_with_args(): self.array2 = hax.zeros(Dim3) devices = jax.devices() - with Mesh(np.array(devices).reshape(-1, 1), (ResourceAxis.DATA, ResourceAxis.MODEL)): + mesh = jax.make_mesh((len(devices), 1), (ResourceAxis.DATA, ResourceAxis.MODEL)) + with set_mesh(mesh): mod = named_jit(ModWithArgs)(hax.shard(hax.ones((Dim1, Dim2)))) assert isinstance(mod, ModWithArgs) assert mod.array.array.shape == (Dim1.size, Dim2.size) @@ -159,7 +147,7 @@ def test_pjit_class_init_with_args(): def test_infer_resource_partition_gda_bug(): devices = jax.devices() - with Mesh(np.array(devices).reshape(-1, 1), (ResourceAxis.DATA, ResourceAxis.MODEL)): + with Mesh(np.array(devices).reshape(-1, 1), (ResourceAxis.DATA, ResourceAxis.MODEL)) as mesh, set_mesh(mesh): def foo(): return hax.zeros((Dim1, Dim2, Dim3)) @@ -180,7 +168,7 @@ def test_infer_resource_partition_gda_bug(): @skip_if_not_enough_devices(4) def test_shard_with_axis_mapping_outside_pjit(): devices = jax.devices() - with Mesh(np.array(devices).reshape(-1, 2), (ResourceAxis.DATA, ResourceAxis.MODEL)) as mesh: + with Mesh(np.array(devices).reshape(-1, 2), (ResourceAxis.DATA, ResourceAxis.MODEL)) as mesh, set_mesh(mesh): x = hax.ones((Dim1, Dim2)) y = hax.ones((Dim2, Dim3)) @@ -193,7 +181,7 @@ def test_shard_with_axis_mapping_outside_pjit(): def test_named_jit_works_without_axis_resources(): devices = jax.devices() - with Mesh(np.array(devices).reshape(-1, 1), (ResourceAxis.DATA, ResourceAxis.MODEL)) as mesh: + with Mesh(np.array(devices).reshape(-1, 1), (ResourceAxis.DATA, ResourceAxis.MODEL)) as mesh, set_mesh(mesh): def foo(x): return x @@ -215,7 +203,7 @@ def test_named_jit_works_without_axis_resources(): @skip_if_not_enough_devices(4) def test_shard_with_axis_mapping_inside_jit(): devices = jax.devices() - with Mesh(np.array(devices).reshape(-1, 2), (ResourceAxis.DATA, ResourceAxis.MODEL)) as mesh: + with Mesh(np.array(devices).reshape(-1, 2), (ResourceAxis.DATA, ResourceAxis.MODEL)) as mesh, set_mesh(mesh): x = hax.ones((Dim1, Dim2)) y = hax.ones((Dim2, Dim3)) @@ -253,7 +241,7 @@ def test_shard_scalar_in_module(): ) devices = jax.devices() - with Mesh(np.array(devices).reshape(-1, 1), (ResourceAxis.DATA, ResourceAxis.MODEL)): + with Mesh(np.array(devices).reshape(-1, 1), (ResourceAxis.DATA, ResourceAxis.MODEL)) as mesh, set_mesh(mesh): mod = named_jit(MyModule)() assert mod.scalar.sharding.is_fully_replicated @@ -268,7 +256,7 @@ def test_shard_plain_array_in_module(): self.array = jnp.zeros((8, 8)) devices = jax.devices() - with Mesh(np.array(devices).reshape(-1, 1), (ResourceAxis.DATA, ResourceAxis.MODEL)): + with Mesh(np.array(devices).reshape(-1, 1), (ResourceAxis.DATA, ResourceAxis.MODEL)) as mesh, set_mesh(mesh): mod = named_jit(MyModule)() assert mod.array.sharding.is_fully_replicated @@ -281,7 +269,7 @@ def test_named_jit_with_donation(): array2: jnp.ndarray devices = jax.devices() - with Mesh(np.array(devices).reshape(-1, 1), (ResourceAxis.DATA, ResourceAxis.MODEL)): + with Mesh(np.array(devices).reshape(-1, 1), (ResourceAxis.DATA, ResourceAxis.MODEL)) as mesh, set_mesh(mesh): mod = named_jit(MyModule, donate_args=(True, False))(jnp.zeros((8, 8)), jnp.zeros((8, 16))) assert mod.array.sharding.is_fully_replicated @@ -301,7 +289,7 @@ def test_named_jit_with_donation_nested_pytrees(): return MyModule2(MyModule(a1, a2), MyModule(a1, a2)) devices = jax.devices() - with Mesh(np.array(devices).reshape(-1, 1), (ResourceAxis.DATA, ResourceAxis.MODEL)): + with Mesh(np.array(devices).reshape(-1, 1), (ResourceAxis.DATA, ResourceAxis.MODEL)) as mesh, set_mesh(mesh): mod = named_jit(init, donate_args=(True, False))(jnp.zeros((8, 8)), jnp.zeros((8, 16))) assert mod.mod.array.sharding.is_fully_replicated @@ -321,7 +309,7 @@ def test_jit_lower_doesnt_blow_up(): return MyModule2(MyModule(a1, a2), MyModule(a1, a2)) devices = jax.devices() - with Mesh(np.array(devices).reshape(-1, 1), (ResourceAxis.DATA, ResourceAxis.MODEL)): + with Mesh(np.array(devices).reshape(-1, 1), (ResourceAxis.DATA, ResourceAxis.MODEL)) as mesh, set_mesh(mesh): jit_init = named_jit(init, donate_args=(True, False)) lowered = jit_init.lower(jnp.zeros((8, 8)), jnp.zeros((8, 16))) assert lowered @@ -350,7 +338,7 @@ def test_cross_device_sharding(): def test_named_jit_no_in_axis_resources(): mesh = Mesh(np.array(jax.devices()).reshape(-1, 1), (ResourceAxis.DATA, ResourceAxis.MODEL)) - with axis_mapping(resource_map), mesh: + with axis_mapping(resource_map), set_mesh(mesh): class MyModule(eqx.Module): array: NamedArray diff --git a/tests/test_utils.py b/tests/test_utils.py index 2e6c396..ba85796 100644 --- a/tests/test_utils.py +++ b/tests/test_utils.py @@ -11,8 +11,11 @@ import pytest T = TypeVar("T") -def skip_if_not_enough_devices(count: int): - return pytest.mark.skipif(len(jax.devices()) < count, reason=f"Not enough devices ({len(jax.devices())})") +def skip_if_not_enough_devices(count: int, reason: str | None = None): + msg = f"Not enough devices ({len(jax.devices())})" + if reason: + msg += f": {reason}" + return pytest.mark.skipif(len(jax.devices()) < count, reason=msg) def has_torch(): diff --git a/tests/test_visualize_sharding.py b/tests/test_visualize_sharding.py index a8f11a8..79796ee 100644 --- a/tests/test_visualize_sharding.py +++ b/tests/test_visualize_sharding.py @@ -37,16 +37,19 @@ def test_visualize_shardings_runs(capsys): assert "dim1" in out and "dim2" in out and "dim3" in out +@skip_if_not_enough_devices(2, reason="JAX will claim it's unsharded if there's only one device") def test_visualize_shardings_inside_jit(capsys): mesh = jax.sharding.Mesh(np.array(jax.devices()).reshape(-1, 1), (ResourceAxis.DATA, ResourceAxis.MODEL)) - @named_jit(out_axis_resources={"dim1": ResourceAxis.DATA}) + @named_jit def fn(x): + x = hax.shard(x) visualize_shardings(x) return x with axis_mapping({"dim1": ResourceAxis.DATA}), mesh: - x = hax.ones(Dim1) + x = hax.ones({"dim1": 8 * len(jax.devices())}) + x = hax.shard(x) fn(x) out = capsys.readouterr().out diff --git a/uv.lock b/uv.lock index 53078e3..4741549 100644 --- a/uv.lock +++ b/uv.lock @@ -1,5 +1,5 @@ version = 1 -revision = 1 +revision = 3 requires-python = ">=3.10" resolution-markers = [ "python_full_version >= '3.13'", @@ -12,208 +12,247 @@ resolution-markers = [ name = "absl-py" version = "2.3.1" source = { registry = "https://pypi.org/simple" } -sdist = { url = "https://files.pythonhosted.org/packages/10/2a/c93173ffa1b39c1d0395b7e842bbdc62e556ca9d8d3b5572926f3e4ca752/absl_py-2.3.1.tar.gz", hash = "sha256:a97820526f7fbfd2ec1bce83f3f25e3a14840dac0d8e02a0b71cd75db3f77fc9", size = 116588 } +sdist = { url = "https://files.pythonhosted.org/packages/10/2a/c93173ffa1b39c1d0395b7e842bbdc62e556ca9d8d3b5572926f3e4ca752/absl_py-2.3.1.tar.gz", hash = "sha256:a97820526f7fbfd2ec1bce83f3f25e3a14840dac0d8e02a0b71cd75db3f77fc9", size = 116588, upload-time = "2025-07-03T09:31:44.05Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/8f/aa/ba0014cc4659328dc818a28827be78e6d97312ab0cb98105a770924dc11e/absl_py-2.3.1-py3-none-any.whl", hash = "sha256:eeecf07f0c2a93ace0772c92e596ace6d3d3996c042b2128459aaae2a76de11d", size = 135811 }, + { url = "https://files.pythonhosted.org/packages/8f/aa/ba0014cc4659328dc818a28827be78e6d97312ab0cb98105a770924dc11e/absl_py-2.3.1-py3-none-any.whl", hash = "sha256:eeecf07f0c2a93ace0772c92e596ace6d3d3996c042b2128459aaae2a76de11d", size = 135811, upload-time = "2025-07-03T09:31:42.253Z" }, +] + +[[package]] +name = "aiofiles" +version = "24.1.0" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/0b/03/a88171e277e8caa88a4c77808c20ebb04ba74cc4681bf1e9416c862de237/aiofiles-24.1.0.tar.gz", hash = "sha256:22a075c9e5a3810f0c2e48f3008c94d68c65d763b9b03857924c99e57355166c", size = 30247, upload-time = "2024-06-24T11:02:03.584Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/a5/45/30bb92d442636f570cb5651bc661f52b610e2eec3f891a5dc3a4c3667db0/aiofiles-24.1.0-py3-none-any.whl", hash = "sha256:b4ec55f4195e3eb5d7abd1bf7e061763e864dd4954231fb8539a0ef8bb8260e5", size = 15896, upload-time = "2024-06-24T11:02:01.529Z" }, ] [[package]] name = "aqtp" -version = "0.8.4" +version = "0.9.0" source = { registry = "https://pypi.org/simple" } dependencies = [ { name = "absl-py" }, - { name = "flax" }, - { name = "jax" }, - { name = "jaxlib" }, + { name = "flax", version = "0.10.7", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version < '3.11'" }, + { name = "flax", version = "0.12.0", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version >= '3.11'" }, + { name = "jax", version = "0.6.2", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version < '3.11'" }, + { name = "jax", version = "0.7.2", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version >= '3.11'" }, + { name = "jaxlib", version = "0.6.2", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version < '3.11'" }, + { name = "jaxlib", version = "0.7.2", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version >= '3.11'" }, ] -sdist = { url = "https://files.pythonhosted.org/packages/c3/29/efd4017ad572cca8453f17c2e6613a22bc5b1d8680a8c350d955570d3dba/aqtp-0.8.4.tar.gz", hash = "sha256:e3a887f0f78e3f5ce5ba1dfe57b4de074fd978054d3457217d92c90538654ba6", size = 884549 } +sdist = { url = "https://files.pythonhosted.org/packages/85/b2/028d15474268205dc2a7382759a51eb8903bd3a218a9d261874e2ec772a4/aqtp-0.9.0.tar.gz", hash = "sha256:a42f03f0de5ed54d0d0d9437741a44f6408eaed48103a3434f0ad405ff86874a", size = 885899, upload-time = "2025-08-01T17:54:59.738Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/81/dc/f15b71bdf6c20b362005c37e6d9d3ddf582cb00c57b01b2734299e699e35/aqtp-0.8.4-py3-none-any.whl", hash = "sha256:36c7b88973d7cb892fbaba95550383ef6c011943af6e3407a4c19d8f7682abdb", size = 900357 }, + { url = "https://files.pythonhosted.org/packages/48/96/32cb1e91e37f52967033101236190c44de3714666663e3c7e265454e1cc8/aqtp-0.9.0-py3-none-any.whl", hash = "sha256:5efdccd24657e149d3ac17599bb3d4eb88297fdc6aab14eaba0c70625057a257", size = 901643, upload-time = "2025-08-01T17:54:57.762Z" }, ] [[package]] name = "babel" version = "2.17.0" source = { registry = "https://pypi.org/simple" } -sdist = { url = "https://files.pythonhosted.org/packages/7d/6b/d52e42361e1aa00709585ecc30b3f9684b3ab62530771402248b1b1d6240/babel-2.17.0.tar.gz", hash = "sha256:0c54cffb19f690cdcc52a3b50bcbf71e07a808d1c80d549f2459b9d2cf0afb9d", size = 9951852 } +sdist = { url = "https://files.pythonhosted.org/packages/7d/6b/d52e42361e1aa00709585ecc30b3f9684b3ab62530771402248b1b1d6240/babel-2.17.0.tar.gz", hash = "sha256:0c54cffb19f690cdcc52a3b50bcbf71e07a808d1c80d549f2459b9d2cf0afb9d", size = 9951852, upload-time = "2025-02-01T15:17:41.026Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/b7/b8/3fe70c75fe32afc4bb507f75563d39bc5642255d1d94f1f23604725780bf/babel-2.17.0-py3-none-any.whl", hash = "sha256:4d0b53093fdfb4b21c92b5213dba5a1b23885afa8383709427046b21c366e5f2", size = 10182537 }, + { url = "https://files.pythonhosted.org/packages/b7/b8/3fe70c75fe32afc4bb507f75563d39bc5642255d1d94f1f23604725780bf/babel-2.17.0-py3-none-any.whl", hash = "sha256:4d0b53093fdfb4b21c92b5213dba5a1b23885afa8383709427046b21c366e5f2", size = 10182537, upload-time = "2025-02-01T15:17:37.39Z" }, ] [[package]] name = "backrefs" version = "5.9" source = { registry = "https://pypi.org/simple" } -sdist = { url = "https://files.pythonhosted.org/packages/eb/a7/312f673df6a79003279e1f55619abbe7daebbb87c17c976ddc0345c04c7b/backrefs-5.9.tar.gz", hash = "sha256:808548cb708d66b82ee231f962cb36faaf4f2baab032f2fbb783e9c2fdddaa59", size = 5765857 } +sdist = { url = "https://files.pythonhosted.org/packages/eb/a7/312f673df6a79003279e1f55619abbe7daebbb87c17c976ddc0345c04c7b/backrefs-5.9.tar.gz", hash = "sha256:808548cb708d66b82ee231f962cb36faaf4f2baab032f2fbb783e9c2fdddaa59", size = 5765857, upload-time = "2025-06-22T19:34:13.97Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/19/4d/798dc1f30468134906575156c089c492cf79b5a5fd373f07fe26c4d046bf/backrefs-5.9-py310-none-any.whl", hash = "sha256:db8e8ba0e9de81fcd635f440deab5ae5f2591b54ac1ebe0550a2ca063488cd9f", size = 380267 }, - { url = "https://files.pythonhosted.org/packages/55/07/f0b3375bf0d06014e9787797e6b7cc02b38ac9ff9726ccfe834d94e9991e/backrefs-5.9-py311-none-any.whl", hash = "sha256:6907635edebbe9b2dc3de3a2befff44d74f30a4562adbb8b36f21252ea19c5cf", size = 392072 }, - { url = "https://files.pythonhosted.org/packages/9d/12/4f345407259dd60a0997107758ba3f221cf89a9b5a0f8ed5b961aef97253/backrefs-5.9-py312-none-any.whl", hash = "sha256:7fdf9771f63e6028d7fee7e0c497c81abda597ea45d6b8f89e8ad76994f5befa", size = 397947 }, - { url = "https://files.pythonhosted.org/packages/10/bf/fa31834dc27a7f05e5290eae47c82690edc3a7b37d58f7fb35a1bdbf355b/backrefs-5.9-py313-none-any.whl", hash = "sha256:cc37b19fa219e93ff825ed1fed8879e47b4d89aa7a1884860e2db64ccd7c676b", size = 399843 }, - { url = "https://files.pythonhosted.org/packages/fc/24/b29af34b2c9c41645a9f4ff117bae860291780d73880f449e0b5d948c070/backrefs-5.9-py314-none-any.whl", hash = "sha256:df5e169836cc8acb5e440ebae9aad4bf9d15e226d3bad049cf3f6a5c20cc8dc9", size = 411762 }, - { url = "https://files.pythonhosted.org/packages/41/ff/392bff89415399a979be4a65357a41d92729ae8580a66073d8ec8d810f98/backrefs-5.9-py39-none-any.whl", hash = "sha256:f48ee18f6252b8f5777a22a00a09a85de0ca931658f1dd96d4406a34f3748c60", size = 380265 }, + { url = "https://files.pythonhosted.org/packages/19/4d/798dc1f30468134906575156c089c492cf79b5a5fd373f07fe26c4d046bf/backrefs-5.9-py310-none-any.whl", hash = "sha256:db8e8ba0e9de81fcd635f440deab5ae5f2591b54ac1ebe0550a2ca063488cd9f", size = 380267, upload-time = "2025-06-22T19:34:05.252Z" }, + { url = "https://files.pythonhosted.org/packages/55/07/f0b3375bf0d06014e9787797e6b7cc02b38ac9ff9726ccfe834d94e9991e/backrefs-5.9-py311-none-any.whl", hash = "sha256:6907635edebbe9b2dc3de3a2befff44d74f30a4562adbb8b36f21252ea19c5cf", size = 392072, upload-time = "2025-06-22T19:34:06.743Z" }, + { url = "https://files.pythonhosted.org/packages/9d/12/4f345407259dd60a0997107758ba3f221cf89a9b5a0f8ed5b961aef97253/backrefs-5.9-py312-none-any.whl", hash = "sha256:7fdf9771f63e6028d7fee7e0c497c81abda597ea45d6b8f89e8ad76994f5befa", size = 397947, upload-time = "2025-06-22T19:34:08.172Z" }, + { url = "https://files.pythonhosted.org/packages/10/bf/fa31834dc27a7f05e5290eae47c82690edc3a7b37d58f7fb35a1bdbf355b/backrefs-5.9-py313-none-any.whl", hash = "sha256:cc37b19fa219e93ff825ed1fed8879e47b4d89aa7a1884860e2db64ccd7c676b", size = 399843, upload-time = "2025-06-22T19:34:09.68Z" }, + { url = "https://files.pythonhosted.org/packages/fc/24/b29af34b2c9c41645a9f4ff117bae860291780d73880f449e0b5d948c070/backrefs-5.9-py314-none-any.whl", hash = "sha256:df5e169836cc8acb5e440ebae9aad4bf9d15e226d3bad049cf3f6a5c20cc8dc9", size = 411762, upload-time = "2025-06-22T19:34:11.037Z" }, + { url = "https://files.pythonhosted.org/packages/41/ff/392bff89415399a979be4a65357a41d92729ae8580a66073d8ec8d810f98/backrefs-5.9-py39-none-any.whl", hash = "sha256:f48ee18f6252b8f5777a22a00a09a85de0ca931658f1dd96d4406a34f3748c60", size = 380265, upload-time = "2025-06-22T19:34:12.405Z" }, ] [[package]] name = "bracex" version = "2.6" source = { registry = "https://pypi.org/simple" } -sdist = { url = "https://files.pythonhosted.org/packages/63/9a/fec38644694abfaaeca2798b58e276a8e61de49e2e37494ace423395febc/bracex-2.6.tar.gz", hash = "sha256:98f1347cd77e22ee8d967a30ad4e310b233f7754dbf31ff3fceb76145ba47dc7", size = 26642 } +sdist = { url = "https://files.pythonhosted.org/packages/63/9a/fec38644694abfaaeca2798b58e276a8e61de49e2e37494ace423395febc/bracex-2.6.tar.gz", hash = "sha256:98f1347cd77e22ee8d967a30ad4e310b233f7754dbf31ff3fceb76145ba47dc7", size = 26642, upload-time = "2025-06-22T19:12:31.254Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/9d/2a/9186535ce58db529927f6cf5990a849aa9e052eea3e2cfefe20b9e1802da/bracex-2.6-py3-none-any.whl", hash = "sha256:0b0049264e7340b3ec782b5cb99beb325f36c3782a32e36e876452fd49a09952", size = 11508 }, + { url = "https://files.pythonhosted.org/packages/9d/2a/9186535ce58db529927f6cf5990a849aa9e052eea3e2cfefe20b9e1802da/bracex-2.6-py3-none-any.whl", hash = "sha256:0b0049264e7340b3ec782b5cb99beb325f36c3782a32e36e876452fd49a09952", size = 11508, upload-time = "2025-06-22T19:12:29.781Z" }, ] [[package]] name = "certifi" -version = "2025.6.15" +version = "2025.8.3" source = { registry = "https://pypi.org/simple" } -sdist = { url = "https://files.pythonhosted.org/packages/73/f7/f14b46d4bcd21092d7d3ccef689615220d8a08fb25e564b65d20738e672e/certifi-2025.6.15.tar.gz", hash = "sha256:d747aa5a8b9bbbb1bb8c22bb13e22bd1f18e9796defa16bab421f7f7a317323b", size = 158753 } +sdist = { url = "https://files.pythonhosted.org/packages/dc/67/960ebe6bf230a96cda2e0abcf73af550ec4f090005363542f0765df162e0/certifi-2025.8.3.tar.gz", hash = "sha256:e564105f78ded564e3ae7c923924435e1daa7463faeab5bb932bc53ffae63407", size = 162386, upload-time = "2025-08-03T03:07:47.08Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/84/ae/320161bd181fc06471eed047ecce67b693fd7515b16d495d8932db763426/certifi-2025.6.15-py3-none-any.whl", hash = "sha256:2e0c7ce7cb5d8f8634ca55d2ba7e6ec2689a2fd6537d8dec1296a477a4910057", size = 157650 }, + { url = "https://files.pythonhosted.org/packages/e5/48/1549795ba7742c948d2ad169c1c8cdbae65bc450d6cd753d124b17c8cd32/certifi-2025.8.3-py3-none-any.whl", hash = "sha256:f6c12493cfb1b06ba2ff328595af9350c65d6644968e5d3a2ffd78699af217a5", size = 161216, upload-time = "2025-08-03T03:07:45.777Z" }, ] [[package]] name = "cfgv" version = "3.4.0" source = { registry = "https://pypi.org/simple" } -sdist = { url = "https://files.pythonhosted.org/packages/11/74/539e56497d9bd1d484fd863dd69cbbfa653cd2aa27abfe35653494d85e94/cfgv-3.4.0.tar.gz", hash = "sha256:e52591d4c5f5dead8e0f673fb16db7949d2cfb3f7da4582893288f0ded8fe560", size = 7114 } +sdist = { url = "https://files.pythonhosted.org/packages/11/74/539e56497d9bd1d484fd863dd69cbbfa653cd2aa27abfe35653494d85e94/cfgv-3.4.0.tar.gz", hash = "sha256:e52591d4c5f5dead8e0f673fb16db7949d2cfb3f7da4582893288f0ded8fe560", size = 7114, upload-time = "2023-08-12T20:38:17.776Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/c5/55/51844dd50c4fc7a33b653bfaba4c2456f06955289ca770a5dbd5fd267374/cfgv-3.4.0-py2.py3-none-any.whl", hash = "sha256:b7265b1f29fd3316bfcd2b330d63d024f2bfd8bcb8b0272f8e19a504856c48f9", size = 7249 }, + { url = "https://files.pythonhosted.org/packages/c5/55/51844dd50c4fc7a33b653bfaba4c2456f06955289ca770a5dbd5fd267374/cfgv-3.4.0-py2.py3-none-any.whl", hash = "sha256:b7265b1f29fd3316bfcd2b330d63d024f2bfd8bcb8b0272f8e19a504856c48f9", size = 7249, upload-time = "2023-08-12T20:38:16.269Z" }, ] [[package]] name = "charset-normalizer" -version = "3.4.2" -source = { registry = "https://pypi.org/simple" } -sdist = { url = "https://files.pythonhosted.org/packages/e4/33/89c2ced2b67d1c2a61c19c6751aa8902d46ce3dacb23600a283619f5a12d/charset_normalizer-3.4.2.tar.gz", hash = "sha256:5baececa9ecba31eff645232d59845c07aa030f0c81ee70184a90d35099a0e63", size = 126367 } -wheels = [ - { url = "https://files.pythonhosted.org/packages/95/28/9901804da60055b406e1a1c5ba7aac1276fb77f1dde635aabfc7fd84b8ab/charset_normalizer-3.4.2-cp310-cp310-macosx_10_9_universal2.whl", hash = "sha256:7c48ed483eb946e6c04ccbe02c6b4d1d48e51944b6db70f697e089c193404941", size = 201818 }, - { url = "https://files.pythonhosted.org/packages/d9/9b/892a8c8af9110935e5adcbb06d9c6fe741b6bb02608c6513983048ba1a18/charset_normalizer-3.4.2-cp310-cp310-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:b2d318c11350e10662026ad0eb71bb51c7812fc8590825304ae0bdd4ac283acd", size = 144649 }, - { url = "https://files.pythonhosted.org/packages/7b/a5/4179abd063ff6414223575e008593861d62abfc22455b5d1a44995b7c101/charset_normalizer-3.4.2-cp310-cp310-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:9cbfacf36cb0ec2897ce0ebc5d08ca44213af24265bd56eca54bee7923c48fd6", size = 155045 }, - { url = "https://files.pythonhosted.org/packages/3b/95/bc08c7dfeddd26b4be8c8287b9bb055716f31077c8b0ea1cd09553794665/charset_normalizer-3.4.2-cp310-cp310-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:18dd2e350387c87dabe711b86f83c9c78af772c748904d372ade190b5c7c9d4d", size = 147356 }, - { url = "https://files.pythonhosted.org/packages/a8/2d/7a5b635aa65284bf3eab7653e8b4151ab420ecbae918d3e359d1947b4d61/charset_normalizer-3.4.2-cp310-cp310-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:8075c35cd58273fee266c58c0c9b670947c19df5fb98e7b66710e04ad4e9ff86", size = 149471 }, - { url = "https://files.pythonhosted.org/packages/ae/38/51fc6ac74251fd331a8cfdb7ec57beba8c23fd5493f1050f71c87ef77ed0/charset_normalizer-3.4.2-cp310-cp310-manylinux_2_5_i686.manylinux1_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:5bf4545e3b962767e5c06fe1738f951f77d27967cb2caa64c28be7c4563e162c", size = 151317 }, - { url = "https://files.pythonhosted.org/packages/b7/17/edee1e32215ee6e9e46c3e482645b46575a44a2d72c7dfd49e49f60ce6bf/charset_normalizer-3.4.2-cp310-cp310-musllinux_1_2_aarch64.whl", hash = "sha256:7a6ab32f7210554a96cd9e33abe3ddd86732beeafc7a28e9955cdf22ffadbab0", size = 146368 }, - { url = "https://files.pythonhosted.org/packages/26/2c/ea3e66f2b5f21fd00b2825c94cafb8c326ea6240cd80a91eb09e4a285830/charset_normalizer-3.4.2-cp310-cp310-musllinux_1_2_i686.whl", hash = "sha256:b33de11b92e9f75a2b545d6e9b6f37e398d86c3e9e9653c4864eb7e89c5773ef", size = 154491 }, - { url = "https://files.pythonhosted.org/packages/52/47/7be7fa972422ad062e909fd62460d45c3ef4c141805b7078dbab15904ff7/charset_normalizer-3.4.2-cp310-cp310-musllinux_1_2_ppc64le.whl", hash = "sha256:8755483f3c00d6c9a77f490c17e6ab0c8729e39e6390328e42521ef175380ae6", size = 157695 }, - { url = "https://files.pythonhosted.org/packages/2f/42/9f02c194da282b2b340f28e5fb60762de1151387a36842a92b533685c61e/charset_normalizer-3.4.2-cp310-cp310-musllinux_1_2_s390x.whl", hash = "sha256:68a328e5f55ec37c57f19ebb1fdc56a248db2e3e9ad769919a58672958e8f366", size = 154849 }, - { url = "https://files.pythonhosted.org/packages/67/44/89cacd6628f31fb0b63201a618049be4be2a7435a31b55b5eb1c3674547a/charset_normalizer-3.4.2-cp310-cp310-musllinux_1_2_x86_64.whl", hash = "sha256:21b2899062867b0e1fde9b724f8aecb1af14f2778d69aacd1a5a1853a597a5db", size = 150091 }, - { url = "https://files.pythonhosted.org/packages/1f/79/4b8da9f712bc079c0f16b6d67b099b0b8d808c2292c937f267d816ec5ecc/charset_normalizer-3.4.2-cp310-cp310-win32.whl", hash = "sha256:e8082b26888e2f8b36a042a58307d5b917ef2b1cacab921ad3323ef91901c71a", size = 98445 }, - { url = "https://files.pythonhosted.org/packages/7d/d7/96970afb4fb66497a40761cdf7bd4f6fca0fc7bafde3a84f836c1f57a926/charset_normalizer-3.4.2-cp310-cp310-win_amd64.whl", hash = "sha256:f69a27e45c43520f5487f27627059b64aaf160415589230992cec34c5e18a509", size = 105782 }, - { url = "https://files.pythonhosted.org/packages/05/85/4c40d00dcc6284a1c1ad5de5e0996b06f39d8232f1031cd23c2f5c07ee86/charset_normalizer-3.4.2-cp311-cp311-macosx_10_9_universal2.whl", hash = "sha256:be1e352acbe3c78727a16a455126d9ff83ea2dfdcbc83148d2982305a04714c2", size = 198794 }, - { url = "https://files.pythonhosted.org/packages/41/d9/7a6c0b9db952598e97e93cbdfcb91bacd89b9b88c7c983250a77c008703c/charset_normalizer-3.4.2-cp311-cp311-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:aa88ca0b1932e93f2d961bf3addbb2db902198dca337d88c89e1559e066e7645", size = 142846 }, - { url = "https://files.pythonhosted.org/packages/66/82/a37989cda2ace7e37f36c1a8ed16c58cf48965a79c2142713244bf945c89/charset_normalizer-3.4.2-cp311-cp311-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:d524ba3f1581b35c03cb42beebab4a13e6cdad7b36246bd22541fa585a56cccd", size = 153350 }, - { url = "https://files.pythonhosted.org/packages/df/68/a576b31b694d07b53807269d05ec3f6f1093e9545e8607121995ba7a8313/charset_normalizer-3.4.2-cp311-cp311-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:28a1005facc94196e1fb3e82a3d442a9d9110b8434fc1ded7a24a2983c9888d8", size = 145657 }, - { url = "https://files.pythonhosted.org/packages/92/9b/ad67f03d74554bed3aefd56fe836e1623a50780f7c998d00ca128924a499/charset_normalizer-3.4.2-cp311-cp311-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:fdb20a30fe1175ecabed17cbf7812f7b804b8a315a25f24678bcdf120a90077f", size = 147260 }, - { url = "https://files.pythonhosted.org/packages/a6/e6/8aebae25e328160b20e31a7e9929b1578bbdc7f42e66f46595a432f8539e/charset_normalizer-3.4.2-cp311-cp311-manylinux_2_5_i686.manylinux1_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:0f5d9ed7f254402c9e7d35d2f5972c9bbea9040e99cd2861bd77dc68263277c7", size = 149164 }, - { url = "https://files.pythonhosted.org/packages/8b/f2/b3c2f07dbcc248805f10e67a0262c93308cfa149a4cd3d1fe01f593e5fd2/charset_normalizer-3.4.2-cp311-cp311-musllinux_1_2_aarch64.whl", hash = "sha256:efd387a49825780ff861998cd959767800d54f8308936b21025326de4b5a42b9", size = 144571 }, - { url = "https://files.pythonhosted.org/packages/60/5b/c3f3a94bc345bc211622ea59b4bed9ae63c00920e2e8f11824aa5708e8b7/charset_normalizer-3.4.2-cp311-cp311-musllinux_1_2_i686.whl", hash = "sha256:f0aa37f3c979cf2546b73e8222bbfa3dc07a641585340179d768068e3455e544", size = 151952 }, - { url = "https://files.pythonhosted.org/packages/e2/4d/ff460c8b474122334c2fa394a3f99a04cf11c646da895f81402ae54f5c42/charset_normalizer-3.4.2-cp311-cp311-musllinux_1_2_ppc64le.whl", hash = "sha256:e70e990b2137b29dc5564715de1e12701815dacc1d056308e2b17e9095372a82", size = 155959 }, - { url = "https://files.pythonhosted.org/packages/a2/2b/b964c6a2fda88611a1fe3d4c400d39c66a42d6c169c924818c848f922415/charset_normalizer-3.4.2-cp311-cp311-musllinux_1_2_s390x.whl", hash = "sha256:0c8c57f84ccfc871a48a47321cfa49ae1df56cd1d965a09abe84066f6853b9c0", size = 153030 }, - { url = "https://files.pythonhosted.org/packages/59/2e/d3b9811db26a5ebf444bc0fa4f4be5aa6d76fc6e1c0fd537b16c14e849b6/charset_normalizer-3.4.2-cp311-cp311-musllinux_1_2_x86_64.whl", hash = "sha256:6b66f92b17849b85cad91259efc341dce9c1af48e2173bf38a85c6329f1033e5", size = 148015 }, - { url = "https://files.pythonhosted.org/packages/90/07/c5fd7c11eafd561bb51220d600a788f1c8d77c5eef37ee49454cc5c35575/charset_normalizer-3.4.2-cp311-cp311-win32.whl", hash = "sha256:daac4765328a919a805fa5e2720f3e94767abd632ae410a9062dff5412bae65a", size = 98106 }, - { url = "https://files.pythonhosted.org/packages/a8/05/5e33dbef7e2f773d672b6d79f10ec633d4a71cd96db6673625838a4fd532/charset_normalizer-3.4.2-cp311-cp311-win_amd64.whl", hash = "sha256:e53efc7c7cee4c1e70661e2e112ca46a575f90ed9ae3fef200f2a25e954f4b28", size = 105402 }, - { url = "https://files.pythonhosted.org/packages/d7/a4/37f4d6035c89cac7930395a35cc0f1b872e652eaafb76a6075943754f095/charset_normalizer-3.4.2-cp312-cp312-macosx_10_13_universal2.whl", hash = "sha256:0c29de6a1a95f24b9a1aa7aefd27d2487263f00dfd55a77719b530788f75cff7", size = 199936 }, - { url = "https://files.pythonhosted.org/packages/ee/8a/1a5e33b73e0d9287274f899d967907cd0bf9c343e651755d9307e0dbf2b3/charset_normalizer-3.4.2-cp312-cp312-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:cddf7bd982eaa998934a91f69d182aec997c6c468898efe6679af88283b498d3", size = 143790 }, - { url = "https://files.pythonhosted.org/packages/66/52/59521f1d8e6ab1482164fa21409c5ef44da3e9f653c13ba71becdd98dec3/charset_normalizer-3.4.2-cp312-cp312-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:fcbe676a55d7445b22c10967bceaaf0ee69407fbe0ece4d032b6eb8d4565982a", size = 153924 }, - { url = "https://files.pythonhosted.org/packages/86/2d/fb55fdf41964ec782febbf33cb64be480a6b8f16ded2dbe8db27a405c09f/charset_normalizer-3.4.2-cp312-cp312-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:d41c4d287cfc69060fa91cae9683eacffad989f1a10811995fa309df656ec214", size = 146626 }, - { url = "https://files.pythonhosted.org/packages/8c/73/6ede2ec59bce19b3edf4209d70004253ec5f4e319f9a2e3f2f15601ed5f7/charset_normalizer-3.4.2-cp312-cp312-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:4e594135de17ab3866138f496755f302b72157d115086d100c3f19370839dd3a", size = 148567 }, - { url = "https://files.pythonhosted.org/packages/09/14/957d03c6dc343c04904530b6bef4e5efae5ec7d7990a7cbb868e4595ee30/charset_normalizer-3.4.2-cp312-cp312-manylinux_2_5_i686.manylinux1_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:cf713fe9a71ef6fd5adf7a79670135081cd4431c2943864757f0fa3a65b1fafd", size = 150957 }, - { url = "https://files.pythonhosted.org/packages/0d/c8/8174d0e5c10ccebdcb1b53cc959591c4c722a3ad92461a273e86b9f5a302/charset_normalizer-3.4.2-cp312-cp312-musllinux_1_2_aarch64.whl", hash = "sha256:a370b3e078e418187da8c3674eddb9d983ec09445c99a3a263c2011993522981", size = 145408 }, - { url = "https://files.pythonhosted.org/packages/58/aa/8904b84bc8084ac19dc52feb4f5952c6df03ffb460a887b42615ee1382e8/charset_normalizer-3.4.2-cp312-cp312-musllinux_1_2_i686.whl", hash = "sha256:a955b438e62efdf7e0b7b52a64dc5c3396e2634baa62471768a64bc2adb73d5c", size = 153399 }, - { url = "https://files.pythonhosted.org/packages/c2/26/89ee1f0e264d201cb65cf054aca6038c03b1a0c6b4ae998070392a3ce605/charset_normalizer-3.4.2-cp312-cp312-musllinux_1_2_ppc64le.whl", hash = "sha256:7222ffd5e4de8e57e03ce2cef95a4c43c98fcb72ad86909abdfc2c17d227fc1b", size = 156815 }, - { url = "https://files.pythonhosted.org/packages/fd/07/68e95b4b345bad3dbbd3a8681737b4338ff2c9df29856a6d6d23ac4c73cb/charset_normalizer-3.4.2-cp312-cp312-musllinux_1_2_s390x.whl", hash = "sha256:bee093bf902e1d8fc0ac143c88902c3dfc8941f7ea1d6a8dd2bcb786d33db03d", size = 154537 }, - { url = "https://files.pythonhosted.org/packages/77/1a/5eefc0ce04affb98af07bc05f3bac9094513c0e23b0562d64af46a06aae4/charset_normalizer-3.4.2-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:dedb8adb91d11846ee08bec4c8236c8549ac721c245678282dcb06b221aab59f", size = 149565 }, - { url = "https://files.pythonhosted.org/packages/37/a0/2410e5e6032a174c95e0806b1a6585eb21e12f445ebe239fac441995226a/charset_normalizer-3.4.2-cp312-cp312-win32.whl", hash = "sha256:db4c7bf0e07fc3b7d89ac2a5880a6a8062056801b83ff56d8464b70f65482b6c", size = 98357 }, - { url = "https://files.pythonhosted.org/packages/6c/4f/c02d5c493967af3eda9c771ad4d2bbc8df6f99ddbeb37ceea6e8716a32bc/charset_normalizer-3.4.2-cp312-cp312-win_amd64.whl", hash = "sha256:5a9979887252a82fefd3d3ed2a8e3b937a7a809f65dcb1e068b090e165bbe99e", size = 105776 }, - { url = "https://files.pythonhosted.org/packages/ea/12/a93df3366ed32db1d907d7593a94f1fe6293903e3e92967bebd6950ed12c/charset_normalizer-3.4.2-cp313-cp313-macosx_10_13_universal2.whl", hash = "sha256:926ca93accd5d36ccdabd803392ddc3e03e6d4cd1cf17deff3b989ab8e9dbcf0", size = 199622 }, - { url = "https://files.pythonhosted.org/packages/04/93/bf204e6f344c39d9937d3c13c8cd5bbfc266472e51fc8c07cb7f64fcd2de/charset_normalizer-3.4.2-cp313-cp313-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:eba9904b0f38a143592d9fc0e19e2df0fa2e41c3c3745554761c5f6447eedabf", size = 143435 }, - { url = "https://files.pythonhosted.org/packages/22/2a/ea8a2095b0bafa6c5b5a55ffdc2f924455233ee7b91c69b7edfcc9e02284/charset_normalizer-3.4.2-cp313-cp313-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:3fddb7e2c84ac87ac3a947cb4e66d143ca5863ef48e4a5ecb83bd48619e4634e", size = 153653 }, - { url = "https://files.pythonhosted.org/packages/b6/57/1b090ff183d13cef485dfbe272e2fe57622a76694061353c59da52c9a659/charset_normalizer-3.4.2-cp313-cp313-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:98f862da73774290f251b9df8d11161b6cf25b599a66baf087c1ffe340e9bfd1", size = 146231 }, - { url = "https://files.pythonhosted.org/packages/e2/28/ffc026b26f441fc67bd21ab7f03b313ab3fe46714a14b516f931abe1a2d8/charset_normalizer-3.4.2-cp313-cp313-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:6c9379d65defcab82d07b2a9dfbfc2e95bc8fe0ebb1b176a3190230a3ef0e07c", size = 148243 }, - { url = "https://files.pythonhosted.org/packages/c0/0f/9abe9bd191629c33e69e47c6ef45ef99773320e9ad8e9cb08b8ab4a8d4cb/charset_normalizer-3.4.2-cp313-cp313-manylinux_2_5_i686.manylinux1_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:e635b87f01ebc977342e2697d05b56632f5f879a4f15955dfe8cef2448b51691", size = 150442 }, - { url = "https://files.pythonhosted.org/packages/67/7c/a123bbcedca91d5916c056407f89a7f5e8fdfce12ba825d7d6b9954a1a3c/charset_normalizer-3.4.2-cp313-cp313-musllinux_1_2_aarch64.whl", hash = "sha256:1c95a1e2902a8b722868587c0e1184ad5c55631de5afc0eb96bc4b0d738092c0", size = 145147 }, - { url = "https://files.pythonhosted.org/packages/ec/fe/1ac556fa4899d967b83e9893788e86b6af4d83e4726511eaaad035e36595/charset_normalizer-3.4.2-cp313-cp313-musllinux_1_2_i686.whl", hash = "sha256:ef8de666d6179b009dce7bcb2ad4c4a779f113f12caf8dc77f0162c29d20490b", size = 153057 }, - { url = "https://files.pythonhosted.org/packages/2b/ff/acfc0b0a70b19e3e54febdd5301a98b72fa07635e56f24f60502e954c461/charset_normalizer-3.4.2-cp313-cp313-musllinux_1_2_ppc64le.whl", hash = "sha256:32fc0341d72e0f73f80acb0a2c94216bd704f4f0bce10aedea38f30502b271ff", size = 156454 }, - { url = "https://files.pythonhosted.org/packages/92/08/95b458ce9c740d0645feb0e96cea1f5ec946ea9c580a94adfe0b617f3573/charset_normalizer-3.4.2-cp313-cp313-musllinux_1_2_s390x.whl", hash = "sha256:289200a18fa698949d2b39c671c2cc7a24d44096784e76614899a7ccf2574b7b", size = 154174 }, - { url = "https://files.pythonhosted.org/packages/78/be/8392efc43487ac051eee6c36d5fbd63032d78f7728cb37aebcc98191f1ff/charset_normalizer-3.4.2-cp313-cp313-musllinux_1_2_x86_64.whl", hash = "sha256:4a476b06fbcf359ad25d34a057b7219281286ae2477cc5ff5e3f70a246971148", size = 149166 }, - { url = "https://files.pythonhosted.org/packages/44/96/392abd49b094d30b91d9fbda6a69519e95802250b777841cf3bda8fe136c/charset_normalizer-3.4.2-cp313-cp313-win32.whl", hash = "sha256:aaeeb6a479c7667fbe1099af9617c83aaca22182d6cf8c53966491a0f1b7ffb7", size = 98064 }, - { url = "https://files.pythonhosted.org/packages/e9/b0/0200da600134e001d91851ddc797809e2fe0ea72de90e09bec5a2fbdaccb/charset_normalizer-3.4.2-cp313-cp313-win_amd64.whl", hash = "sha256:aa6af9e7d59f9c12b33ae4e9450619cf2488e2bbe9b44030905877f0b2324980", size = 105641 }, - { url = "https://files.pythonhosted.org/packages/20/94/c5790835a017658cbfabd07f3bfb549140c3ac458cfc196323996b10095a/charset_normalizer-3.4.2-py3-none-any.whl", hash = "sha256:7f56930ab0abd1c45cd15be65cc741c28b1c9a34876ce8c17a2fa107810c0af0", size = 52626 }, +version = "3.4.3" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/83/2d/5fd176ceb9b2fc619e63405525573493ca23441330fcdaee6bef9460e924/charset_normalizer-3.4.3.tar.gz", hash = "sha256:6fce4b8500244f6fcb71465d4a4930d132ba9ab8e71a7859e6a5d59851068d14", size = 122371, upload-time = "2025-08-09T07:57:28.46Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/d6/98/f3b8013223728a99b908c9344da3aa04ee6e3fa235f19409033eda92fb78/charset_normalizer-3.4.3-cp310-cp310-macosx_10_9_universal2.whl", hash = "sha256:fb7f67a1bfa6e40b438170ebdc8158b78dc465a5a67b6dde178a46987b244a72", size = 207695, upload-time = "2025-08-09T07:55:36.452Z" }, + { url = "https://files.pythonhosted.org/packages/21/40/5188be1e3118c82dcb7c2a5ba101b783822cfb413a0268ed3be0468532de/charset_normalizer-3.4.3-cp310-cp310-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:cc9370a2da1ac13f0153780040f465839e6cccb4a1e44810124b4e22483c93fe", size = 147153, upload-time = "2025-08-09T07:55:38.467Z" }, + { url = "https://files.pythonhosted.org/packages/37/60/5d0d74bc1e1380f0b72c327948d9c2aca14b46a9efd87604e724260f384c/charset_normalizer-3.4.3-cp310-cp310-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:07a0eae9e2787b586e129fdcbe1af6997f8d0e5abaa0bc98c0e20e124d67e601", size = 160428, upload-time = "2025-08-09T07:55:40.072Z" }, + { url = "https://files.pythonhosted.org/packages/85/9a/d891f63722d9158688de58d050c59dc3da560ea7f04f4c53e769de5140f5/charset_normalizer-3.4.3-cp310-cp310-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:74d77e25adda8581ffc1c720f1c81ca082921329452eba58b16233ab1842141c", size = 157627, upload-time = "2025-08-09T07:55:41.706Z" }, + { url = "https://files.pythonhosted.org/packages/65/1a/7425c952944a6521a9cfa7e675343f83fd82085b8af2b1373a2409c683dc/charset_normalizer-3.4.3-cp310-cp310-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:d0e909868420b7049dafd3a31d45125b31143eec59235311fc4c57ea26a4acd2", size = 152388, upload-time = "2025-08-09T07:55:43.262Z" }, + { url = "https://files.pythonhosted.org/packages/f0/c9/a2c9c2a355a8594ce2446085e2ec97fd44d323c684ff32042e2a6b718e1d/charset_normalizer-3.4.3-cp310-cp310-musllinux_1_2_aarch64.whl", hash = "sha256:c6f162aabe9a91a309510d74eeb6507fab5fff92337a15acbe77753d88d9dcf0", size = 150077, upload-time = "2025-08-09T07:55:44.903Z" }, + { url = "https://files.pythonhosted.org/packages/3b/38/20a1f44e4851aa1c9105d6e7110c9d020e093dfa5836d712a5f074a12bf7/charset_normalizer-3.4.3-cp310-cp310-musllinux_1_2_ppc64le.whl", hash = "sha256:4ca4c094de7771a98d7fbd67d9e5dbf1eb73efa4f744a730437d8a3a5cf994f0", size = 161631, upload-time = "2025-08-09T07:55:46.346Z" }, + { url = "https://files.pythonhosted.org/packages/a4/fa/384d2c0f57edad03d7bec3ebefb462090d8905b4ff5a2d2525f3bb711fac/charset_normalizer-3.4.3-cp310-cp310-musllinux_1_2_s390x.whl", hash = "sha256:02425242e96bcf29a49711b0ca9f37e451da7c70562bc10e8ed992a5a7a25cc0", size = 159210, upload-time = "2025-08-09T07:55:47.539Z" }, + { url = "https://files.pythonhosted.org/packages/33/9e/eca49d35867ca2db336b6ca27617deed4653b97ebf45dfc21311ce473c37/charset_normalizer-3.4.3-cp310-cp310-musllinux_1_2_x86_64.whl", hash = "sha256:78deba4d8f9590fe4dae384aeff04082510a709957e968753ff3c48399f6f92a", size = 153739, upload-time = "2025-08-09T07:55:48.744Z" }, + { url = "https://files.pythonhosted.org/packages/2a/91/26c3036e62dfe8de8061182d33be5025e2424002125c9500faff74a6735e/charset_normalizer-3.4.3-cp310-cp310-win32.whl", hash = "sha256:d79c198e27580c8e958906f803e63cddb77653731be08851c7df0b1a14a8fc0f", size = 99825, upload-time = "2025-08-09T07:55:50.305Z" }, + { url = "https://files.pythonhosted.org/packages/e2/c6/f05db471f81af1fa01839d44ae2a8bfeec8d2a8b4590f16c4e7393afd323/charset_normalizer-3.4.3-cp310-cp310-win_amd64.whl", hash = "sha256:c6e490913a46fa054e03699c70019ab869e990270597018cef1d8562132c2669", size = 107452, upload-time = "2025-08-09T07:55:51.461Z" }, + { url = "https://files.pythonhosted.org/packages/7f/b5/991245018615474a60965a7c9cd2b4efbaabd16d582a5547c47ee1c7730b/charset_normalizer-3.4.3-cp311-cp311-macosx_10_9_universal2.whl", hash = "sha256:b256ee2e749283ef3ddcff51a675ff43798d92d746d1a6e4631bf8c707d22d0b", size = 204483, upload-time = "2025-08-09T07:55:53.12Z" }, + { url = "https://files.pythonhosted.org/packages/c7/2a/ae245c41c06299ec18262825c1569c5d3298fc920e4ddf56ab011b417efd/charset_normalizer-3.4.3-cp311-cp311-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:13faeacfe61784e2559e690fc53fa4c5ae97c6fcedb8eb6fb8d0a15b475d2c64", size = 145520, upload-time = "2025-08-09T07:55:54.712Z" }, + { url = "https://files.pythonhosted.org/packages/3a/a4/b3b6c76e7a635748c4421d2b92c7b8f90a432f98bda5082049af37ffc8e3/charset_normalizer-3.4.3-cp311-cp311-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:00237675befef519d9af72169d8604a067d92755e84fe76492fef5441db05b91", size = 158876, upload-time = "2025-08-09T07:55:56.024Z" }, + { url = "https://files.pythonhosted.org/packages/e2/e6/63bb0e10f90a8243c5def74b5b105b3bbbfb3e7bb753915fe333fb0c11ea/charset_normalizer-3.4.3-cp311-cp311-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:585f3b2a80fbd26b048a0be90c5aae8f06605d3c92615911c3a2b03a8a3b796f", size = 156083, upload-time = "2025-08-09T07:55:57.582Z" }, + { url = "https://files.pythonhosted.org/packages/87/df/b7737ff046c974b183ea9aa111b74185ac8c3a326c6262d413bd5a1b8c69/charset_normalizer-3.4.3-cp311-cp311-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:0e78314bdc32fa80696f72fa16dc61168fda4d6a0c014e0380f9d02f0e5d8a07", size = 150295, upload-time = "2025-08-09T07:55:59.147Z" }, + { url = "https://files.pythonhosted.org/packages/61/f1/190d9977e0084d3f1dc169acd060d479bbbc71b90bf3e7bf7b9927dec3eb/charset_normalizer-3.4.3-cp311-cp311-musllinux_1_2_aarch64.whl", hash = "sha256:96b2b3d1a83ad55310de8c7b4a2d04d9277d5591f40761274856635acc5fcb30", size = 148379, upload-time = "2025-08-09T07:56:00.364Z" }, + { url = "https://files.pythonhosted.org/packages/4c/92/27dbe365d34c68cfe0ca76f1edd70e8705d82b378cb54ebbaeabc2e3029d/charset_normalizer-3.4.3-cp311-cp311-musllinux_1_2_ppc64le.whl", hash = "sha256:939578d9d8fd4299220161fdd76e86c6a251987476f5243e8864a7844476ba14", size = 160018, upload-time = "2025-08-09T07:56:01.678Z" }, + { url = "https://files.pythonhosted.org/packages/99/04/baae2a1ea1893a01635d475b9261c889a18fd48393634b6270827869fa34/charset_normalizer-3.4.3-cp311-cp311-musllinux_1_2_s390x.whl", hash = "sha256:fd10de089bcdcd1be95a2f73dbe6254798ec1bda9f450d5828c96f93e2536b9c", size = 157430, upload-time = "2025-08-09T07:56:02.87Z" }, + { url = "https://files.pythonhosted.org/packages/2f/36/77da9c6a328c54d17b960c89eccacfab8271fdaaa228305330915b88afa9/charset_normalizer-3.4.3-cp311-cp311-musllinux_1_2_x86_64.whl", hash = "sha256:1e8ac75d72fa3775e0b7cb7e4629cec13b7514d928d15ef8ea06bca03ef01cae", size = 151600, upload-time = "2025-08-09T07:56:04.089Z" }, + { url = "https://files.pythonhosted.org/packages/64/d4/9eb4ff2c167edbbf08cdd28e19078bf195762e9bd63371689cab5ecd3d0d/charset_normalizer-3.4.3-cp311-cp311-win32.whl", hash = "sha256:6cf8fd4c04756b6b60146d98cd8a77d0cdae0e1ca20329da2ac85eed779b6849", size = 99616, upload-time = "2025-08-09T07:56:05.658Z" }, + { url = "https://files.pythonhosted.org/packages/f4/9c/996a4a028222e7761a96634d1820de8a744ff4327a00ada9c8942033089b/charset_normalizer-3.4.3-cp311-cp311-win_amd64.whl", hash = "sha256:31a9a6f775f9bcd865d88ee350f0ffb0e25936a7f930ca98995c05abf1faf21c", size = 107108, upload-time = "2025-08-09T07:56:07.176Z" }, + { url = "https://files.pythonhosted.org/packages/e9/5e/14c94999e418d9b87682734589404a25854d5f5d0408df68bc15b6ff54bb/charset_normalizer-3.4.3-cp312-cp312-macosx_10_13_universal2.whl", hash = "sha256:e28e334d3ff134e88989d90ba04b47d84382a828c061d0d1027b1b12a62b39b1", size = 205655, upload-time = "2025-08-09T07:56:08.475Z" }, + { url = "https://files.pythonhosted.org/packages/7d/a8/c6ec5d389672521f644505a257f50544c074cf5fc292d5390331cd6fc9c3/charset_normalizer-3.4.3-cp312-cp312-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:0cacf8f7297b0c4fcb74227692ca46b4a5852f8f4f24b3c766dd94a1075c4884", size = 146223, upload-time = "2025-08-09T07:56:09.708Z" }, + { url = "https://files.pythonhosted.org/packages/fc/eb/a2ffb08547f4e1e5415fb69eb7db25932c52a52bed371429648db4d84fb1/charset_normalizer-3.4.3-cp312-cp312-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:c6fd51128a41297f5409deab284fecbe5305ebd7e5a1f959bee1c054622b7018", size = 159366, upload-time = "2025-08-09T07:56:11.326Z" }, + { url = "https://files.pythonhosted.org/packages/82/10/0fd19f20c624b278dddaf83b8464dcddc2456cb4b02bb902a6da126b87a1/charset_normalizer-3.4.3-cp312-cp312-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:3cfb2aad70f2c6debfbcb717f23b7eb55febc0bb23dcffc0f076009da10c6392", size = 157104, upload-time = "2025-08-09T07:56:13.014Z" }, + { url = "https://files.pythonhosted.org/packages/16/ab/0233c3231af734f5dfcf0844aa9582d5a1466c985bbed6cedab85af9bfe3/charset_normalizer-3.4.3-cp312-cp312-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:1606f4a55c0fd363d754049cdf400175ee96c992b1f8018b993941f221221c5f", size = 151830, upload-time = "2025-08-09T07:56:14.428Z" }, + { url = "https://files.pythonhosted.org/packages/ae/02/e29e22b4e02839a0e4a06557b1999d0a47db3567e82989b5bb21f3fbbd9f/charset_normalizer-3.4.3-cp312-cp312-musllinux_1_2_aarch64.whl", hash = "sha256:027b776c26d38b7f15b26a5da1044f376455fb3766df8fc38563b4efbc515154", size = 148854, upload-time = "2025-08-09T07:56:16.051Z" }, + { url = "https://files.pythonhosted.org/packages/05/6b/e2539a0a4be302b481e8cafb5af8792da8093b486885a1ae4d15d452bcec/charset_normalizer-3.4.3-cp312-cp312-musllinux_1_2_ppc64le.whl", hash = "sha256:42e5088973e56e31e4fa58eb6bd709e42fc03799c11c42929592889a2e54c491", size = 160670, upload-time = "2025-08-09T07:56:17.314Z" }, + { url = "https://files.pythonhosted.org/packages/31/e7/883ee5676a2ef217a40ce0bffcc3d0dfbf9e64cbcfbdf822c52981c3304b/charset_normalizer-3.4.3-cp312-cp312-musllinux_1_2_s390x.whl", hash = "sha256:cc34f233c9e71701040d772aa7490318673aa7164a0efe3172b2981218c26d93", size = 158501, upload-time = "2025-08-09T07:56:18.641Z" }, + { url = "https://files.pythonhosted.org/packages/c1/35/6525b21aa0db614cf8b5792d232021dca3df7f90a1944db934efa5d20bb1/charset_normalizer-3.4.3-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:320e8e66157cc4e247d9ddca8e21f427efc7a04bbd0ac8a9faf56583fa543f9f", size = 153173, upload-time = "2025-08-09T07:56:20.289Z" }, + { url = "https://files.pythonhosted.org/packages/50/ee/f4704bad8201de513fdc8aac1cabc87e38c5818c93857140e06e772b5892/charset_normalizer-3.4.3-cp312-cp312-win32.whl", hash = "sha256:fb6fecfd65564f208cbf0fba07f107fb661bcd1a7c389edbced3f7a493f70e37", size = 99822, upload-time = "2025-08-09T07:56:21.551Z" }, + { url = "https://files.pythonhosted.org/packages/39/f5/3b3836ca6064d0992c58c7561c6b6eee1b3892e9665d650c803bd5614522/charset_normalizer-3.4.3-cp312-cp312-win_amd64.whl", hash = "sha256:86df271bf921c2ee3818f0522e9a5b8092ca2ad8b065ece5d7d9d0e9f4849bcc", size = 107543, upload-time = "2025-08-09T07:56:23.115Z" }, + { url = "https://files.pythonhosted.org/packages/65/ca/2135ac97709b400c7654b4b764daf5c5567c2da45a30cdd20f9eefe2d658/charset_normalizer-3.4.3-cp313-cp313-macosx_10_13_universal2.whl", hash = "sha256:14c2a87c65b351109f6abfc424cab3927b3bdece6f706e4d12faaf3d52ee5efe", size = 205326, upload-time = "2025-08-09T07:56:24.721Z" }, + { url = "https://files.pythonhosted.org/packages/71/11/98a04c3c97dd34e49c7d247083af03645ca3730809a5509443f3c37f7c99/charset_normalizer-3.4.3-cp313-cp313-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:41d1fc408ff5fdfb910200ec0e74abc40387bccb3252f3f27c0676731df2b2c8", size = 146008, upload-time = "2025-08-09T07:56:26.004Z" }, + { url = "https://files.pythonhosted.org/packages/60/f5/4659a4cb3c4ec146bec80c32d8bb16033752574c20b1252ee842a95d1a1e/charset_normalizer-3.4.3-cp313-cp313-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:1bb60174149316da1c35fa5233681f7c0f9f514509b8e399ab70fea5f17e45c9", size = 159196, upload-time = "2025-08-09T07:56:27.25Z" }, + { url = "https://files.pythonhosted.org/packages/86/9e/f552f7a00611f168b9a5865a1414179b2c6de8235a4fa40189f6f79a1753/charset_normalizer-3.4.3-cp313-cp313-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:30d006f98569de3459c2fc1f2acde170b7b2bd265dc1943e87e1a4efe1b67c31", size = 156819, upload-time = "2025-08-09T07:56:28.515Z" }, + { url = "https://files.pythonhosted.org/packages/7e/95/42aa2156235cbc8fa61208aded06ef46111c4d3f0de233107b3f38631803/charset_normalizer-3.4.3-cp313-cp313-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:416175faf02e4b0810f1f38bcb54682878a4af94059a1cd63b8747244420801f", size = 151350, upload-time = "2025-08-09T07:56:29.716Z" }, + { url = "https://files.pythonhosted.org/packages/c2/a9/3865b02c56f300a6f94fc631ef54f0a8a29da74fb45a773dfd3dcd380af7/charset_normalizer-3.4.3-cp313-cp313-musllinux_1_2_aarch64.whl", hash = "sha256:6aab0f181c486f973bc7262a97f5aca3ee7e1437011ef0c2ec04b5a11d16c927", size = 148644, upload-time = "2025-08-09T07:56:30.984Z" }, + { url = "https://files.pythonhosted.org/packages/77/d9/cbcf1a2a5c7d7856f11e7ac2d782aec12bdfea60d104e60e0aa1c97849dc/charset_normalizer-3.4.3-cp313-cp313-musllinux_1_2_ppc64le.whl", hash = "sha256:fdabf8315679312cfa71302f9bd509ded4f2f263fb5b765cf1433b39106c3cc9", size = 160468, upload-time = "2025-08-09T07:56:32.252Z" }, + { url = "https://files.pythonhosted.org/packages/f6/42/6f45efee8697b89fda4d50580f292b8f7f9306cb2971d4b53f8914e4d890/charset_normalizer-3.4.3-cp313-cp313-musllinux_1_2_s390x.whl", hash = "sha256:bd28b817ea8c70215401f657edef3a8aa83c29d447fb0b622c35403780ba11d5", size = 158187, upload-time = "2025-08-09T07:56:33.481Z" }, + { url = "https://files.pythonhosted.org/packages/70/99/f1c3bdcfaa9c45b3ce96f70b14f070411366fa19549c1d4832c935d8e2c3/charset_normalizer-3.4.3-cp313-cp313-musllinux_1_2_x86_64.whl", hash = "sha256:18343b2d246dc6761a249ba1fb13f9ee9a2bcd95decc767319506056ea4ad4dc", size = 152699, upload-time = "2025-08-09T07:56:34.739Z" }, + { url = "https://files.pythonhosted.org/packages/a3/ad/b0081f2f99a4b194bcbb1934ef3b12aa4d9702ced80a37026b7607c72e58/charset_normalizer-3.4.3-cp313-cp313-win32.whl", hash = "sha256:6fb70de56f1859a3f71261cbe41005f56a7842cc348d3aeb26237560bfa5e0ce", size = 99580, upload-time = "2025-08-09T07:56:35.981Z" }, + { url = "https://files.pythonhosted.org/packages/9a/8f/ae790790c7b64f925e5c953b924aaa42a243fb778fed9e41f147b2a5715a/charset_normalizer-3.4.3-cp313-cp313-win_amd64.whl", hash = "sha256:cf1ebb7d78e1ad8ec2a8c4732c7be2e736f6e5123a4146c5b89c9d1f585f8cef", size = 107366, upload-time = "2025-08-09T07:56:37.339Z" }, + { url = "https://files.pythonhosted.org/packages/8e/91/b5a06ad970ddc7a0e513112d40113e834638f4ca1120eb727a249fb2715e/charset_normalizer-3.4.3-cp314-cp314-macosx_10_13_universal2.whl", hash = "sha256:3cd35b7e8aedeb9e34c41385fda4f73ba609e561faedfae0a9e75e44ac558a15", size = 204342, upload-time = "2025-08-09T07:56:38.687Z" }, + { url = "https://files.pythonhosted.org/packages/ce/ec/1edc30a377f0a02689342f214455c3f6c2fbedd896a1d2f856c002fc3062/charset_normalizer-3.4.3-cp314-cp314-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:b89bc04de1d83006373429975f8ef9e7932534b8cc9ca582e4db7d20d91816db", size = 145995, upload-time = "2025-08-09T07:56:40.048Z" }, + { url = "https://files.pythonhosted.org/packages/17/e5/5e67ab85e6d22b04641acb5399c8684f4d37caf7558a53859f0283a650e9/charset_normalizer-3.4.3-cp314-cp314-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:2001a39612b241dae17b4687898843f254f8748b796a2e16f1051a17078d991d", size = 158640, upload-time = "2025-08-09T07:56:41.311Z" }, + { url = "https://files.pythonhosted.org/packages/f1/e5/38421987f6c697ee3722981289d554957c4be652f963d71c5e46a262e135/charset_normalizer-3.4.3-cp314-cp314-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:8dcfc373f888e4fb39a7bc57e93e3b845e7f462dacc008d9749568b1c4ece096", size = 156636, upload-time = "2025-08-09T07:56:43.195Z" }, + { url = "https://files.pythonhosted.org/packages/a0/e4/5a075de8daa3ec0745a9a3b54467e0c2967daaaf2cec04c845f73493e9a1/charset_normalizer-3.4.3-cp314-cp314-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:18b97b8404387b96cdbd30ad660f6407799126d26a39ca65729162fd810a99aa", size = 150939, upload-time = "2025-08-09T07:56:44.819Z" }, + { url = "https://files.pythonhosted.org/packages/02/f7/3611b32318b30974131db62b4043f335861d4d9b49adc6d57c1149cc49d4/charset_normalizer-3.4.3-cp314-cp314-musllinux_1_2_aarch64.whl", hash = "sha256:ccf600859c183d70eb47e05a44cd80a4ce77394d1ac0f79dbd2dd90a69a3a049", size = 148580, upload-time = "2025-08-09T07:56:46.684Z" }, + { url = "https://files.pythonhosted.org/packages/7e/61/19b36f4bd67f2793ab6a99b979b4e4f3d8fc754cbdffb805335df4337126/charset_normalizer-3.4.3-cp314-cp314-musllinux_1_2_ppc64le.whl", hash = "sha256:53cd68b185d98dde4ad8990e56a58dea83a4162161b1ea9272e5c9182ce415e0", size = 159870, upload-time = "2025-08-09T07:56:47.941Z" }, + { url = "https://files.pythonhosted.org/packages/06/57/84722eefdd338c04cf3030ada66889298eaedf3e7a30a624201e0cbe424a/charset_normalizer-3.4.3-cp314-cp314-musllinux_1_2_s390x.whl", hash = "sha256:30a96e1e1f865f78b030d65241c1ee850cdf422d869e9028e2fc1d5e4db73b92", size = 157797, upload-time = "2025-08-09T07:56:49.756Z" }, + { url = "https://files.pythonhosted.org/packages/72/2a/aff5dd112b2f14bcc3462c312dce5445806bfc8ab3a7328555da95330e4b/charset_normalizer-3.4.3-cp314-cp314-musllinux_1_2_x86_64.whl", hash = "sha256:d716a916938e03231e86e43782ca7878fb602a125a91e7acb8b5112e2e96ac16", size = 152224, upload-time = "2025-08-09T07:56:51.369Z" }, + { url = "https://files.pythonhosted.org/packages/b7/8c/9839225320046ed279c6e839d51f028342eb77c91c89b8ef2549f951f3ec/charset_normalizer-3.4.3-cp314-cp314-win32.whl", hash = "sha256:c6dbd0ccdda3a2ba7c2ecd9d77b37f3b5831687d8dc1b6ca5f56a4880cc7b7ce", size = 100086, upload-time = "2025-08-09T07:56:52.722Z" }, + { url = "https://files.pythonhosted.org/packages/ee/7a/36fbcf646e41f710ce0a563c1c9a343c6edf9be80786edeb15b6f62e17db/charset_normalizer-3.4.3-cp314-cp314-win_amd64.whl", hash = "sha256:73dc19b562516fc9bcf6e5d6e596df0b4eb98d87e4f79f3ae71840e6ed21361c", size = 107400, upload-time = "2025-08-09T07:56:55.172Z" }, + { url = "https://files.pythonhosted.org/packages/8a/1f/f041989e93b001bc4e44bb1669ccdcf54d3f00e628229a85b08d330615c5/charset_normalizer-3.4.3-py3-none-any.whl", hash = "sha256:ce571ab16d890d23b5c278547ba694193a45011ff86a9162a71307ed9f86759a", size = 53175, upload-time = "2025-08-09T07:57:26.864Z" }, ] [[package]] name = "chex" -version = "0.1.89" +version = "0.1.90" source = { registry = "https://pypi.org/simple" } +resolution-markers = [ + "python_full_version < '3.11'", +] dependencies = [ - { name = "absl-py" }, - { name = "jax" }, - { name = "jaxlib" }, + { name = "absl-py", marker = "python_full_version < '3.11'" }, + { name = "jax", version = "0.6.2", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version < '3.11'" }, + { name = "jaxlib", version = "0.6.2", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version < '3.11'" }, { name = "numpy", version = "2.2.6", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version < '3.11'" }, - { name = "numpy", version = "2.3.1", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version >= '3.11'" }, - { name = "setuptools", marker = "python_full_version >= '3.12'" }, - { name = "toolz" }, - { name = "typing-extensions" }, + { name = "toolz", marker = "python_full_version < '3.11'" }, + { name = "typing-extensions", marker = "python_full_version < '3.11'" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/77/70/53c7d404ce9e2a94009aea7f77ef6e392f6740e071c62683a506647c520f/chex-0.1.90.tar.gz", hash = "sha256:d3c375aeb6154b08f1cccd2bee4ed83659ee2198a6acf1160d2fe2e4a6c87b5c", size = 92363, upload-time = "2025-07-23T19:50:47.945Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/6f/3d/46bb04776c465cea2dd8aa2d4b61ab610b707f798f47838ef7e6105b025c/chex-0.1.90-py3-none-any.whl", hash = "sha256:fce3de82588f72d4796e545e574a433aa29229cbdcf792555e41bead24b704ae", size = 101047, upload-time = "2025-07-23T19:50:46.603Z" }, +] + +[[package]] +name = "chex" +version = "0.1.91" +source = { registry = "https://pypi.org/simple" } +resolution-markers = [ + "python_full_version >= '3.13'", + "python_full_version == '3.12.*'", + "python_full_version == '3.11.*'", ] -sdist = { url = "https://files.pythonhosted.org/packages/ca/ac/504a8019f7ef372fc6cc3999ec9e3d0fbb38e6992f55d845d5b928010c11/chex-0.1.89.tar.gz", hash = "sha256:78f856e6a0a8459edfcbb402c2c044d2b8102eac4b633838cbdfdcdb09c6c8e0", size = 90676 } +dependencies = [ + { name = "absl-py", marker = "python_full_version >= '3.11'" }, + { name = "jax", version = "0.7.2", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version >= '3.11'" }, + { name = "jaxlib", version = "0.7.2", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version >= '3.11'" }, + { name = "numpy", version = "2.3.3", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version >= '3.11'" }, + { name = "toolz", marker = "python_full_version >= '3.11'" }, + { name = "typing-extensions", marker = "python_full_version >= '3.11'" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/5b/7d/812f01e7b2ddf28a0caa8dde56bd951a2c8f691c9bbfce38d469458d1502/chex-0.1.91.tar.gz", hash = "sha256:65367a521415ada905b8c0222b0a41a68337fcadf79a1fb6fc992dbd95dd9f76", size = 90302, upload-time = "2025-09-01T21:49:32.834Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/5e/6c/309972937d931069816dc8b28193a650485bc35cca92c04c8c15c4bd181e/chex-0.1.89-py3-none-any.whl", hash = "sha256:145241c27d8944adb634fb7d472a460e1c1b643f561507d4031ad5156ef82dfa", size = 99908 }, + { url = "https://files.pythonhosted.org/packages/12/0c/96102c01dd02ae740d4afc3644d5c7d7fc51d3feefd67300a2aa1ddbf7cb/chex-0.1.91-py3-none-any.whl", hash = "sha256:6fc4cbfc22301c08d4a7ef706045668410100962eba8ba6af03fa07f4e5dcf9b", size = 100965, upload-time = "2025-09-01T21:49:31.141Z" }, ] [[package]] name = "click" -version = "8.2.1" +version = "8.3.0" source = { registry = "https://pypi.org/simple" } dependencies = [ { name = "colorama", marker = "sys_platform == 'win32'" }, ] -sdist = { url = "https://files.pythonhosted.org/packages/60/6c/8ca2efa64cf75a977a0d7fac081354553ebe483345c734fb6b6515d96bbc/click-8.2.1.tar.gz", hash = "sha256:27c491cc05d968d271d5a1db13e3b5a184636d9d930f148c50b038f0d0646202", size = 286342 } +sdist = { url = "https://files.pythonhosted.org/packages/46/61/de6cd827efad202d7057d93e0fed9294b96952e188f7384832791c7b2254/click-8.3.0.tar.gz", hash = "sha256:e7b8232224eba16f4ebe410c25ced9f7875cb5f3263ffc93cc3e8da705e229c4", size = 276943, upload-time = "2025-09-18T17:32:23.696Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/85/32/10bb5764d90a8eee674e9dc6f4db6a0ab47c8c4d0d83c27f7c39ac415a4d/click-8.2.1-py3-none-any.whl", hash = "sha256:61a3265b914e850b85317d0b3109c7f8cd35a670f963866005d6ef1d5175a12b", size = 102215 }, + { url = "https://files.pythonhosted.org/packages/db/d3/9dcc0f5797f070ec8edf30fbadfb200e71d9db6b84d211e3b2085a7589a0/click-8.3.0-py3-none-any.whl", hash = "sha256:9b9f285302c6e3064f4330c05f05b81945b2a39544279343e6e7c5f27a9baddc", size = 107295, upload-time = "2025-09-18T17:32:22.42Z" }, ] [[package]] name = "colorama" version = "0.4.6" source = { registry = "https://pypi.org/simple" } -sdist = { url = "https://files.pythonhosted.org/packages/d8/53/6f443c9a4a8358a93a6792e2acffb9d9d5cb0a5cfd8802644b7b1c9a02e4/colorama-0.4.6.tar.gz", hash = "sha256:08695f5cb7ed6e0531a20572697297273c47b8cae5a63ffc6d6ed5c201be6e44", size = 27697 } +sdist = { url = "https://files.pythonhosted.org/packages/d8/53/6f443c9a4a8358a93a6792e2acffb9d9d5cb0a5cfd8802644b7b1c9a02e4/colorama-0.4.6.tar.gz", hash = "sha256:08695f5cb7ed6e0531a20572697297273c47b8cae5a63ffc6d6ed5c201be6e44", size = 27697, upload-time = "2022-10-25T02:36:22.414Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/d1/d6/3965ed04c63042e047cb6a3e6ed1a63a35087b6a609aa3a15ed8ac56c221/colorama-0.4.6-py2.py3-none-any.whl", hash = "sha256:4f1d9991f5acc0ca119f9d443620b77f9d6b33703e51011c16baf57afb285fc6", size = 25335 }, + { url = "https://files.pythonhosted.org/packages/d1/d6/3965ed04c63042e047cb6a3e6ed1a63a35087b6a609aa3a15ed8ac56c221/colorama-0.4.6-py2.py3-none-any.whl", hash = "sha256:4f1d9991f5acc0ca119f9d443620b77f9d6b33703e51011c16baf57afb285fc6", size = 25335, upload-time = "2022-10-25T02:36:20.889Z" }, ] [[package]] name = "distlib" -version = "0.3.9" +version = "0.4.0" source = { registry = "https://pypi.org/simple" } -sdist = { url = "https://files.pythonhosted.org/packages/0d/dd/1bec4c5ddb504ca60fc29472f3d27e8d4da1257a854e1d96742f15c1d02d/distlib-0.3.9.tar.gz", hash = "sha256:a60f20dea646b8a33f3e7772f74dc0b2d0772d2837ee1342a00645c81edf9403", size = 613923 } +sdist = { url = "https://files.pythonhosted.org/packages/96/8e/709914eb2b5749865801041647dc7f4e6d00b549cfe88b65ca192995f07c/distlib-0.4.0.tar.gz", hash = "sha256:feec40075be03a04501a973d81f633735b4b69f98b05450592310c0f401a4e0d", size = 614605, upload-time = "2025-07-17T16:52:00.465Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/91/a1/cf2472db20f7ce4a6be1253a81cfdf85ad9c7885ffbed7047fb72c24cf87/distlib-0.3.9-py2.py3-none-any.whl", hash = "sha256:47f8c22fd27c27e25a65601af709b38e4f0a45ea4fc2e710f65755fa8caaaf87", size = 468973 }, + { url = "https://files.pythonhosted.org/packages/33/6b/e0547afaf41bf2c42e52430072fa5658766e3d65bd4b03a563d1b6336f57/distlib-0.4.0-py2.py3-none-any.whl", hash = "sha256:9659f7d87e46584a30b5780e43ac7a2143098441670ff0a49d5f9034c54a6c16", size = 469047, upload-time = "2025-07-17T16:51:58.613Z" }, ] [[package]] name = "equinox" -version = "0.12.2" +version = "0.13.1" source = { registry = "https://pypi.org/simple" } dependencies = [ - { name = "jax" }, + { name = "jax", version = "0.6.2", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version < '3.11'" }, + { name = "jax", version = "0.7.2", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version >= '3.11'" }, { name = "jaxtyping" }, { name = "typing-extensions" }, { name = "wadler-lindig" }, ] -sdist = { url = "https://files.pythonhosted.org/packages/4c/1c/da174caa2902cee108a542cfb801bd4366a5e44541b625d5a0984c9238e0/equinox-0.12.2.tar.gz", hash = "sha256:648e4206bbc53b228922e8f18cd3cffe543ddda1172c0002f8954e484bab0023", size = 139007 } +sdist = { url = "https://files.pythonhosted.org/packages/c8/43/2b7b3895f910f2335ade18a261b3f77ce9466605adbb211c4e254ad14b25/equinox-0.13.1.tar.gz", hash = "sha256:e90f11cfe66b2f73f5c172260a17c48851794a0f243dd2cbe4ea70f4c90cbd07", size = 139339, upload-time = "2025-09-20T15:21:40.199Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/8e/a7/5961a7cad10df1e165a8b9c4ba0661aaec9497861e53682effa1787d97aa/equinox-0.12.2-py3-none-any.whl", hash = "sha256:0d9c09c077e7895a5334930ddb9ecd7d39840c3ad252cf8262aa8ddc6bb8ae97", size = 177247 }, + { url = "https://files.pythonhosted.org/packages/1f/10/9c0687024ce9e478a667262d111fb15502828d28c93482b48446e3558efd/equinox-0.13.1-py3-none-any.whl", hash = "sha256:3c6e9043352c9a63216b40e3f3cdd1d1452f82a0175cfe322f79630ebdb80d71", size = 179254, upload-time = "2025-09-20T15:21:38.679Z" }, ] [[package]] name = "etils" -version = "1.12.2" +version = "1.13.0" source = { registry = "https://pypi.org/simple" } -sdist = { url = "https://files.pythonhosted.org/packages/e4/12/1cc11e88a0201280ff389bc4076df7c3432e39d9f22cba8b71aa263f67b8/etils-1.12.2.tar.gz", hash = "sha256:c6b9e1f0ce66d1bbf54f99201b08a60ba396d3446d9eb18d4bc39b26a2e1a5ee", size = 104711 } +sdist = { url = "https://files.pythonhosted.org/packages/9b/a0/522bbff0f3cdd37968f90dd7f26c7aa801ed87f5ba335f156de7f2b88a48/etils-1.13.0.tar.gz", hash = "sha256:a5b60c71f95bcd2d43d4e9fb3dc3879120c1f60472bb5ce19f7a860b1d44f607", size = 106368, upload-time = "2025-07-15T10:29:10.563Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/dd/71/40ee142e564b8a34a7ae9546e99e665e0001011a3254d5bbbe113d72ccba/etils-1.12.2-py3-none-any.whl", hash = "sha256:4600bec9de6cf5cb043a171e1856e38b5f273719cf3ecef90199f7091a6b3912", size = 167613 }, + { url = "https://files.pythonhosted.org/packages/e7/98/87b5946356095738cb90a6df7b35ff69ac5750f6e783d5fbcc5cb3b6cbd7/etils-1.13.0-py3-none-any.whl", hash = "sha256:d9cd4f40fbe77ad6613b7348a18132cc511237b6c076dbb89105c0b520a4c6bb", size = 170603, upload-time = "2025-07-15T10:29:09.076Z" }, ] [package.optional-dependencies] @@ -234,48 +273,76 @@ source = { registry = "https://pypi.org/simple" } dependencies = [ { name = "typing-extensions", marker = "python_full_version < '3.11'" }, ] -sdist = { url = "https://files.pythonhosted.org/packages/0b/9f/a65090624ecf468cdca03533906e7c69ed7588582240cfe7cc9e770b50eb/exceptiongroup-1.3.0.tar.gz", hash = "sha256:b241f5885f560bc56a59ee63ca4c6a8bfa46ae4ad651af316d4e81817bb9fd88", size = 29749 } +sdist = { url = "https://files.pythonhosted.org/packages/0b/9f/a65090624ecf468cdca03533906e7c69ed7588582240cfe7cc9e770b50eb/exceptiongroup-1.3.0.tar.gz", hash = "sha256:b241f5885f560bc56a59ee63ca4c6a8bfa46ae4ad651af316d4e81817bb9fd88", size = 29749, upload-time = "2025-05-10T17:42:51.123Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/36/f4/c6e662dade71f56cd2f3735141b265c3c79293c109549c1e6933b0651ffc/exceptiongroup-1.3.0-py3-none-any.whl", hash = "sha256:4d111e6e0c13d0644cad6ddaa7ed0261a0b36971f6d23e7ec9b4b9097da78a10", size = 16674 }, + { url = "https://files.pythonhosted.org/packages/36/f4/c6e662dade71f56cd2f3735141b265c3c79293c109549c1e6933b0651ffc/exceptiongroup-1.3.0-py3-none-any.whl", hash = "sha256:4d111e6e0c13d0644cad6ddaa7ed0261a0b36971f6d23e7ec9b4b9097da78a10", size = 16674, upload-time = "2025-05-10T17:42:49.33Z" }, ] [[package]] name = "filelock" -version = "3.18.0" +version = "3.19.1" source = { registry = "https://pypi.org/simple" } -sdist = { url = "https://files.pythonhosted.org/packages/0a/10/c23352565a6544bdc5353e0b15fc1c563352101f30e24bf500207a54df9a/filelock-3.18.0.tar.gz", hash = "sha256:adbc88eabb99d2fec8c9c1b229b171f18afa655400173ddc653d5d01501fb9f2", size = 18075 } +sdist = { url = "https://files.pythonhosted.org/packages/40/bb/0ab3e58d22305b6f5440629d20683af28959bf793d98d11950e305c1c326/filelock-3.19.1.tar.gz", hash = "sha256:66eda1888b0171c998b35be2bcc0f6d75c388a7ce20c3f3f37aa8e96c2dddf58", size = 17687, upload-time = "2025-08-14T16:56:03.016Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/4d/36/2a115987e2d8c300a974597416d9de88f2444426de9571f4b59b2cca3acc/filelock-3.18.0-py3-none-any.whl", hash = "sha256:c401f4f8377c4464e6db25fff06205fd89bdd83b65eb0488ed1b160f780e21de", size = 16215 }, + { url = "https://files.pythonhosted.org/packages/42/14/42b2651a2f46b022ccd948bca9f2d5af0fd8929c4eec235b8d6d844fbe67/filelock-3.19.1-py3-none-any.whl", hash = "sha256:d38e30481def20772f5baf097c122c3babc4fcdb7e14e57049eb9d88c6dc017d", size = 15988, upload-time = "2025-08-14T16:56:01.633Z" }, ] [[package]] name = "flax" version = "0.10.7" source = { registry = "https://pypi.org/simple" } +resolution-markers = [ + "python_full_version < '3.11'", +] dependencies = [ - { name = "jax" }, - { name = "msgpack" }, - { name = "numpy", version = "2.3.1", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version >= '3.11'" }, - { name = "optax" }, - { name = "orbax-checkpoint" }, - { name = "pyyaml" }, - { name = "rich" }, - { name = "tensorstore" }, - { name = "treescope" }, - { name = "typing-extensions" }, + { name = "jax", version = "0.6.2", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version < '3.11'" }, + { name = "msgpack", marker = "python_full_version < '3.11'" }, + { name = "optax", marker = "python_full_version < '3.11'" }, + { name = "orbax-checkpoint", marker = "python_full_version < '3.11'" }, + { name = "pyyaml", marker = "python_full_version < '3.11'" }, + { name = "rich", marker = "python_full_version < '3.11'" }, + { name = "tensorstore", marker = "python_full_version < '3.11'" }, + { name = "treescope", marker = "python_full_version < '3.11'" }, + { name = "typing-extensions", marker = "python_full_version < '3.11'" }, ] -sdist = { url = "https://files.pythonhosted.org/packages/e6/76/4ea55a60a47e98fcff591238ee26ed4624cb4fdc4893aa3ebf78d0d021f4/flax-0.10.7.tar.gz", hash = "sha256:2930d6671e23076f6db3b96afacf45c5060898f5c189ecab6dda7e05d26c2085", size = 5136099 } +sdist = { url = "https://files.pythonhosted.org/packages/e6/76/4ea55a60a47e98fcff591238ee26ed4624cb4fdc4893aa3ebf78d0d021f4/flax-0.10.7.tar.gz", hash = "sha256:2930d6671e23076f6db3b96afacf45c5060898f5c189ecab6dda7e05d26c2085", size = 5136099, upload-time = "2025-07-02T06:10:07.819Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/11/f6/560d338687d40182c8429cf35c64cc022e0d57ba3e52191c4a78ed239b4e/flax-0.10.7-py3-none-any.whl", hash = "sha256:4033223a9a9969ba0b252e085e9714d0a1e9124ac300aaf48e92c40769c420f6", size = 456944 }, + { url = "https://files.pythonhosted.org/packages/11/f6/560d338687d40182c8429cf35c64cc022e0d57ba3e52191c4a78ed239b4e/flax-0.10.7-py3-none-any.whl", hash = "sha256:4033223a9a9969ba0b252e085e9714d0a1e9124ac300aaf48e92c40769c420f6", size = 456944, upload-time = "2025-07-02T06:10:05.807Z" }, +] + +[[package]] +name = "flax" +version = "0.12.0" +source = { registry = "https://pypi.org/simple" } +resolution-markers = [ + "python_full_version >= '3.13'", + "python_full_version == '3.12.*'", + "python_full_version == '3.11.*'", +] +dependencies = [ + { name = "jax", version = "0.7.2", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version >= '3.11'" }, + { name = "msgpack", marker = "python_full_version >= '3.11'" }, + { name = "numpy", version = "2.3.3", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version >= '3.11'" }, + { name = "optax", marker = "python_full_version >= '3.11'" }, + { name = "orbax-checkpoint", marker = "python_full_version >= '3.11'" }, + { name = "pyyaml", marker = "python_full_version >= '3.11'" }, + { name = "rich", marker = "python_full_version >= '3.11'" }, + { name = "tensorstore", marker = "python_full_version >= '3.11'" }, + { name = "treescope", marker = "python_full_version >= '3.11'" }, + { name = "typing-extensions", marker = "python_full_version >= '3.11'" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/8b/02/2d4fbc31dcf5fb02e2b8ce733f8eecaffc7f24e905df2da39539809b195b/flax-0.12.0.tar.gz", hash = "sha256:cb3d4a2028666640c1a2e5b267dadfbd42ef14c6db41896fb4c765a7f05ebe74", size = 5038989, upload-time = "2025-09-25T23:59:00.919Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/e6/cf/d118be069d0fbbfbb6c5591069233678b573e49d81e2a387afb0297528a0/flax-0.12.0-py3-none-any.whl", hash = "sha256:13dee5f2658e8b51e22cef54b788ddbad1b6e14a9d7c5b6d1ae9c3a0110d645e", size = 466282, upload-time = "2025-09-25T23:58:58.631Z" }, ] [[package]] name = "fsspec" -version = "2025.5.1" +version = "2025.9.0" source = { registry = "https://pypi.org/simple" } -sdist = { url = "https://files.pythonhosted.org/packages/00/f7/27f15d41f0ed38e8fcc488584b57e902b331da7f7c6dcda53721b15838fc/fsspec-2025.5.1.tar.gz", hash = "sha256:2e55e47a540b91843b755e83ded97c6e897fa0942b11490113f09e9c443c2475", size = 303033 } +sdist = { url = "https://files.pythonhosted.org/packages/de/e0/bab50af11c2d75c9c4a2a26a5254573c0bd97cea152254401510950486fa/fsspec-2025.9.0.tar.gz", hash = "sha256:19fd429483d25d28b65ec68f9f4adc16c17ea2c7c7bf54ec61360d478fb19c19", size = 304847, upload-time = "2025-09-02T19:10:49.215Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/bb/61/78c7b3851add1481b048b5fdc29067397a1784e2910592bc81bb3f608635/fsspec-2025.5.1-py3-none-any.whl", hash = "sha256:24d3a2e663d5fc735ab256263c4075f374a174c3410c0b25e5bd1970bceaa462", size = 199052 }, + { url = "https://files.pythonhosted.org/packages/47/71/70db47e4f6ce3e5c37a607355f80da8860a33226be640226ac52cb05ef2e/fsspec-2025.9.0-py3-none-any.whl", hash = "sha256:530dc2a2af60a414a832059574df4a6e10cce927f6f4a78209390fe38955cfb7", size = 199289, upload-time = "2025-09-02T19:10:47.708Z" }, ] [[package]] @@ -285,21 +352,21 @@ source = { registry = "https://pypi.org/simple" } dependencies = [ { name = "python-dateutil" }, ] -sdist = { url = "https://files.pythonhosted.org/packages/d9/29/d40217cbe2f6b1359e00c6c307bb3fc876ba74068cbab3dde77f03ca0dc4/ghp-import-2.1.0.tar.gz", hash = "sha256:9c535c4c61193c2df8871222567d7fd7e5014d835f97dc7b7439069e2413d343", size = 10943 } +sdist = { url = "https://files.pythonhosted.org/packages/d9/29/d40217cbe2f6b1359e00c6c307bb3fc876ba74068cbab3dde77f03ca0dc4/ghp-import-2.1.0.tar.gz", hash = "sha256:9c535c4c61193c2df8871222567d7fd7e5014d835f97dc7b7439069e2413d343", size = 10943, upload-time = "2022-05-02T15:47:16.11Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/f7/ec/67fbef5d497f86283db54c22eec6f6140243aae73265799baaaa19cd17fb/ghp_import-2.1.0-py3-none-any.whl", hash = "sha256:8337dd7b50877f163d4c0289bc1f1c7f127550241988d568c1db512c4324a619", size = 11034 }, + { url = "https://files.pythonhosted.org/packages/f7/ec/67fbef5d497f86283db54c22eec6f6140243aae73265799baaaa19cd17fb/ghp_import-2.1.0-py3-none-any.whl", hash = "sha256:8337dd7b50877f163d4c0289bc1f1c7f127550241988d568c1db512c4324a619", size = 11034, upload-time = "2022-05-02T15:47:14.552Z" }, ] [[package]] name = "griffe" -version = "1.7.3" +version = "1.14.0" source = { registry = "https://pypi.org/simple" } dependencies = [ { name = "colorama" }, ] -sdist = { url = "https://files.pythonhosted.org/packages/a9/3e/5aa9a61f7c3c47b0b52a1d930302992229d191bf4bc76447b324b731510a/griffe-1.7.3.tar.gz", hash = "sha256:52ee893c6a3a968b639ace8015bec9d36594961e156e23315c8e8e51401fa50b", size = 395137 } +sdist = { url = "https://files.pythonhosted.org/packages/ec/d7/6c09dd7ce4c7837e4cdb11dce980cb45ae3cd87677298dc3b781b6bce7d3/griffe-1.14.0.tar.gz", hash = "sha256:9d2a15c1eca966d68e00517de5d69dd1bc5c9f2335ef6c1775362ba5b8651a13", size = 424684, upload-time = "2025-09-05T15:02:29.167Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/58/c6/5c20af38c2a57c15d87f7f38bee77d63c1d2a3689f74fefaf35915dd12b2/griffe-1.7.3-py3-none-any.whl", hash = "sha256:c6b3ee30c2f0f17f30bcdef5068d6ab7a2a4f1b8bf1a3e74b56fffd21e1c5f75", size = 129303 }, + { url = "https://files.pythonhosted.org/packages/2a/b1/9ff6578d789a89812ff21e4e0f80ffae20a65d5dd84e7a17873fe3b365be/griffe-1.14.0-py3-none-any.whl", hash = "sha256:0e9d52832cccf0f7188cfe585ba962d2674b241c01916d780925df34873bceb0", size = 144439, upload-time = "2025-09-05T15:02:27.511Z" }, ] [[package]] @@ -308,6 +375,8 @@ source = { editable = "." } dependencies = [ { name = "aqtp" }, { name = "equinox" }, + { name = "jax", version = "0.6.2", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version < '3.11'" }, + { name = "jax", version = "0.7.2", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version >= '3.11'" }, { name = "jaxtyping" }, { name = "jmp" }, { name = "safetensors" }, @@ -315,7 +384,8 @@ dependencies = [ [package.dev-dependencies] dev = [ - { name = "chex" }, + { name = "chex", version = "0.1.90", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version < '3.11'" }, + { name = "chex", version = "0.1.91", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version >= '3.11'" }, { name = "mkdocs" }, { name = "mkdocs-include-markdown-plugin" }, { name = "mkdocs-literate-nav" }, @@ -334,6 +404,7 @@ dev = [ requires-dist = [ { name = "aqtp", specifier = ">=0.8.2" }, { name = "equinox", specifier = ">=0.10.6" }, + { name = "jax", specifier = ">=0.6.2" }, { name = "jaxtyping", specifier = ">=0.2.20" }, { name = "jmp", specifier = ">=0.0.4" }, { name = "safetensors", specifier = ">=0.4.3" }, @@ -360,104 +431,166 @@ dev = [ name = "hjson" version = "3.1.0" source = { registry = "https://pypi.org/simple" } -sdist = { url = "https://files.pythonhosted.org/packages/82/e5/0b56d723a76ca67abadbf7fb71609fb0ea7e6926e94fcca6c65a85b36a0e/hjson-3.1.0.tar.gz", hash = "sha256:55af475a27cf83a7969c808399d7bccdec8fb836a07ddbd574587593b9cdcf75", size = 40541 } +sdist = { url = "https://files.pythonhosted.org/packages/82/e5/0b56d723a76ca67abadbf7fb71609fb0ea7e6926e94fcca6c65a85b36a0e/hjson-3.1.0.tar.gz", hash = "sha256:55af475a27cf83a7969c808399d7bccdec8fb836a07ddbd574587593b9cdcf75", size = 40541, upload-time = "2022-08-13T02:53:01.919Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/1f/7f/13cd798d180af4bf4c0ceddeefba2b864a63c71645abc0308b768d67bb81/hjson-3.1.0-py3-none-any.whl", hash = "sha256:65713cdcf13214fb554eb8b4ef803419733f4f5e551047c9b711098ab7186b89", size = 54018 }, + { url = "https://files.pythonhosted.org/packages/1f/7f/13cd798d180af4bf4c0ceddeefba2b864a63c71645abc0308b768d67bb81/hjson-3.1.0-py3-none-any.whl", hash = "sha256:65713cdcf13214fb554eb8b4ef803419733f4f5e551047c9b711098ab7186b89", size = 54018, upload-time = "2022-08-13T02:52:59.899Z" }, ] [[package]] name = "humanize" -version = "4.12.3" +version = "4.13.0" source = { registry = "https://pypi.org/simple" } -sdist = { url = "https://files.pythonhosted.org/packages/22/d1/bbc4d251187a43f69844f7fd8941426549bbe4723e8ff0a7441796b0789f/humanize-4.12.3.tar.gz", hash = "sha256:8430be3a615106fdfceb0b2c1b41c4c98c6b0fc5cc59663a5539b111dd325fb0", size = 80514 } +sdist = { url = "https://files.pythonhosted.org/packages/98/1d/3062fcc89ee05a715c0b9bfe6490c00c576314f27ffee3a704122c6fd259/humanize-4.13.0.tar.gz", hash = "sha256:78f79e68f76f0b04d711c4e55d32bebef5be387148862cb1ef83d2b58e7935a0", size = 81884, upload-time = "2025-08-25T09:39:20.04Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/a0/1e/62a2ec3104394a2975a2629eec89276ede9dbe717092f6966fcf963e1bf0/humanize-4.12.3-py3-none-any.whl", hash = "sha256:2cbf6370af06568fa6d2da77c86edb7886f3160ecd19ee1ffef07979efc597f6", size = 128487 }, + { url = "https://files.pythonhosted.org/packages/1e/c7/316e7ca04d26695ef0635dc81683d628350810eb8e9b2299fc08ba49f366/humanize-4.13.0-py3-none-any.whl", hash = "sha256:b810820b31891813b1673e8fec7f1ed3312061eab2f26e3fa192c393d11ed25f", size = 128869, upload-time = "2025-08-25T09:39:18.54Z" }, ] [[package]] name = "identify" -version = "2.6.12" +version = "2.6.14" source = { registry = "https://pypi.org/simple" } -sdist = { url = "https://files.pythonhosted.org/packages/a2/88/d193a27416618628a5eea64e3223acd800b40749a96ffb322a9b55a49ed1/identify-2.6.12.tar.gz", hash = "sha256:d8de45749f1efb108badef65ee8386f0f7bb19a7f26185f74de6367bffbaf0e6", size = 99254 } +sdist = { url = "https://files.pythonhosted.org/packages/52/c4/62963f25a678f6a050fb0505a65e9e726996171e6dbe1547f79619eefb15/identify-2.6.14.tar.gz", hash = "sha256:663494103b4f717cb26921c52f8751363dc89db64364cd836a9bf1535f53cd6a", size = 99283, upload-time = "2025-09-06T19:30:52.938Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/7a/cd/18f8da995b658420625f7ef13f037be53ae04ec5ad33f9b718240dcfd48c/identify-2.6.12-py2.py3-none-any.whl", hash = "sha256:ad9672d5a72e0d2ff7c5c8809b62dfa60458626352fb0eb7b55e69bdc45334a2", size = 99145 }, + { url = "https://files.pythonhosted.org/packages/e5/ae/2ad30f4652712c82f1c23423d79136fbce338932ad166d70c1efb86a5998/identify-2.6.14-py2.py3-none-any.whl", hash = "sha256:11a073da82212c6646b1f39bb20d4483bfb9543bd5566fec60053c4bb309bf2e", size = 99172, upload-time = "2025-09-06T19:30:51.759Z" }, ] [[package]] name = "idna" version = "3.10" source = { registry = "https://pypi.org/simple" } -sdist = { url = "https://files.pythonhosted.org/packages/f1/70/7703c29685631f5a7590aa73f1f1d3fa9a380e654b86af429e0934a32f7d/idna-3.10.tar.gz", hash = "sha256:12f65c9b470abda6dc35cf8e63cc574b1c52b11df2c86030af0ac09b01b13ea9", size = 190490 } +sdist = { url = "https://files.pythonhosted.org/packages/f1/70/7703c29685631f5a7590aa73f1f1d3fa9a380e654b86af429e0934a32f7d/idna-3.10.tar.gz", hash = "sha256:12f65c9b470abda6dc35cf8e63cc574b1c52b11df2c86030af0ac09b01b13ea9", size = 190490, upload-time = "2024-09-15T18:07:39.745Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/76/c6/c88e154df9c4e1a2a66ccf0005a88dfb2650c1dffb6f5ce603dfbd452ce3/idna-3.10-py3-none-any.whl", hash = "sha256:946d195a0d259cbba61165e88e65941f16e9b36ea6ddb97f00452bae8b1287d3", size = 70442 }, + { url = "https://files.pythonhosted.org/packages/76/c6/c88e154df9c4e1a2a66ccf0005a88dfb2650c1dffb6f5ce603dfbd452ce3/idna-3.10-py3-none-any.whl", hash = "sha256:946d195a0d259cbba61165e88e65941f16e9b36ea6ddb97f00452bae8b1287d3", size = 70442, upload-time = "2024-09-15T18:07:37.964Z" }, ] [[package]] name = "importlib-resources" version = "6.5.2" source = { registry = "https://pypi.org/simple" } -sdist = { url = "https://files.pythonhosted.org/packages/cf/8c/f834fbf984f691b4f7ff60f50b514cc3de5cc08abfc3295564dd89c5e2e7/importlib_resources-6.5.2.tar.gz", hash = "sha256:185f87adef5bcc288449d98fb4fba07cea78bc036455dd44c5fc4a2fe78fed2c", size = 44693 } +sdist = { url = "https://files.pythonhosted.org/packages/cf/8c/f834fbf984f691b4f7ff60f50b514cc3de5cc08abfc3295564dd89c5e2e7/importlib_resources-6.5.2.tar.gz", hash = "sha256:185f87adef5bcc288449d98fb4fba07cea78bc036455dd44c5fc4a2fe78fed2c", size = 44693, upload-time = "2025-01-03T18:51:56.698Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/a4/ed/1f1afb2e9e7f38a545d628f864d562a5ae64fe6f7a10e28ffb9b185b4e89/importlib_resources-6.5.2-py3-none-any.whl", hash = "sha256:789cfdc3ed28c78b67a06acb8126751ced69a3d5f79c095a98298cd8a760ccec", size = 37461 }, + { url = "https://files.pythonhosted.org/packages/a4/ed/1f1afb2e9e7f38a545d628f864d562a5ae64fe6f7a10e28ffb9b185b4e89/importlib_resources-6.5.2-py3-none-any.whl", hash = "sha256:789cfdc3ed28c78b67a06acb8126751ced69a3d5f79c095a98298cd8a760ccec", size = 37461, upload-time = "2025-01-03T18:51:54.306Z" }, ] [[package]] name = "iniconfig" version = "2.1.0" source = { registry = "https://pypi.org/simple" } -sdist = { url = "https://files.pythonhosted.org/packages/f2/97/ebf4da567aa6827c909642694d71c9fcf53e5b504f2d96afea02718862f3/iniconfig-2.1.0.tar.gz", hash = "sha256:3abbd2e30b36733fee78f9c7f7308f2d0050e88f0087fd25c2645f63c773e1c7", size = 4793 } +sdist = { url = "https://files.pythonhosted.org/packages/f2/97/ebf4da567aa6827c909642694d71c9fcf53e5b504f2d96afea02718862f3/iniconfig-2.1.0.tar.gz", hash = "sha256:3abbd2e30b36733fee78f9c7f7308f2d0050e88f0087fd25c2645f63c773e1c7", size = 4793, upload-time = "2025-03-19T20:09:59.721Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/2c/e1/e6716421ea10d38022b952c159d5161ca1193197fb744506875fbb87ea7b/iniconfig-2.1.0-py3-none-any.whl", hash = "sha256:9deba5723312380e77435581c6bf4935c94cbfab9b1ed33ef8d238ea168eb760", size = 6050 }, + { url = "https://files.pythonhosted.org/packages/2c/e1/e6716421ea10d38022b952c159d5161ca1193197fb744506875fbb87ea7b/iniconfig-2.1.0-py3-none-any.whl", hash = "sha256:9deba5723312380e77435581c6bf4935c94cbfab9b1ed33ef8d238ea168eb760", size = 6050, upload-time = "2025-03-19T20:10:01.071Z" }, ] [[package]] name = "jax" version = "0.6.2" source = { registry = "https://pypi.org/simple" } +resolution-markers = [ + "python_full_version < '3.11'", +] dependencies = [ - { name = "jaxlib" }, - { name = "ml-dtypes" }, + { name = "jaxlib", version = "0.6.2", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version < '3.11'" }, + { name = "ml-dtypes", marker = "python_full_version < '3.11'" }, { name = "numpy", version = "2.2.6", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version < '3.11'" }, - { name = "numpy", version = "2.3.1", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version >= '3.11'" }, - { name = "opt-einsum" }, + { name = "opt-einsum", marker = "python_full_version < '3.11'" }, { name = "scipy", version = "1.15.3", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version < '3.11'" }, - { name = "scipy", version = "1.16.0", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version >= '3.11'" }, ] -sdist = { url = "https://files.pythonhosted.org/packages/cf/1e/267f59c8fb7f143c3f778c76cb7ef1389db3fd7e4540f04b9f42ca90764d/jax-0.6.2.tar.gz", hash = "sha256:a437d29038cbc8300334119692744704ca7941490867b9665406b7f90665cd96", size = 2334091 } +sdist = { url = "https://files.pythonhosted.org/packages/cf/1e/267f59c8fb7f143c3f778c76cb7ef1389db3fd7e4540f04b9f42ca90764d/jax-0.6.2.tar.gz", hash = "sha256:a437d29038cbc8300334119692744704ca7941490867b9665406b7f90665cd96", size = 2334091, upload-time = "2025-06-17T23:10:27.186Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/31/a8/97ef0cbb7a17143ace2643d600a7b80d6705b2266fc31078229e406bdef2/jax-0.6.2-py3-none-any.whl", hash = "sha256:bb24a82dc60ccf704dcaf6dbd07d04957f68a6c686db19630dd75260d1fb788c", size = 2722396, upload-time = "2025-06-17T23:10:25.293Z" }, +] + +[[package]] +name = "jax" +version = "0.7.2" +source = { registry = "https://pypi.org/simple" } +resolution-markers = [ + "python_full_version >= '3.13'", + "python_full_version == '3.12.*'", + "python_full_version == '3.11.*'", +] +dependencies = [ + { name = "jaxlib", version = "0.7.2", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version >= '3.11'" }, + { name = "ml-dtypes", marker = "python_full_version >= '3.11'" }, + { name = "numpy", version = "2.3.3", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version >= '3.11'" }, + { name = "opt-einsum", marker = "python_full_version >= '3.11'" }, + { name = "scipy", version = "1.16.2", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version >= '3.11'" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/8f/e7/1e8e8af59b7659c83dc07dfa1dc23bc13551e5ef89bdef19ced044a497fc/jax-0.7.2.tar.gz", hash = "sha256:71a42b964bc6d52e819311429e6c0f5742e2a4650226dab1a1dd26fd986ca70d", size = 2434085, upload-time = "2025-09-16T16:48:53.108Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/31/a8/97ef0cbb7a17143ace2643d600a7b80d6705b2266fc31078229e406bdef2/jax-0.6.2-py3-none-any.whl", hash = "sha256:bb24a82dc60ccf704dcaf6dbd07d04957f68a6c686db19630dd75260d1fb788c", size = 2722396 }, + { url = "https://files.pythonhosted.org/packages/d5/e6/5fd0f6fff79eb47469ff9c4fa27125b661517a2fbf8884689b02e9fdfaa8/jax-0.7.2-py3-none-any.whl", hash = "sha256:e7e32f9be51ae5cc6854225958c57de8cca2187d279844338465b15e8a1fe7f2", size = 2835570, upload-time = "2025-09-16T16:48:51.33Z" }, ] [[package]] name = "jaxlib" version = "0.6.2" source = { registry = "https://pypi.org/simple" } +resolution-markers = [ + "python_full_version < '3.11'", +] dependencies = [ - { name = "ml-dtypes" }, + { name = "ml-dtypes", marker = "python_full_version < '3.11'" }, { name = "numpy", version = "2.2.6", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version < '3.11'" }, - { name = "numpy", version = "2.3.1", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version >= '3.11'" }, { name = "scipy", version = "1.15.3", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version < '3.11'" }, - { name = "scipy", version = "1.16.0", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version >= '3.11'" }, -] -wheels = [ - { url = "https://files.pythonhosted.org/packages/15/c5/41598634c99cbebba46e6777286fb76abc449d33d50aeae5d36128ca8803/jaxlib-0.6.2-cp310-cp310-macosx_11_0_arm64.whl", hash = "sha256:da4601b2b5dc8c23d6afb293eacfb9aec4e1d1871cb2f29c5a151d103e73b0f8", size = 54298019 }, - { url = "https://files.pythonhosted.org/packages/81/af/db07d746cd5867d5967528e7811da53374e94f64e80a890d6a5a4b95b130/jaxlib-0.6.2-cp310-cp310-manylinux2014_aarch64.whl", hash = "sha256:4205d098ce8efb5f7fe2fe5098bae6036094dc8d8829f5e0e0d7a9b155326336", size = 79440052 }, - { url = "https://files.pythonhosted.org/packages/7e/d8/b7ae9e819c62c1854dbc2c70540a5c041173fbc8bec5e78ab7fd615a4aee/jaxlib-0.6.2-cp310-cp310-manylinux2014_x86_64.whl", hash = "sha256:c087a0eb6fb7f6f8f54d56f4730328dfde5040dd3b5ddfa810e7c28ea7102b42", size = 89917034 }, - { url = "https://files.pythonhosted.org/packages/fd/e5/87e91bc70569ac5c3e3449eefcaf47986e892f10cfe1d5e5720dceae3068/jaxlib-0.6.2-cp310-cp310-win_amd64.whl", hash = "sha256:153eaa51f778b60851720729d4f461a91edd9ba3932f6f3bc598d4413870038b", size = 57896337 }, - { url = "https://files.pythonhosted.org/packages/a4/ee/6899b0aed36a4acc51319465ddd83c7c300a062a9e236cceee00984ffe0b/jaxlib-0.6.2-cp311-cp311-macosx_11_0_arm64.whl", hash = "sha256:a208ff61c58128d306bb4e5ad0858bd2b0960f2c1c10ad42c548f74a60c0020e", size = 54300346 }, - { url = "https://files.pythonhosted.org/packages/e6/03/34bb6b346609079a71942cfbf507892e3c877a06a430a0df8429c455cebc/jaxlib-0.6.2-cp311-cp311-manylinux2014_aarch64.whl", hash = "sha256:11eae7e05bc5a79875da36324afb9eddd4baeaef2a0386caf6d4f3720b9aef28", size = 79438425 }, - { url = "https://files.pythonhosted.org/packages/80/02/49b05cbab519ffd3cb79586336451fbbf8b6523f67128a794acc9f179000/jaxlib-0.6.2-cp311-cp311-manylinux2014_x86_64.whl", hash = "sha256:335d7e3515ce78b52a410136f46aa4a7ea14d0e7d640f34e1e137409554ad0ac", size = 89920354 }, - { url = "https://files.pythonhosted.org/packages/a7/7a/93b28d9452b46c15fc28dd65405672fc8a158b35d46beabaa0fe9631afb0/jaxlib-0.6.2-cp311-cp311-win_amd64.whl", hash = "sha256:c6815509997d6b05e5c9daa7994b9ad473ce3e8c8a17bdbbcacc3c744f76f7a0", size = 57895707 }, - { url = "https://files.pythonhosted.org/packages/ac/db/05e702d2534e87abf606b1067b46a273b120e6adc7d459696e3ce7399317/jaxlib-0.6.2-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:34d8a684a8be949dd87dd4acc97101b4106a0dc9ad151ec891da072319a57b99", size = 54301644 }, - { url = "https://files.pythonhosted.org/packages/0d/8a/b0a96887b97a25d45ae2c30e4acecd2f95acd074c18ec737dda8c5cc7016/jaxlib-0.6.2-cp312-cp312-manylinux2014_aarch64.whl", hash = "sha256:87ec2dc9c3ed9ab936eec8535160c5fbd2c849948559f1c5daa75f63fabe5942", size = 79439161 }, - { url = "https://files.pythonhosted.org/packages/ba/e8/71c2555431edb5dd115cf86a7b599aa7e1be26728d89ae59aa11251d299c/jaxlib-0.6.2-cp312-cp312-manylinux2014_x86_64.whl", hash = "sha256:f1dd09b481a93c1d4c750013f467f74194493ba7bd29fcd4d1cec16e3a214f65", size = 89942952 }, - { url = "https://files.pythonhosted.org/packages/de/3a/06849113c844b86d20174df54735c84202ccf82cbd36d805f478c834418b/jaxlib-0.6.2-cp312-cp312-win_amd64.whl", hash = "sha256:921dbd4db214eba19a29ba9f2450d880e08b2b2c7b968f28cc89da3e62366af4", size = 57919603 }, - { url = "https://files.pythonhosted.org/packages/af/38/bed4279c2a3407820ed8bcd72dbad43c330ada35f88fafe9952b35abf785/jaxlib-0.6.2-cp313-cp313-macosx_11_0_arm64.whl", hash = "sha256:bff67b188133ce1f0111c7b163ac321fd646b59ed221ea489063e2e0f85cb967", size = 54300638 }, - { url = "https://files.pythonhosted.org/packages/52/dc/9e35a1dc089ddf3d6be53ef2e6ba4718c5b6c0f90bccc535a20edac0c895/jaxlib-0.6.2-cp313-cp313-manylinux2014_aarch64.whl", hash = "sha256:70498837caf538bd458ff6858c8bfd404db82015aba8f663670197fa9900ff02", size = 79439983 }, - { url = "https://files.pythonhosted.org/packages/34/16/e93f0184b80a4e1ad38c6998aa3a2f7569c0b0152cbae39f7572393eda04/jaxlib-0.6.2-cp313-cp313-manylinux2014_x86_64.whl", hash = "sha256:f94163f14c8fd3ba93ae14b631abacf14cb031bba0b59138869984b4d10375f8", size = 89941720 }, - { url = "https://files.pythonhosted.org/packages/06/b9/ea50792ee0333dba764e06c305fe098bce1cb938dcb66fbe2fc47ef5dd02/jaxlib-0.6.2-cp313-cp313-win_amd64.whl", hash = "sha256:b977604cd36c74b174d25ed685017379468138eb747d865f75e466cb273c801d", size = 57919073 }, - { url = "https://files.pythonhosted.org/packages/09/ce/9596391c104a0547fcaf6a8c72078bbae79dbc8e7f0843dc8318f6606328/jaxlib-0.6.2-cp313-cp313t-manylinux2014_aarch64.whl", hash = "sha256:39cf9555f85ae1ce2e2c1a59fc71f2eca4f9867a7cb934fef881ba56b11371d1", size = 79579638 }, - { url = "https://files.pythonhosted.org/packages/10/79/f6e80f7f4cacfc9f03e64ac57ecb856b140de7c2f939b25f8dcf1aff63f9/jaxlib-0.6.2-cp313-cp313t-manylinux2014_x86_64.whl", hash = "sha256:3abd536e44b05fb1657507e3ff1fc3691f99613bae3921ecab9e82f27255f784", size = 90066675 }, +] +wheels = [ + { url = "https://files.pythonhosted.org/packages/15/c5/41598634c99cbebba46e6777286fb76abc449d33d50aeae5d36128ca8803/jaxlib-0.6.2-cp310-cp310-macosx_11_0_arm64.whl", hash = "sha256:da4601b2b5dc8c23d6afb293eacfb9aec4e1d1871cb2f29c5a151d103e73b0f8", size = 54298019, upload-time = "2025-06-17T23:10:36.916Z" }, + { url = "https://files.pythonhosted.org/packages/81/af/db07d746cd5867d5967528e7811da53374e94f64e80a890d6a5a4b95b130/jaxlib-0.6.2-cp310-cp310-manylinux2014_aarch64.whl", hash = "sha256:4205d098ce8efb5f7fe2fe5098bae6036094dc8d8829f5e0e0d7a9b155326336", size = 79440052, upload-time = "2025-06-17T23:10:41.282Z" }, + { url = "https://files.pythonhosted.org/packages/7e/d8/b7ae9e819c62c1854dbc2c70540a5c041173fbc8bec5e78ab7fd615a4aee/jaxlib-0.6.2-cp310-cp310-manylinux2014_x86_64.whl", hash = "sha256:c087a0eb6fb7f6f8f54d56f4730328dfde5040dd3b5ddfa810e7c28ea7102b42", size = 89917034, upload-time = "2025-06-17T23:10:45.897Z" }, + { url = "https://files.pythonhosted.org/packages/fd/e5/87e91bc70569ac5c3e3449eefcaf47986e892f10cfe1d5e5720dceae3068/jaxlib-0.6.2-cp310-cp310-win_amd64.whl", hash = "sha256:153eaa51f778b60851720729d4f461a91edd9ba3932f6f3bc598d4413870038b", size = 57896337, upload-time = "2025-06-17T23:10:50.179Z" }, + { url = "https://files.pythonhosted.org/packages/a4/ee/6899b0aed36a4acc51319465ddd83c7c300a062a9e236cceee00984ffe0b/jaxlib-0.6.2-cp311-cp311-macosx_11_0_arm64.whl", hash = "sha256:a208ff61c58128d306bb4e5ad0858bd2b0960f2c1c10ad42c548f74a60c0020e", size = 54300346, upload-time = "2025-06-17T23:10:54.591Z" }, + { url = "https://files.pythonhosted.org/packages/e6/03/34bb6b346609079a71942cfbf507892e3c877a06a430a0df8429c455cebc/jaxlib-0.6.2-cp311-cp311-manylinux2014_aarch64.whl", hash = "sha256:11eae7e05bc5a79875da36324afb9eddd4baeaef2a0386caf6d4f3720b9aef28", size = 79438425, upload-time = "2025-06-17T23:10:58.356Z" }, + { url = "https://files.pythonhosted.org/packages/80/02/49b05cbab519ffd3cb79586336451fbbf8b6523f67128a794acc9f179000/jaxlib-0.6.2-cp311-cp311-manylinux2014_x86_64.whl", hash = "sha256:335d7e3515ce78b52a410136f46aa4a7ea14d0e7d640f34e1e137409554ad0ac", size = 89920354, upload-time = "2025-06-17T23:11:03.086Z" }, + { url = "https://files.pythonhosted.org/packages/a7/7a/93b28d9452b46c15fc28dd65405672fc8a158b35d46beabaa0fe9631afb0/jaxlib-0.6.2-cp311-cp311-win_amd64.whl", hash = "sha256:c6815509997d6b05e5c9daa7994b9ad473ce3e8c8a17bdbbcacc3c744f76f7a0", size = 57895707, upload-time = "2025-06-17T23:11:07.074Z" }, + { url = "https://files.pythonhosted.org/packages/ac/db/05e702d2534e87abf606b1067b46a273b120e6adc7d459696e3ce7399317/jaxlib-0.6.2-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:34d8a684a8be949dd87dd4acc97101b4106a0dc9ad151ec891da072319a57b99", size = 54301644, upload-time = "2025-06-17T23:11:10.977Z" }, + { url = "https://files.pythonhosted.org/packages/0d/8a/b0a96887b97a25d45ae2c30e4acecd2f95acd074c18ec737dda8c5cc7016/jaxlib-0.6.2-cp312-cp312-manylinux2014_aarch64.whl", hash = "sha256:87ec2dc9c3ed9ab936eec8535160c5fbd2c849948559f1c5daa75f63fabe5942", size = 79439161, upload-time = "2025-06-17T23:11:14.822Z" }, + { url = "https://files.pythonhosted.org/packages/ba/e8/71c2555431edb5dd115cf86a7b599aa7e1be26728d89ae59aa11251d299c/jaxlib-0.6.2-cp312-cp312-manylinux2014_x86_64.whl", hash = "sha256:f1dd09b481a93c1d4c750013f467f74194493ba7bd29fcd4d1cec16e3a214f65", size = 89942952, upload-time = "2025-06-17T23:11:19.181Z" }, + { url = "https://files.pythonhosted.org/packages/de/3a/06849113c844b86d20174df54735c84202ccf82cbd36d805f478c834418b/jaxlib-0.6.2-cp312-cp312-win_amd64.whl", hash = "sha256:921dbd4db214eba19a29ba9f2450d880e08b2b2c7b968f28cc89da3e62366af4", size = 57919603, upload-time = "2025-06-17T23:11:23.207Z" }, + { url = "https://files.pythonhosted.org/packages/af/38/bed4279c2a3407820ed8bcd72dbad43c330ada35f88fafe9952b35abf785/jaxlib-0.6.2-cp313-cp313-macosx_11_0_arm64.whl", hash = "sha256:bff67b188133ce1f0111c7b163ac321fd646b59ed221ea489063e2e0f85cb967", size = 54300638, upload-time = "2025-06-17T23:11:26.372Z" }, + { url = "https://files.pythonhosted.org/packages/52/dc/9e35a1dc089ddf3d6be53ef2e6ba4718c5b6c0f90bccc535a20edac0c895/jaxlib-0.6.2-cp313-cp313-manylinux2014_aarch64.whl", hash = "sha256:70498837caf538bd458ff6858c8bfd404db82015aba8f663670197fa9900ff02", size = 79439983, upload-time = "2025-06-17T23:11:30.016Z" }, + { url = "https://files.pythonhosted.org/packages/34/16/e93f0184b80a4e1ad38c6998aa3a2f7569c0b0152cbae39f7572393eda04/jaxlib-0.6.2-cp313-cp313-manylinux2014_x86_64.whl", hash = "sha256:f94163f14c8fd3ba93ae14b631abacf14cb031bba0b59138869984b4d10375f8", size = 89941720, upload-time = "2025-06-17T23:11:34.62Z" }, + { url = "https://files.pythonhosted.org/packages/06/b9/ea50792ee0333dba764e06c305fe098bce1cb938dcb66fbe2fc47ef5dd02/jaxlib-0.6.2-cp313-cp313-win_amd64.whl", hash = "sha256:b977604cd36c74b174d25ed685017379468138eb747d865f75e466cb273c801d", size = 57919073, upload-time = "2025-06-17T23:11:39.344Z" }, + { url = "https://files.pythonhosted.org/packages/09/ce/9596391c104a0547fcaf6a8c72078bbae79dbc8e7f0843dc8318f6606328/jaxlib-0.6.2-cp313-cp313t-manylinux2014_aarch64.whl", hash = "sha256:39cf9555f85ae1ce2e2c1a59fc71f2eca4f9867a7cb934fef881ba56b11371d1", size = 79579638, upload-time = "2025-06-17T23:11:43.054Z" }, + { url = "https://files.pythonhosted.org/packages/10/79/f6e80f7f4cacfc9f03e64ac57ecb856b140de7c2f939b25f8dcf1aff63f9/jaxlib-0.6.2-cp313-cp313t-manylinux2014_x86_64.whl", hash = "sha256:3abd536e44b05fb1657507e3ff1fc3691f99613bae3921ecab9e82f27255f784", size = 90066675, upload-time = "2025-06-17T23:11:47.454Z" }, +] + +[[package]] +name = "jaxlib" +version = "0.7.2" +source = { registry = "https://pypi.org/simple" } +resolution-markers = [ + "python_full_version >= '3.13'", + "python_full_version == '3.12.*'", + "python_full_version == '3.11.*'", +] +dependencies = [ + { name = "ml-dtypes", marker = "python_full_version >= '3.11'" }, + { name = "numpy", version = "2.3.3", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version >= '3.11'" }, + { name = "scipy", version = "1.16.2", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version >= '3.11'" }, +] +wheels = [ + { url = "https://files.pythonhosted.org/packages/55/fe/41e1df8a02acdc12472b2922e41495cf0a9b805f5fd1f163c9aaf81b30df/jaxlib-0.7.2-cp311-cp311-macosx_11_0_arm64.whl", hash = "sha256:9fbf90afce30e34eba2ea929a506f5907bdd4062358122de499ce9e671a0ba1f", size = 53550443, upload-time = "2025-09-16T16:49:04.061Z" }, + { url = "https://files.pythonhosted.org/packages/cb/9b/c86d5c3cf354326b6d0c89f7a1562299e0cdcf3f507c82a6aca8ce77dcb6/jaxlib-0.7.2-cp311-cp311-manylinux_2_27_aarch64.whl", hash = "sha256:8ca7003351fbe8ccfa2fa5a493ec2dfbf2df92441306cf5c3b970508eedb92ab", size = 71551113, upload-time = "2025-09-16T16:49:07.95Z" }, + { url = "https://files.pythonhosted.org/packages/80/dd/4a0565f636c0e702777bdb0afeeb262a019039869268194cbd0440ad47da/jaxlib-0.7.2-cp311-cp311-manylinux_2_27_x86_64.whl", hash = "sha256:4382006235cced59d2f795acc983c1bedcfbca4fea8f9461311d61c6a793ae66", size = 78159922, upload-time = "2025-09-16T16:49:11.656Z" }, + { url = "https://files.pythonhosted.org/packages/28/03/199d9ce30981c6c8d2ae3a442d2fc3eeb1f31fa6aab9620ff1d3d3fdfd7f/jaxlib-0.7.2-cp311-cp311-win_amd64.whl", hash = "sha256:3b37eb937e0b8ed4f9b265fdf46a3cf64e1decd4f41c0053e96540d39bd7050c", size = 58013064, upload-time = "2025-09-16T16:49:15.063Z" }, + { url = "https://files.pythonhosted.org/packages/df/82/324ffb86a6de8c149689b499b6dc6e4f83684fe43ae9e81c8e5eb91bc50f/jaxlib-0.7.2-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:bd6d1c53bd475e0e768a54af98b1642fb49d7304cf055ceebb1d01e89d38a1cb", size = 53563644, upload-time = "2025-09-16T16:49:18.04Z" }, + { url = "https://files.pythonhosted.org/packages/89/6a/689b177de0672a7b4fe5489eec7cbb11305959c3af8da7d646e7f3aeb754/jaxlib-0.7.2-cp312-cp312-manylinux_2_27_aarch64.whl", hash = "sha256:9b5a0d357497611a113d207fb2c1997f01ab7a175870700812220f0bcaa31822", size = 71557871, upload-time = "2025-09-16T16:49:20.964Z" }, + { url = "https://files.pythonhosted.org/packages/7b/73/b44fbe943c9e02e25c99eb64e6b86e2dde8d918d064326813b5bbe620951/jaxlib-0.7.2-cp312-cp312-manylinux_2_27_x86_64.whl", hash = "sha256:11f32319e662ccff66859eb393757050d8971bd880bc4dd70dec6434d890fb59", size = 78167979, upload-time = "2025-09-16T16:49:24.607Z" }, + { url = "https://files.pythonhosted.org/packages/ee/0e/13d5264bbe08f03ae9e7abe7aa3041b5c29f9daf5493b8156ae7baa6cbf1/jaxlib-0.7.2-cp312-cp312-win_amd64.whl", hash = "sha256:b53cf3a7ed342ca1a9f419cc7a3c387598fc743043ba4a7c5895ebc4d62fa05a", size = 58040487, upload-time = "2025-09-16T16:49:28.101Z" }, + { url = "https://files.pythonhosted.org/packages/57/48/4eafdde441b6e37a20b969033b0c73680eb4bf59003518d9099459a115d0/jaxlib-0.7.2-cp313-cp313-macosx_11_0_arm64.whl", hash = "sha256:e1b3dfe9915825fce006ea095b853f57681845c5bfa80975dcc3788936371fb0", size = 53562665, upload-time = "2025-09-16T16:49:31.05Z" }, + { url = "https://files.pythonhosted.org/packages/14/a2/3ed83db683a8f0cd7c60266f1d8e34137c6d13cb0f6e8b66717ea3f38665/jaxlib-0.7.2-cp313-cp313-manylinux_2_27_aarch64.whl", hash = "sha256:97c793e97be5ddc73b3e85e6ce8ad3709e8054f75ea219cc0cb4f0805a65af06", size = 71556806, upload-time = "2025-09-16T16:49:34.45Z" }, + { url = "https://files.pythonhosted.org/packages/3e/0b/a33add48e904dd88a52d4653cc8290da0f2d3dc132c60c5dbda6783f4e4a/jaxlib-0.7.2-cp313-cp313-manylinux_2_27_x86_64.whl", hash = "sha256:49d99620486effda87400024723a452306566996e3de719ee633f05220d1ee77", size = 78167866, upload-time = "2025-09-16T16:49:37.838Z" }, + { url = "https://files.pythonhosted.org/packages/90/9b/2049f4e5e5527cee1cf26a9f037b91abac85503074b5420678bc199b1af7/jaxlib-0.7.2-cp313-cp313-win_amd64.whl", hash = "sha256:59081f79245a40a6a2590e660fb2981ac541112893a6617121822a6afdbb5ead", size = 58041016, upload-time = "2025-09-16T16:49:40.962Z" }, + { url = "https://files.pythonhosted.org/packages/5e/da/79ab9f3d34b3ea6b30dacdb3415afd6a9d8160a8bdb48ed581192e80fb5c/jaxlib-0.7.2-cp313-cp313t-macosx_11_0_arm64.whl", hash = "sha256:3ba65706622ba6b8cd33be51d2b8a3619ac4023faa18de67158ae6c67dc7097f", size = 53649187, upload-time = "2025-09-16T16:49:43.817Z" }, + { url = "https://files.pythonhosted.org/packages/87/0f/b39c008ef8015dcfafee04a5f575546a8111d0b9baee027fee2c89f40549/jaxlib-0.7.2-cp313-cp313t-manylinux_2_27_aarch64.whl", hash = "sha256:a1427c5f61c52d792fc55678cdc005ad9889ecd61e12dd312494e3daa71ce58d", size = 71654672, upload-time = "2025-09-16T16:49:46.82Z" }, + { url = "https://files.pythonhosted.org/packages/f2/7e/883e9bc1198f64a45505c0d83d013a1a068265c0f8c53ba7b28c874562f9/jaxlib-0.7.2-cp313-cp313t-manylinux_2_27_x86_64.whl", hash = "sha256:4803d42c9019f7650da15db32dde6f17cd49279da72000878b045e31524e2cda", size = 78265965, upload-time = "2025-09-16T16:49:50.484Z" }, + { url = "https://files.pythonhosted.org/packages/de/9c/44efc0f1636e96292339d9fbef34261ba57d7197d527c302d52fac584016/jaxlib-0.7.2-cp314-cp314-macosx_11_0_arm64.whl", hash = "sha256:b24ff1c564033bbe8dc4a14690e3fdb89b7e15230474afda6b2c1c90ef94bf32", size = 53565475, upload-time = "2025-09-16T16:49:53.708Z" }, + { url = "https://files.pythonhosted.org/packages/68/99/4b1ff7240b62e4d812f7fef28422d3927dd288a2ed9d54471f1eeb0b93e8/jaxlib-0.7.2-cp314-cp314-manylinux_2_27_aarch64.whl", hash = "sha256:7c70385cf7a0ea5feebd47d5a45816b3b1abfd0487060da58173f175cfd318a8", size = 71563416, upload-time = "2025-09-16T16:49:57.172Z" }, + { url = "https://files.pythonhosted.org/packages/8a/00/d8f5dc1113b55eae3d2f74e424b13de152478cd73f3d40d96b359307106c/jaxlib-0.7.2-cp314-cp314-manylinux_2_27_x86_64.whl", hash = "sha256:c76fb5fbb3ca2417f881ecbadd0516ea5ab9cc49daeab079752dc7f7a4951f0d", size = 78182392, upload-time = "2025-09-16T16:50:00.749Z" }, + { url = "https://files.pythonhosted.org/packages/be/0b/f0e2f6c391c2691b4ec7d32045832270148182d6e3fbb15d6d04027c7bec/jaxlib-0.7.2-cp314-cp314-win_amd64.whl", hash = "sha256:2554fcb4835efafdf2cc92754733aec2a566d26716ad95ea5a77da1053e6269a", size = 60230144, upload-time = "2025-09-16T16:50:03.993Z" }, + { url = "https://files.pythonhosted.org/packages/68/01/e1c44924d3a2a84a6dbc97d9fa515712decc92199a16a519c44e98dcfe33/jaxlib-0.7.2-cp314-cp314t-macosx_11_0_arm64.whl", hash = "sha256:84e158bbc79eab93b1493cdd031f93e1483b7a26a98edfdd2868f3d0752b0228", size = 53648014, upload-time = "2025-09-16T16:50:07.348Z" }, + { url = "https://files.pythonhosted.org/packages/ee/8e/b16f6f1957aba6736f1c90c0161060deb1c1f4c91ea68cbced3ba7b6e163/jaxlib-0.7.2-cp314-cp314t-manylinux_2_27_aarch64.whl", hash = "sha256:4716dc886bda1372a2c78dc6d3c23e50049044d7c552d22a95a14aac6e040731", size = 71659925, upload-time = "2025-09-16T16:50:11.135Z" }, + { url = "https://files.pythonhosted.org/packages/0c/e2/47c52aa806e98f00754b1c303f85d0594d623a7ff5c8592923f7bae45fce/jaxlib-0.7.2-cp314-cp314t-manylinux_2_27_x86_64.whl", hash = "sha256:3ecc0b2e76c089cef350f7916275431b299a17615e32ced1ece18cdd47df6bd2", size = 78264963, upload-time = "2025-09-16T16:50:14.613Z" }, ] [[package]] @@ -467,9 +600,9 @@ source = { registry = "https://pypi.org/simple" } dependencies = [ { name = "wadler-lindig" }, ] -sdist = { url = "https://files.pythonhosted.org/packages/88/a8/416bd7ea110ec6b68e8868b0f99c985c735adcf7badc491d3c343937260a/jaxtyping-0.3.2.tar.gz", hash = "sha256:f30483fac4b42e915db8ad2414a85c3b63284aa7d3c100b96b59f755cf4a86ad", size = 44989 } +sdist = { url = "https://files.pythonhosted.org/packages/88/a8/416bd7ea110ec6b68e8868b0f99c985c735adcf7badc491d3c343937260a/jaxtyping-0.3.2.tar.gz", hash = "sha256:f30483fac4b42e915db8ad2414a85c3b63284aa7d3c100b96b59f755cf4a86ad", size = 44989, upload-time = "2025-04-23T09:48:16.907Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/c9/b9/281e10e2d967ea5e481683eaec99f55ac5a61085ee60551c36942ef32bef/jaxtyping-0.3.2-py3-none-any.whl", hash = "sha256:6a020fd276226ddb5ac4f5725323843dd65e3c7e85c64fd62431e5f738c74e04", size = 55409 }, + { url = "https://files.pythonhosted.org/packages/c9/b9/281e10e2d967ea5e481683eaec99f55ac5a61085ee60551c36942ef32bef/jaxtyping-0.3.2-py3-none-any.whl", hash = "sha256:6a020fd276226ddb5ac4f5725323843dd65e3c7e85c64fd62431e5f738c74e04", size = 55409, upload-time = "2025-04-23T09:48:15.924Z" }, ] [[package]] @@ -479,9 +612,9 @@ source = { registry = "https://pypi.org/simple" } dependencies = [ { name = "markupsafe" }, ] -sdist = { url = "https://files.pythonhosted.org/packages/df/bf/f7da0350254c0ed7c72f3e33cef02e048281fec7ecec5f032d4aac52226b/jinja2-3.1.6.tar.gz", hash = "sha256:0137fb05990d35f1275a587e9aee6d56da821fc83491a0fb838183be43f66d6d", size = 245115 } +sdist = { url = "https://files.pythonhosted.org/packages/df/bf/f7da0350254c0ed7c72f3e33cef02e048281fec7ecec5f032d4aac52226b/jinja2-3.1.6.tar.gz", hash = "sha256:0137fb05990d35f1275a587e9aee6d56da821fc83491a0fb838183be43f66d6d", size = 245115, upload-time = "2025-03-05T20:05:02.478Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/62/a1/3d680cbfd5f4b8f15abc1d571870c5fc3e594bb582bc3b64ea099db13e56/jinja2-3.1.6-py3-none-any.whl", hash = "sha256:85ece4451f492d0c13c5dd7c13a64681a86afae63a5f347908daf103ce6d2f67", size = 134899 }, + { url = "https://files.pythonhosted.org/packages/62/a1/3d680cbfd5f4b8f15abc1d571870c5fc3e594bb582bc3b64ea099db13e56/jinja2-3.1.6-py3-none-any.whl", hash = "sha256:85ece4451f492d0c13c5dd7c13a64681a86afae63a5f347908daf103ce6d2f67", size = 134899, upload-time = "2025-03-05T20:05:00.369Z" }, ] [[package]] @@ -490,108 +623,135 @@ version = "0.0.4" source = { registry = "https://pypi.org/simple" } dependencies = [ { name = "numpy", version = "2.2.6", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version < '3.11'" }, - { name = "numpy", version = "2.3.1", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version >= '3.11'" }, + { name = "numpy", version = "2.3.3", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version >= '3.11'" }, ] -sdist = { url = "https://files.pythonhosted.org/packages/ab/b0/e90fbbffef4b345329c878a69f0336d3edc5a1f9fcba193931aca2132d62/jmp-0.0.4.tar.gz", hash = "sha256:5dfeb0fd7c7a9f72a70fff0aab9d0cbfae32a809c02f4037ff3485ceb33e1730", size = 18582 } +sdist = { url = "https://files.pythonhosted.org/packages/ab/b0/e90fbbffef4b345329c878a69f0336d3edc5a1f9fcba193931aca2132d62/jmp-0.0.4.tar.gz", hash = "sha256:5dfeb0fd7c7a9f72a70fff0aab9d0cbfae32a809c02f4037ff3485ceb33e1730", size = 18582, upload-time = "2023-01-30T12:47:13.634Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/27/e5/cce82de2831e5aff9332d8d624bb57188f1b2af6ccf6979caf898a8a4348/jmp-0.0.4-py3-none-any.whl", hash = "sha256:6aa7adbddf2bd574b28c7faf6e81a735eb11f53386447896909c6968dc36807d", size = 18274 }, + { url = "https://files.pythonhosted.org/packages/27/e5/cce82de2831e5aff9332d8d624bb57188f1b2af6ccf6979caf898a8a4348/jmp-0.0.4-py3-none-any.whl", hash = "sha256:6aa7adbddf2bd574b28c7faf6e81a735eb11f53386447896909c6968dc36807d", size = 18274, upload-time = "2023-01-30T12:47:11.931Z" }, ] [[package]] name = "markdown" -version = "3.8.2" +version = "3.9" source = { registry = "https://pypi.org/simple" } -sdist = { url = "https://files.pythonhosted.org/packages/d7/c2/4ab49206c17f75cb08d6311171f2d65798988db4360c4d1485bd0eedd67c/markdown-3.8.2.tar.gz", hash = "sha256:247b9a70dd12e27f67431ce62523e675b866d254f900c4fe75ce3dda62237c45", size = 362071 } +sdist = { url = "https://files.pythonhosted.org/packages/8d/37/02347f6d6d8279247a5837082ebc26fc0d5aaeaf75aa013fcbb433c777ab/markdown-3.9.tar.gz", hash = "sha256:d2900fe1782bd33bdbbd56859defef70c2e78fc46668f8eb9df3128138f2cb6a", size = 364585, upload-time = "2025-09-04T20:25:22.885Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/96/2b/34cc11786bc00d0f04d0f5fdc3a2b1ae0b6239eef72d3d345805f9ad92a1/markdown-3.8.2-py3-none-any.whl", hash = "sha256:5c83764dbd4e00bdd94d85a19b8d55ccca20fe35b2e678a1422b380324dd5f24", size = 106827 }, + { url = "https://files.pythonhosted.org/packages/70/ae/44c4a6a4cbb496d93c6257954260fe3a6e91b7bed2240e5dad2a717f5111/markdown-3.9-py3-none-any.whl", hash = "sha256:9f4d91ed810864ea88a6f32c07ba8bee1346c0cc1f6b1f9f6c822f2a9667d280", size = 107441, upload-time = "2025-09-04T20:25:21.784Z" }, ] [[package]] name = "markdown-it-py" -version = "3.0.0" +version = "4.0.0" source = { registry = "https://pypi.org/simple" } dependencies = [ { name = "mdurl" }, ] -sdist = { url = "https://files.pythonhosted.org/packages/38/71/3b932df36c1a044d397a1f92d1cf91ee0a503d91e470cbd670aa66b07ed0/markdown-it-py-3.0.0.tar.gz", hash = "sha256:e3f60a94fa066dc52ec76661e37c851cb232d92f9886b15cb560aaada2df8feb", size = 74596 } +sdist = { url = "https://files.pythonhosted.org/packages/5b/f5/4ec618ed16cc4f8fb3b701563655a69816155e79e24a17b651541804721d/markdown_it_py-4.0.0.tar.gz", hash = "sha256:cb0a2b4aa34f932c007117b194e945bd74e0ec24133ceb5bac59009cda1cb9f3", size = 73070, upload-time = "2025-08-11T12:57:52.854Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/42/d7/1ec15b46af6af88f19b8e5ffea08fa375d433c998b8a7639e76935c14f1f/markdown_it_py-3.0.0-py3-none-any.whl", hash = "sha256:355216845c60bd96232cd8d8c40e8f9765cc86f46880e43a8fd22dc1a1a8cab1", size = 87528 }, + { url = "https://files.pythonhosted.org/packages/94/54/e7d793b573f298e1c9013b8c4dade17d481164aa517d1d7148619c2cedbf/markdown_it_py-4.0.0-py3-none-any.whl", hash = "sha256:87327c59b172c5011896038353a81343b6754500a08cd7a4973bb48c6d578147", size = 87321, upload-time = "2025-08-11T12:57:51.923Z" }, ] [[package]] name = "markupsafe" -version = "3.0.2" -source = { registry = "https://pypi.org/simple" } -sdist = { url = "https://files.pythonhosted.org/packages/b2/97/5d42485e71dfc078108a86d6de8fa46db44a1a9295e89c5d6d4a06e23a62/markupsafe-3.0.2.tar.gz", hash = "sha256:ee55d3edf80167e48ea11a923c7386f4669df67d7994554387f84e7d8b0a2bf0", size = 20537 } -wheels = [ - { url = "https://files.pythonhosted.org/packages/04/90/d08277ce111dd22f77149fd1a5d4653eeb3b3eaacbdfcbae5afb2600eebd/MarkupSafe-3.0.2-cp310-cp310-macosx_10_9_universal2.whl", hash = "sha256:7e94c425039cde14257288fd61dcfb01963e658efbc0ff54f5306b06054700f8", size = 14357 }, - { url = "https://files.pythonhosted.org/packages/04/e1/6e2194baeae0bca1fae6629dc0cbbb968d4d941469cbab11a3872edff374/MarkupSafe-3.0.2-cp310-cp310-macosx_11_0_arm64.whl", hash = "sha256:9e2d922824181480953426608b81967de705c3cef4d1af983af849d7bd619158", size = 12393 }, - { url = "https://files.pythonhosted.org/packages/1d/69/35fa85a8ece0a437493dc61ce0bb6d459dcba482c34197e3efc829aa357f/MarkupSafe-3.0.2-cp310-cp310-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:38a9ef736c01fccdd6600705b09dc574584b89bea478200c5fbf112a6b0d5579", size = 21732 }, - { url = "https://files.pythonhosted.org/packages/22/35/137da042dfb4720b638d2937c38a9c2df83fe32d20e8c8f3185dbfef05f7/MarkupSafe-3.0.2-cp310-cp310-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:bbcb445fa71794da8f178f0f6d66789a28d7319071af7a496d4d507ed566270d", size = 20866 }, - { url = "https://files.pythonhosted.org/packages/29/28/6d029a903727a1b62edb51863232152fd335d602def598dade38996887f0/MarkupSafe-3.0.2-cp310-cp310-manylinux_2_5_i686.manylinux1_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:57cb5a3cf367aeb1d316576250f65edec5bb3be939e9247ae594b4bcbc317dfb", size = 20964 }, - { url = "https://files.pythonhosted.org/packages/cc/cd/07438f95f83e8bc028279909d9c9bd39e24149b0d60053a97b2bc4f8aa51/MarkupSafe-3.0.2-cp310-cp310-musllinux_1_2_aarch64.whl", hash = "sha256:3809ede931876f5b2ec92eef964286840ed3540dadf803dd570c3b7e13141a3b", size = 21977 }, - { url = "https://files.pythonhosted.org/packages/29/01/84b57395b4cc062f9c4c55ce0df7d3108ca32397299d9df00fedd9117d3d/MarkupSafe-3.0.2-cp310-cp310-musllinux_1_2_i686.whl", hash = "sha256:e07c3764494e3776c602c1e78e298937c3315ccc9043ead7e685b7f2b8d47b3c", size = 21366 }, - { url = "https://files.pythonhosted.org/packages/bd/6e/61ebf08d8940553afff20d1fb1ba7294b6f8d279df9fd0c0db911b4bbcfd/MarkupSafe-3.0.2-cp310-cp310-musllinux_1_2_x86_64.whl", hash = "sha256:b424c77b206d63d500bcb69fa55ed8d0e6a3774056bdc4839fc9298a7edca171", size = 21091 }, - { url = "https://files.pythonhosted.org/packages/11/23/ffbf53694e8c94ebd1e7e491de185124277964344733c45481f32ede2499/MarkupSafe-3.0.2-cp310-cp310-win32.whl", hash = "sha256:fcabf5ff6eea076f859677f5f0b6b5c1a51e70a376b0579e0eadef8db48c6b50", size = 15065 }, - { url = "https://files.pythonhosted.org/packages/44/06/e7175d06dd6e9172d4a69a72592cb3f7a996a9c396eee29082826449bbc3/MarkupSafe-3.0.2-cp310-cp310-win_amd64.whl", hash = "sha256:6af100e168aa82a50e186c82875a5893c5597a0c1ccdb0d8b40240b1f28b969a", size = 15514 }, - { url = "https://files.pythonhosted.org/packages/6b/28/bbf83e3f76936960b850435576dd5e67034e200469571be53f69174a2dfd/MarkupSafe-3.0.2-cp311-cp311-macosx_10_9_universal2.whl", hash = "sha256:9025b4018f3a1314059769c7bf15441064b2207cb3f065e6ea1e7359cb46db9d", size = 14353 }, - { url = "https://files.pythonhosted.org/packages/6c/30/316d194b093cde57d448a4c3209f22e3046c5bb2fb0820b118292b334be7/MarkupSafe-3.0.2-cp311-cp311-macosx_11_0_arm64.whl", hash = "sha256:93335ca3812df2f366e80509ae119189886b0f3c2b81325d39efdb84a1e2ae93", size = 12392 }, - { url = "https://files.pythonhosted.org/packages/f2/96/9cdafba8445d3a53cae530aaf83c38ec64c4d5427d975c974084af5bc5d2/MarkupSafe-3.0.2-cp311-cp311-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:2cb8438c3cbb25e220c2ab33bb226559e7afb3baec11c4f218ffa7308603c832", size = 23984 }, - { url = "https://files.pythonhosted.org/packages/f1/a4/aefb044a2cd8d7334c8a47d3fb2c9f328ac48cb349468cc31c20b539305f/MarkupSafe-3.0.2-cp311-cp311-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:a123e330ef0853c6e822384873bef7507557d8e4a082961e1defa947aa59ba84", size = 23120 }, - { url = "https://files.pythonhosted.org/packages/8d/21/5e4851379f88f3fad1de30361db501300d4f07bcad047d3cb0449fc51f8c/MarkupSafe-3.0.2-cp311-cp311-manylinux_2_5_i686.manylinux1_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:1e084f686b92e5b83186b07e8a17fc09e38fff551f3602b249881fec658d3eca", size = 23032 }, - { url = "https://files.pythonhosted.org/packages/00/7b/e92c64e079b2d0d7ddf69899c98842f3f9a60a1ae72657c89ce2655c999d/MarkupSafe-3.0.2-cp311-cp311-musllinux_1_2_aarch64.whl", hash = "sha256:d8213e09c917a951de9d09ecee036d5c7d36cb6cb7dbaece4c71a60d79fb9798", size = 24057 }, - { url = "https://files.pythonhosted.org/packages/f9/ac/46f960ca323037caa0a10662ef97d0a4728e890334fc156b9f9e52bcc4ca/MarkupSafe-3.0.2-cp311-cp311-musllinux_1_2_i686.whl", hash = "sha256:5b02fb34468b6aaa40dfc198d813a641e3a63b98c2b05a16b9f80b7ec314185e", size = 23359 }, - { url = "https://files.pythonhosted.org/packages/69/84/83439e16197337b8b14b6a5b9c2105fff81d42c2a7c5b58ac7b62ee2c3b1/MarkupSafe-3.0.2-cp311-cp311-musllinux_1_2_x86_64.whl", hash = "sha256:0bff5e0ae4ef2e1ae4fdf2dfd5b76c75e5c2fa4132d05fc1b0dabcd20c7e28c4", size = 23306 }, - { url = "https://files.pythonhosted.org/packages/9a/34/a15aa69f01e2181ed8d2b685c0d2f6655d5cca2c4db0ddea775e631918cd/MarkupSafe-3.0.2-cp311-cp311-win32.whl", hash = "sha256:6c89876f41da747c8d3677a2b540fb32ef5715f97b66eeb0c6b66f5e3ef6f59d", size = 15094 }, - { url = "https://files.pythonhosted.org/packages/da/b8/3a3bd761922d416f3dc5d00bfbed11f66b1ab89a0c2b6e887240a30b0f6b/MarkupSafe-3.0.2-cp311-cp311-win_amd64.whl", hash = "sha256:70a87b411535ccad5ef2f1df5136506a10775d267e197e4cf531ced10537bd6b", size = 15521 }, - { url = "https://files.pythonhosted.org/packages/22/09/d1f21434c97fc42f09d290cbb6350d44eb12f09cc62c9476effdb33a18aa/MarkupSafe-3.0.2-cp312-cp312-macosx_10_13_universal2.whl", hash = "sha256:9778bd8ab0a994ebf6f84c2b949e65736d5575320a17ae8984a77fab08db94cf", size = 14274 }, - { url = "https://files.pythonhosted.org/packages/6b/b0/18f76bba336fa5aecf79d45dcd6c806c280ec44538b3c13671d49099fdd0/MarkupSafe-3.0.2-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:846ade7b71e3536c4e56b386c2a47adf5741d2d8b94ec9dc3e92e5e1ee1e2225", size = 12348 }, - { url = "https://files.pythonhosted.org/packages/e0/25/dd5c0f6ac1311e9b40f4af06c78efde0f3b5cbf02502f8ef9501294c425b/MarkupSafe-3.0.2-cp312-cp312-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:1c99d261bd2d5f6b59325c92c73df481e05e57f19837bdca8413b9eac4bd8028", size = 24149 }, - { url = "https://files.pythonhosted.org/packages/f3/f0/89e7aadfb3749d0f52234a0c8c7867877876e0a20b60e2188e9850794c17/MarkupSafe-3.0.2-cp312-cp312-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:e17c96c14e19278594aa4841ec148115f9c7615a47382ecb6b82bd8fea3ab0c8", size = 23118 }, - { url = "https://files.pythonhosted.org/packages/d5/da/f2eeb64c723f5e3777bc081da884b414671982008c47dcc1873d81f625b6/MarkupSafe-3.0.2-cp312-cp312-manylinux_2_5_i686.manylinux1_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:88416bd1e65dcea10bc7569faacb2c20ce071dd1f87539ca2ab364bf6231393c", size = 22993 }, - { url = "https://files.pythonhosted.org/packages/da/0e/1f32af846df486dce7c227fe0f2398dc7e2e51d4a370508281f3c1c5cddc/MarkupSafe-3.0.2-cp312-cp312-musllinux_1_2_aarch64.whl", hash = "sha256:2181e67807fc2fa785d0592dc2d6206c019b9502410671cc905d132a92866557", size = 24178 }, - { url = "https://files.pythonhosted.org/packages/c4/f6/bb3ca0532de8086cbff5f06d137064c8410d10779c4c127e0e47d17c0b71/MarkupSafe-3.0.2-cp312-cp312-musllinux_1_2_i686.whl", hash = "sha256:52305740fe773d09cffb16f8ed0427942901f00adedac82ec8b67752f58a1b22", size = 23319 }, - { url = "https://files.pythonhosted.org/packages/a2/82/8be4c96ffee03c5b4a034e60a31294daf481e12c7c43ab8e34a1453ee48b/MarkupSafe-3.0.2-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:ad10d3ded218f1039f11a75f8091880239651b52e9bb592ca27de44eed242a48", size = 23352 }, - { url = "https://files.pythonhosted.org/packages/51/ae/97827349d3fcffee7e184bdf7f41cd6b88d9919c80f0263ba7acd1bbcb18/MarkupSafe-3.0.2-cp312-cp312-win32.whl", hash = "sha256:0f4ca02bea9a23221c0182836703cbf8930c5e9454bacce27e767509fa286a30", size = 15097 }, - { url = "https://files.pythonhosted.org/packages/c1/80/a61f99dc3a936413c3ee4e1eecac96c0da5ed07ad56fd975f1a9da5bc630/MarkupSafe-3.0.2-cp312-cp312-win_amd64.whl", hash = "sha256:8e06879fc22a25ca47312fbe7c8264eb0b662f6db27cb2d3bbbc74b1df4b9b87", size = 15601 }, - { url = "https://files.pythonhosted.org/packages/83/0e/67eb10a7ecc77a0c2bbe2b0235765b98d164d81600746914bebada795e97/MarkupSafe-3.0.2-cp313-cp313-macosx_10_13_universal2.whl", hash = "sha256:ba9527cdd4c926ed0760bc301f6728ef34d841f405abf9d4f959c478421e4efd", size = 14274 }, - { url = "https://files.pythonhosted.org/packages/2b/6d/9409f3684d3335375d04e5f05744dfe7e9f120062c9857df4ab490a1031a/MarkupSafe-3.0.2-cp313-cp313-macosx_11_0_arm64.whl", hash = "sha256:f8b3d067f2e40fe93e1ccdd6b2e1d16c43140e76f02fb1319a05cf2b79d99430", size = 12352 }, - { url = "https://files.pythonhosted.org/packages/d2/f5/6eadfcd3885ea85fe2a7c128315cc1bb7241e1987443d78c8fe712d03091/MarkupSafe-3.0.2-cp313-cp313-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:569511d3b58c8791ab4c2e1285575265991e6d8f8700c7be0e88f86cb0672094", size = 24122 }, - { url = "https://files.pythonhosted.org/packages/0c/91/96cf928db8236f1bfab6ce15ad070dfdd02ed88261c2afafd4b43575e9e9/MarkupSafe-3.0.2-cp313-cp313-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:15ab75ef81add55874e7ab7055e9c397312385bd9ced94920f2802310c930396", size = 23085 }, - { url = "https://files.pythonhosted.org/packages/c2/cf/c9d56af24d56ea04daae7ac0940232d31d5a8354f2b457c6d856b2057d69/MarkupSafe-3.0.2-cp313-cp313-manylinux_2_5_i686.manylinux1_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:f3818cb119498c0678015754eba762e0d61e5b52d34c8b13d770f0719f7b1d79", size = 22978 }, - { url = "https://files.pythonhosted.org/packages/2a/9f/8619835cd6a711d6272d62abb78c033bda638fdc54c4e7f4272cf1c0962b/MarkupSafe-3.0.2-cp313-cp313-musllinux_1_2_aarch64.whl", hash = "sha256:cdb82a876c47801bb54a690c5ae105a46b392ac6099881cdfb9f6e95e4014c6a", size = 24208 }, - { url = "https://files.pythonhosted.org/packages/f9/bf/176950a1792b2cd2102b8ffeb5133e1ed984547b75db47c25a67d3359f77/MarkupSafe-3.0.2-cp313-cp313-musllinux_1_2_i686.whl", hash = "sha256:cabc348d87e913db6ab4aa100f01b08f481097838bdddf7c7a84b7575b7309ca", size = 23357 }, - { url = "https://files.pythonhosted.org/packages/ce/4f/9a02c1d335caabe5c4efb90e1b6e8ee944aa245c1aaaab8e8a618987d816/MarkupSafe-3.0.2-cp313-cp313-musllinux_1_2_x86_64.whl", hash = "sha256:444dcda765c8a838eaae23112db52f1efaf750daddb2d9ca300bcae1039adc5c", size = 23344 }, - { url = "https://files.pythonhosted.org/packages/ee/55/c271b57db36f748f0e04a759ace9f8f759ccf22b4960c270c78a394f58be/MarkupSafe-3.0.2-cp313-cp313-win32.whl", hash = "sha256:bcf3e58998965654fdaff38e58584d8937aa3096ab5354d493c77d1fdd66d7a1", size = 15101 }, - { url = "https://files.pythonhosted.org/packages/29/88/07df22d2dd4df40aba9f3e402e6dc1b8ee86297dddbad4872bd5e7b0094f/MarkupSafe-3.0.2-cp313-cp313-win_amd64.whl", hash = "sha256:e6a2a455bd412959b57a172ce6328d2dd1f01cb2135efda2e4576e8a23fa3b0f", size = 15603 }, - { url = "https://files.pythonhosted.org/packages/62/6a/8b89d24db2d32d433dffcd6a8779159da109842434f1dd2f6e71f32f738c/MarkupSafe-3.0.2-cp313-cp313t-macosx_10_13_universal2.whl", hash = "sha256:b5a6b3ada725cea8a5e634536b1b01c30bcdcd7f9c6fff4151548d5bf6b3a36c", size = 14510 }, - { url = "https://files.pythonhosted.org/packages/7a/06/a10f955f70a2e5a9bf78d11a161029d278eeacbd35ef806c3fd17b13060d/MarkupSafe-3.0.2-cp313-cp313t-macosx_11_0_arm64.whl", hash = "sha256:a904af0a6162c73e3edcb969eeeb53a63ceeb5d8cf642fade7d39e7963a22ddb", size = 12486 }, - { url = "https://files.pythonhosted.org/packages/34/cf/65d4a571869a1a9078198ca28f39fba5fbb910f952f9dbc5220afff9f5e6/MarkupSafe-3.0.2-cp313-cp313t-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:4aa4e5faecf353ed117801a068ebab7b7e09ffb6e1d5e412dc852e0da018126c", size = 25480 }, - { url = "https://files.pythonhosted.org/packages/0c/e3/90e9651924c430b885468b56b3d597cabf6d72be4b24a0acd1fa0e12af67/MarkupSafe-3.0.2-cp313-cp313t-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:c0ef13eaeee5b615fb07c9a7dadb38eac06a0608b41570d8ade51c56539e509d", size = 23914 }, - { url = "https://files.pythonhosted.org/packages/66/8c/6c7cf61f95d63bb866db39085150df1f2a5bd3335298f14a66b48e92659c/MarkupSafe-3.0.2-cp313-cp313t-manylinux_2_5_i686.manylinux1_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:d16a81a06776313e817c951135cf7340a3e91e8c1ff2fac444cfd75fffa04afe", size = 23796 }, - { url = "https://files.pythonhosted.org/packages/bb/35/cbe9238ec3f47ac9a7c8b3df7a808e7cb50fe149dc7039f5f454b3fba218/MarkupSafe-3.0.2-cp313-cp313t-musllinux_1_2_aarch64.whl", hash = "sha256:6381026f158fdb7c72a168278597a5e3a5222e83ea18f543112b2662a9b699c5", size = 25473 }, - { url = "https://files.pythonhosted.org/packages/e6/32/7621a4382488aa283cc05e8984a9c219abad3bca087be9ec77e89939ded9/MarkupSafe-3.0.2-cp313-cp313t-musllinux_1_2_i686.whl", hash = "sha256:3d79d162e7be8f996986c064d1c7c817f6df3a77fe3d6859f6f9e7be4b8c213a", size = 24114 }, - { url = "https://files.pythonhosted.org/packages/0d/80/0985960e4b89922cb5a0bac0ed39c5b96cbc1a536a99f30e8c220a996ed9/MarkupSafe-3.0.2-cp313-cp313t-musllinux_1_2_x86_64.whl", hash = "sha256:131a3c7689c85f5ad20f9f6fb1b866f402c445b220c19fe4308c0b147ccd2ad9", size = 24098 }, - { url = "https://files.pythonhosted.org/packages/82/78/fedb03c7d5380df2427038ec8d973587e90561b2d90cd472ce9254cf348b/MarkupSafe-3.0.2-cp313-cp313t-win32.whl", hash = "sha256:ba8062ed2cf21c07a9e295d5b8a2a5ce678b913b45fdf68c32d95d6c1291e0b6", size = 15208 }, - { url = "https://files.pythonhosted.org/packages/4f/65/6079a46068dfceaeabb5dcad6d674f5f5c61a6fa5673746f42a9f4c233b3/MarkupSafe-3.0.2-cp313-cp313t-win_amd64.whl", hash = "sha256:e444a31f8db13eb18ada366ab3cf45fd4b31e4db1236a4448f68778c1d1a5a2f", size = 15739 }, +version = "3.0.3" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/7e/99/7690b6d4034fffd95959cbe0c02de8deb3098cc577c67bb6a24fe5d7caa7/markupsafe-3.0.3.tar.gz", hash = "sha256:722695808f4b6457b320fdc131280796bdceb04ab50fe1795cd540799ebe1698", size = 80313, upload-time = "2025-09-27T18:37:40.426Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/e8/4b/3541d44f3937ba468b75da9eebcae497dcf67adb65caa16760b0a6807ebb/markupsafe-3.0.3-cp310-cp310-macosx_10_9_x86_64.whl", hash = "sha256:2f981d352f04553a7171b8e44369f2af4055f888dfb147d55e42d29e29e74559", size = 11631, upload-time = "2025-09-27T18:36:05.558Z" }, + { url = "https://files.pythonhosted.org/packages/98/1b/fbd8eed11021cabd9226c37342fa6ca4e8a98d8188a8d9b66740494960e4/markupsafe-3.0.3-cp310-cp310-macosx_11_0_arm64.whl", hash = "sha256:e1c1493fb6e50ab01d20a22826e57520f1284df32f2d8601fdd90b6304601419", size = 12057, upload-time = "2025-09-27T18:36:07.165Z" }, + { url = "https://files.pythonhosted.org/packages/40/01/e560d658dc0bb8ab762670ece35281dec7b6c1b33f5fbc09ebb57a185519/markupsafe-3.0.3-cp310-cp310-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:1ba88449deb3de88bd40044603fafffb7bc2b055d626a330323a9ed736661695", size = 22050, upload-time = "2025-09-27T18:36:08.005Z" }, + { url = "https://files.pythonhosted.org/packages/af/cd/ce6e848bbf2c32314c9b237839119c5a564a59725b53157c856e90937b7a/markupsafe-3.0.3-cp310-cp310-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:f42d0984e947b8adf7dd6dde396e720934d12c506ce84eea8476409563607591", size = 20681, upload-time = "2025-09-27T18:36:08.881Z" }, + { url = "https://files.pythonhosted.org/packages/c9/2a/b5c12c809f1c3045c4d580b035a743d12fcde53cf685dbc44660826308da/markupsafe-3.0.3-cp310-cp310-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:c0c0b3ade1c0b13b936d7970b1d37a57acde9199dc2aecc4c336773e1d86049c", size = 20705, upload-time = "2025-09-27T18:36:10.131Z" }, + { url = "https://files.pythonhosted.org/packages/cf/e3/9427a68c82728d0a88c50f890d0fc072a1484de2f3ac1ad0bfc1a7214fd5/markupsafe-3.0.3-cp310-cp310-musllinux_1_2_aarch64.whl", hash = "sha256:0303439a41979d9e74d18ff5e2dd8c43ed6c6001fd40e5bf2e43f7bd9bbc523f", size = 21524, upload-time = "2025-09-27T18:36:11.324Z" }, + { url = "https://files.pythonhosted.org/packages/bc/36/23578f29e9e582a4d0278e009b38081dbe363c5e7165113fad546918a232/markupsafe-3.0.3-cp310-cp310-musllinux_1_2_riscv64.whl", hash = "sha256:d2ee202e79d8ed691ceebae8e0486bd9a2cd4794cec4824e1c99b6f5009502f6", size = 20282, upload-time = "2025-09-27T18:36:12.573Z" }, + { url = "https://files.pythonhosted.org/packages/56/21/dca11354e756ebd03e036bd8ad58d6d7168c80ce1fe5e75218e4945cbab7/markupsafe-3.0.3-cp310-cp310-musllinux_1_2_x86_64.whl", hash = "sha256:177b5253b2834fe3678cb4a5f0059808258584c559193998be2601324fdeafb1", size = 20745, upload-time = "2025-09-27T18:36:13.504Z" }, + { url = "https://files.pythonhosted.org/packages/87/99/faba9369a7ad6e4d10b6a5fbf71fa2a188fe4a593b15f0963b73859a1bbd/markupsafe-3.0.3-cp310-cp310-win32.whl", hash = "sha256:2a15a08b17dd94c53a1da0438822d70ebcd13f8c3a95abe3a9ef9f11a94830aa", size = 14571, upload-time = "2025-09-27T18:36:14.779Z" }, + { url = "https://files.pythonhosted.org/packages/d6/25/55dc3ab959917602c96985cb1253efaa4ff42f71194bddeb61eb7278b8be/markupsafe-3.0.3-cp310-cp310-win_amd64.whl", hash = "sha256:c4ffb7ebf07cfe8931028e3e4c85f0357459a3f9f9490886198848f4fa002ec8", size = 15056, upload-time = "2025-09-27T18:36:16.125Z" }, + { url = "https://files.pythonhosted.org/packages/d0/9e/0a02226640c255d1da0b8d12e24ac2aa6734da68bff14c05dd53b94a0fc3/markupsafe-3.0.3-cp310-cp310-win_arm64.whl", hash = "sha256:e2103a929dfa2fcaf9bb4e7c091983a49c9ac3b19c9061b6d5427dd7d14d81a1", size = 13932, upload-time = "2025-09-27T18:36:17.311Z" }, + { url = "https://files.pythonhosted.org/packages/08/db/fefacb2136439fc8dd20e797950e749aa1f4997ed584c62cfb8ef7c2be0e/markupsafe-3.0.3-cp311-cp311-macosx_10_9_x86_64.whl", hash = "sha256:1cc7ea17a6824959616c525620e387f6dd30fec8cb44f649e31712db02123dad", size = 11631, upload-time = "2025-09-27T18:36:18.185Z" }, + { url = "https://files.pythonhosted.org/packages/e1/2e/5898933336b61975ce9dc04decbc0a7f2fee78c30353c5efba7f2d6ff27a/markupsafe-3.0.3-cp311-cp311-macosx_11_0_arm64.whl", hash = "sha256:4bd4cd07944443f5a265608cc6aab442e4f74dff8088b0dfc8238647b8f6ae9a", size = 12058, upload-time = "2025-09-27T18:36:19.444Z" }, + { url = "https://files.pythonhosted.org/packages/1d/09/adf2df3699d87d1d8184038df46a9c80d78c0148492323f4693df54e17bb/markupsafe-3.0.3-cp311-cp311-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:6b5420a1d9450023228968e7e6a9ce57f65d148ab56d2313fcd589eee96a7a50", size = 24287, upload-time = "2025-09-27T18:36:20.768Z" }, + { url = "https://files.pythonhosted.org/packages/30/ac/0273f6fcb5f42e314c6d8cd99effae6a5354604d461b8d392b5ec9530a54/markupsafe-3.0.3-cp311-cp311-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:0bf2a864d67e76e5c9a34dc26ec616a66b9888e25e7b9460e1c76d3293bd9dbf", size = 22940, upload-time = "2025-09-27T18:36:22.249Z" }, + { url = "https://files.pythonhosted.org/packages/19/ae/31c1be199ef767124c042c6c3e904da327a2f7f0cd63a0337e1eca2967a8/markupsafe-3.0.3-cp311-cp311-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:bc51efed119bc9cfdf792cdeaa4d67e8f6fcccab66ed4bfdd6bde3e59bfcbb2f", size = 21887, upload-time = "2025-09-27T18:36:23.535Z" }, + { url = "https://files.pythonhosted.org/packages/b2/76/7edcab99d5349a4532a459e1fe64f0b0467a3365056ae550d3bcf3f79e1e/markupsafe-3.0.3-cp311-cp311-musllinux_1_2_aarch64.whl", hash = "sha256:068f375c472b3e7acbe2d5318dea141359e6900156b5b2ba06a30b169086b91a", size = 23692, upload-time = "2025-09-27T18:36:24.823Z" }, + { url = "https://files.pythonhosted.org/packages/a4/28/6e74cdd26d7514849143d69f0bf2399f929c37dc2b31e6829fd2045b2765/markupsafe-3.0.3-cp311-cp311-musllinux_1_2_riscv64.whl", hash = "sha256:7be7b61bb172e1ed687f1754f8e7484f1c8019780f6f6b0786e76bb01c2ae115", size = 21471, upload-time = "2025-09-27T18:36:25.95Z" }, + { url = "https://files.pythonhosted.org/packages/62/7e/a145f36a5c2945673e590850a6f8014318d5577ed7e5920a4b3448e0865d/markupsafe-3.0.3-cp311-cp311-musllinux_1_2_x86_64.whl", hash = "sha256:f9e130248f4462aaa8e2552d547f36ddadbeaa573879158d721bbd33dfe4743a", size = 22923, upload-time = "2025-09-27T18:36:27.109Z" }, + { url = "https://files.pythonhosted.org/packages/0f/62/d9c46a7f5c9adbeeeda52f5b8d802e1094e9717705a645efc71b0913a0a8/markupsafe-3.0.3-cp311-cp311-win32.whl", hash = "sha256:0db14f5dafddbb6d9208827849fad01f1a2609380add406671a26386cdf15a19", size = 14572, upload-time = "2025-09-27T18:36:28.045Z" }, + { url = "https://files.pythonhosted.org/packages/83/8a/4414c03d3f891739326e1783338e48fb49781cc915b2e0ee052aa490d586/markupsafe-3.0.3-cp311-cp311-win_amd64.whl", hash = "sha256:de8a88e63464af587c950061a5e6a67d3632e36df62b986892331d4620a35c01", size = 15077, upload-time = "2025-09-27T18:36:29.025Z" }, + { url = "https://files.pythonhosted.org/packages/35/73/893072b42e6862f319b5207adc9ae06070f095b358655f077f69a35601f0/markupsafe-3.0.3-cp311-cp311-win_arm64.whl", hash = "sha256:3b562dd9e9ea93f13d53989d23a7e775fdfd1066c33494ff43f5418bc8c58a5c", size = 13876, upload-time = "2025-09-27T18:36:29.954Z" }, + { url = "https://files.pythonhosted.org/packages/5a/72/147da192e38635ada20e0a2e1a51cf8823d2119ce8883f7053879c2199b5/markupsafe-3.0.3-cp312-cp312-macosx_10_13_x86_64.whl", hash = "sha256:d53197da72cc091b024dd97249dfc7794d6a56530370992a5e1a08983ad9230e", size = 11615, upload-time = "2025-09-27T18:36:30.854Z" }, + { url = "https://files.pythonhosted.org/packages/9a/81/7e4e08678a1f98521201c3079f77db69fb552acd56067661f8c2f534a718/markupsafe-3.0.3-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:1872df69a4de6aead3491198eaf13810b565bdbeec3ae2dc8780f14458ec73ce", size = 12020, upload-time = "2025-09-27T18:36:31.971Z" }, + { url = "https://files.pythonhosted.org/packages/1e/2c/799f4742efc39633a1b54a92eec4082e4f815314869865d876824c257c1e/markupsafe-3.0.3-cp312-cp312-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:3a7e8ae81ae39e62a41ec302f972ba6ae23a5c5396c8e60113e9066ef893da0d", size = 24332, upload-time = "2025-09-27T18:36:32.813Z" }, + { url = "https://files.pythonhosted.org/packages/3c/2e/8d0c2ab90a8c1d9a24f0399058ab8519a3279d1bd4289511d74e909f060e/markupsafe-3.0.3-cp312-cp312-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:d6dd0be5b5b189d31db7cda48b91d7e0a9795f31430b7f271219ab30f1d3ac9d", size = 22947, upload-time = "2025-09-27T18:36:33.86Z" }, + { url = "https://files.pythonhosted.org/packages/2c/54/887f3092a85238093a0b2154bd629c89444f395618842e8b0c41783898ea/markupsafe-3.0.3-cp312-cp312-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:94c6f0bb423f739146aec64595853541634bde58b2135f27f61c1ffd1cd4d16a", size = 21962, upload-time = "2025-09-27T18:36:35.099Z" }, + { url = "https://files.pythonhosted.org/packages/c9/2f/336b8c7b6f4a4d95e91119dc8521402461b74a485558d8f238a68312f11c/markupsafe-3.0.3-cp312-cp312-musllinux_1_2_aarch64.whl", hash = "sha256:be8813b57049a7dc738189df53d69395eba14fb99345e0a5994914a3864c8a4b", size = 23760, upload-time = "2025-09-27T18:36:36.001Z" }, + { url = "https://files.pythonhosted.org/packages/32/43/67935f2b7e4982ffb50a4d169b724d74b62a3964bc1a9a527f5ac4f1ee2b/markupsafe-3.0.3-cp312-cp312-musllinux_1_2_riscv64.whl", hash = "sha256:83891d0e9fb81a825d9a6d61e3f07550ca70a076484292a70fde82c4b807286f", size = 21529, upload-time = "2025-09-27T18:36:36.906Z" }, + { url = "https://files.pythonhosted.org/packages/89/e0/4486f11e51bbba8b0c041098859e869e304d1c261e59244baa3d295d47b7/markupsafe-3.0.3-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:77f0643abe7495da77fb436f50f8dab76dbc6e5fd25d39589a0f1fe6548bfa2b", size = 23015, upload-time = "2025-09-27T18:36:37.868Z" }, + { url = "https://files.pythonhosted.org/packages/2f/e1/78ee7a023dac597a5825441ebd17170785a9dab23de95d2c7508ade94e0e/markupsafe-3.0.3-cp312-cp312-win32.whl", hash = "sha256:d88b440e37a16e651bda4c7c2b930eb586fd15ca7406cb39e211fcff3bf3017d", size = 14540, upload-time = "2025-09-27T18:36:38.761Z" }, + { url = "https://files.pythonhosted.org/packages/aa/5b/bec5aa9bbbb2c946ca2733ef9c4ca91c91b6a24580193e891b5f7dbe8e1e/markupsafe-3.0.3-cp312-cp312-win_amd64.whl", hash = "sha256:26a5784ded40c9e318cfc2bdb30fe164bdb8665ded9cd64d500a34fb42067b1c", size = 15105, upload-time = "2025-09-27T18:36:39.701Z" }, + { url = "https://files.pythonhosted.org/packages/e5/f1/216fc1bbfd74011693a4fd837e7026152e89c4bcf3e77b6692fba9923123/markupsafe-3.0.3-cp312-cp312-win_arm64.whl", hash = "sha256:35add3b638a5d900e807944a078b51922212fb3dedb01633a8defc4b01a3c85f", size = 13906, upload-time = "2025-09-27T18:36:40.689Z" }, + { url = "https://files.pythonhosted.org/packages/38/2f/907b9c7bbba283e68f20259574b13d005c121a0fa4c175f9bed27c4597ff/markupsafe-3.0.3-cp313-cp313-macosx_10_13_x86_64.whl", hash = "sha256:e1cf1972137e83c5d4c136c43ced9ac51d0e124706ee1c8aa8532c1287fa8795", size = 11622, upload-time = "2025-09-27T18:36:41.777Z" }, + { url = "https://files.pythonhosted.org/packages/9c/d9/5f7756922cdd676869eca1c4e3c0cd0df60ed30199ffd775e319089cb3ed/markupsafe-3.0.3-cp313-cp313-macosx_11_0_arm64.whl", hash = "sha256:116bb52f642a37c115f517494ea5feb03889e04df47eeff5b130b1808ce7c219", size = 12029, upload-time = "2025-09-27T18:36:43.257Z" }, + { url = "https://files.pythonhosted.org/packages/00/07/575a68c754943058c78f30db02ee03a64b3c638586fba6a6dd56830b30a3/markupsafe-3.0.3-cp313-cp313-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:133a43e73a802c5562be9bbcd03d090aa5a1fe899db609c29e8c8d815c5f6de6", size = 24374, upload-time = "2025-09-27T18:36:44.508Z" }, + { url = "https://files.pythonhosted.org/packages/a9/21/9b05698b46f218fc0e118e1f8168395c65c8a2c750ae2bab54fc4bd4e0e8/markupsafe-3.0.3-cp313-cp313-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:ccfcd093f13f0f0b7fdd0f198b90053bf7b2f02a3927a30e63f3ccc9df56b676", size = 22980, upload-time = "2025-09-27T18:36:45.385Z" }, + { url = "https://files.pythonhosted.org/packages/7f/71/544260864f893f18b6827315b988c146b559391e6e7e8f7252839b1b846a/markupsafe-3.0.3-cp313-cp313-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:509fa21c6deb7a7a273d629cf5ec029bc209d1a51178615ddf718f5918992ab9", size = 21990, upload-time = "2025-09-27T18:36:46.916Z" }, + { url = "https://files.pythonhosted.org/packages/c2/28/b50fc2f74d1ad761af2f5dcce7492648b983d00a65b8c0e0cb457c82ebbe/markupsafe-3.0.3-cp313-cp313-musllinux_1_2_aarch64.whl", hash = "sha256:a4afe79fb3de0b7097d81da19090f4df4f8d3a2b3adaa8764138aac2e44f3af1", size = 23784, upload-time = "2025-09-27T18:36:47.884Z" }, + { url = "https://files.pythonhosted.org/packages/ed/76/104b2aa106a208da8b17a2fb72e033a5a9d7073c68f7e508b94916ed47a9/markupsafe-3.0.3-cp313-cp313-musllinux_1_2_riscv64.whl", hash = "sha256:795e7751525cae078558e679d646ae45574b47ed6e7771863fcc079a6171a0fc", size = 21588, upload-time = "2025-09-27T18:36:48.82Z" }, + { url = "https://files.pythonhosted.org/packages/b5/99/16a5eb2d140087ebd97180d95249b00a03aa87e29cc224056274f2e45fd6/markupsafe-3.0.3-cp313-cp313-musllinux_1_2_x86_64.whl", hash = "sha256:8485f406a96febb5140bfeca44a73e3ce5116b2501ac54fe953e488fb1d03b12", size = 23041, upload-time = "2025-09-27T18:36:49.797Z" }, + { url = "https://files.pythonhosted.org/packages/19/bc/e7140ed90c5d61d77cea142eed9f9c303f4c4806f60a1044c13e3f1471d0/markupsafe-3.0.3-cp313-cp313-win32.whl", hash = "sha256:bdd37121970bfd8be76c5fb069c7751683bdf373db1ed6c010162b2a130248ed", size = 14543, upload-time = "2025-09-27T18:36:51.584Z" }, + { url = "https://files.pythonhosted.org/packages/05/73/c4abe620b841b6b791f2edc248f556900667a5a1cf023a6646967ae98335/markupsafe-3.0.3-cp313-cp313-win_amd64.whl", hash = "sha256:9a1abfdc021a164803f4d485104931fb8f8c1efd55bc6b748d2f5774e78b62c5", size = 15113, upload-time = "2025-09-27T18:36:52.537Z" }, + { url = "https://files.pythonhosted.org/packages/f0/3a/fa34a0f7cfef23cf9500d68cb7c32dd64ffd58a12b09225fb03dd37d5b80/markupsafe-3.0.3-cp313-cp313-win_arm64.whl", hash = "sha256:7e68f88e5b8799aa49c85cd116c932a1ac15caaa3f5db09087854d218359e485", size = 13911, upload-time = "2025-09-27T18:36:53.513Z" }, + { url = "https://files.pythonhosted.org/packages/e4/d7/e05cd7efe43a88a17a37b3ae96e79a19e846f3f456fe79c57ca61356ef01/markupsafe-3.0.3-cp313-cp313t-macosx_10_13_x86_64.whl", hash = "sha256:218551f6df4868a8d527e3062d0fb968682fe92054e89978594c28e642c43a73", size = 11658, upload-time = "2025-09-27T18:36:54.819Z" }, + { url = "https://files.pythonhosted.org/packages/99/9e/e412117548182ce2148bdeacdda3bb494260c0b0184360fe0d56389b523b/markupsafe-3.0.3-cp313-cp313t-macosx_11_0_arm64.whl", hash = "sha256:3524b778fe5cfb3452a09d31e7b5adefeea8c5be1d43c4f810ba09f2ceb29d37", size = 12066, upload-time = "2025-09-27T18:36:55.714Z" }, + { url = "https://files.pythonhosted.org/packages/bc/e6/fa0ffcda717ef64a5108eaa7b4f5ed28d56122c9a6d70ab8b72f9f715c80/markupsafe-3.0.3-cp313-cp313t-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:4e885a3d1efa2eadc93c894a21770e4bc67899e3543680313b09f139e149ab19", size = 25639, upload-time = "2025-09-27T18:36:56.908Z" }, + { url = "https://files.pythonhosted.org/packages/96/ec/2102e881fe9d25fc16cb4b25d5f5cde50970967ffa5dddafdb771237062d/markupsafe-3.0.3-cp313-cp313t-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:8709b08f4a89aa7586de0aadc8da56180242ee0ada3999749b183aa23df95025", size = 23569, upload-time = "2025-09-27T18:36:57.913Z" }, + { url = "https://files.pythonhosted.org/packages/4b/30/6f2fce1f1f205fc9323255b216ca8a235b15860c34b6798f810f05828e32/markupsafe-3.0.3-cp313-cp313t-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:b8512a91625c9b3da6f127803b166b629725e68af71f8184ae7e7d54686a56d6", size = 23284, upload-time = "2025-09-27T18:36:58.833Z" }, + { url = "https://files.pythonhosted.org/packages/58/47/4a0ccea4ab9f5dcb6f79c0236d954acb382202721e704223a8aafa38b5c8/markupsafe-3.0.3-cp313-cp313t-musllinux_1_2_aarch64.whl", hash = "sha256:9b79b7a16f7fedff2495d684f2b59b0457c3b493778c9eed31111be64d58279f", size = 24801, upload-time = "2025-09-27T18:36:59.739Z" }, + { url = "https://files.pythonhosted.org/packages/6a/70/3780e9b72180b6fecb83a4814d84c3bf4b4ae4bf0b19c27196104149734c/markupsafe-3.0.3-cp313-cp313t-musllinux_1_2_riscv64.whl", hash = "sha256:12c63dfb4a98206f045aa9563db46507995f7ef6d83b2f68eda65c307c6829eb", size = 22769, upload-time = "2025-09-27T18:37:00.719Z" }, + { url = "https://files.pythonhosted.org/packages/98/c5/c03c7f4125180fc215220c035beac6b9cb684bc7a067c84fc69414d315f5/markupsafe-3.0.3-cp313-cp313t-musllinux_1_2_x86_64.whl", hash = "sha256:8f71bc33915be5186016f675cd83a1e08523649b0e33efdb898db577ef5bb009", size = 23642, upload-time = "2025-09-27T18:37:01.673Z" }, + { url = "https://files.pythonhosted.org/packages/80/d6/2d1b89f6ca4bff1036499b1e29a1d02d282259f3681540e16563f27ebc23/markupsafe-3.0.3-cp313-cp313t-win32.whl", hash = "sha256:69c0b73548bc525c8cb9a251cddf1931d1db4d2258e9599c28c07ef3580ef354", size = 14612, upload-time = "2025-09-27T18:37:02.639Z" }, + { url = "https://files.pythonhosted.org/packages/2b/98/e48a4bfba0a0ffcf9925fe2d69240bfaa19c6f7507b8cd09c70684a53c1e/markupsafe-3.0.3-cp313-cp313t-win_amd64.whl", hash = "sha256:1b4b79e8ebf6b55351f0d91fe80f893b4743f104bff22e90697db1590e47a218", size = 15200, upload-time = "2025-09-27T18:37:03.582Z" }, + { url = "https://files.pythonhosted.org/packages/0e/72/e3cc540f351f316e9ed0f092757459afbc595824ca724cbc5a5d4263713f/markupsafe-3.0.3-cp313-cp313t-win_arm64.whl", hash = "sha256:ad2cf8aa28b8c020ab2fc8287b0f823d0a7d8630784c31e9ee5edea20f406287", size = 13973, upload-time = "2025-09-27T18:37:04.929Z" }, + { url = "https://files.pythonhosted.org/packages/33/8a/8e42d4838cd89b7dde187011e97fe6c3af66d8c044997d2183fbd6d31352/markupsafe-3.0.3-cp314-cp314-macosx_10_13_x86_64.whl", hash = "sha256:eaa9599de571d72e2daf60164784109f19978b327a3910d3e9de8c97b5b70cfe", size = 11619, upload-time = "2025-09-27T18:37:06.342Z" }, + { url = "https://files.pythonhosted.org/packages/b5/64/7660f8a4a8e53c924d0fa05dc3a55c9cee10bbd82b11c5afb27d44b096ce/markupsafe-3.0.3-cp314-cp314-macosx_11_0_arm64.whl", hash = "sha256:c47a551199eb8eb2121d4f0f15ae0f923d31350ab9280078d1e5f12b249e0026", size = 12029, upload-time = "2025-09-27T18:37:07.213Z" }, + { url = "https://files.pythonhosted.org/packages/da/ef/e648bfd021127bef5fa12e1720ffed0c6cbb8310c8d9bea7266337ff06de/markupsafe-3.0.3-cp314-cp314-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:f34c41761022dd093b4b6896d4810782ffbabe30f2d443ff5f083e0cbbb8c737", size = 24408, upload-time = "2025-09-27T18:37:09.572Z" }, + { url = "https://files.pythonhosted.org/packages/41/3c/a36c2450754618e62008bf7435ccb0f88053e07592e6028a34776213d877/markupsafe-3.0.3-cp314-cp314-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:457a69a9577064c05a97c41f4e65148652db078a3a509039e64d3467b9e7ef97", size = 23005, upload-time = "2025-09-27T18:37:10.58Z" }, + { url = "https://files.pythonhosted.org/packages/bc/20/b7fdf89a8456b099837cd1dc21974632a02a999ec9bf7ca3e490aacd98e7/markupsafe-3.0.3-cp314-cp314-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:e8afc3f2ccfa24215f8cb28dcf43f0113ac3c37c2f0f0806d8c70e4228c5cf4d", size = 22048, upload-time = "2025-09-27T18:37:11.547Z" }, + { url = "https://files.pythonhosted.org/packages/9a/a7/591f592afdc734f47db08a75793a55d7fbcc6902a723ae4cfbab61010cc5/markupsafe-3.0.3-cp314-cp314-musllinux_1_2_aarch64.whl", hash = "sha256:ec15a59cf5af7be74194f7ab02d0f59a62bdcf1a537677ce67a2537c9b87fcda", size = 23821, upload-time = "2025-09-27T18:37:12.48Z" }, + { url = "https://files.pythonhosted.org/packages/7d/33/45b24e4f44195b26521bc6f1a82197118f74df348556594bd2262bda1038/markupsafe-3.0.3-cp314-cp314-musllinux_1_2_riscv64.whl", hash = "sha256:0eb9ff8191e8498cca014656ae6b8d61f39da5f95b488805da4bb029cccbfbaf", size = 21606, upload-time = "2025-09-27T18:37:13.485Z" }, + { url = "https://files.pythonhosted.org/packages/ff/0e/53dfaca23a69fbfbbf17a4b64072090e70717344c52eaaaa9c5ddff1e5f0/markupsafe-3.0.3-cp314-cp314-musllinux_1_2_x86_64.whl", hash = "sha256:2713baf880df847f2bece4230d4d094280f4e67b1e813eec43b4c0e144a34ffe", size = 23043, upload-time = "2025-09-27T18:37:14.408Z" }, + { url = "https://files.pythonhosted.org/packages/46/11/f333a06fc16236d5238bfe74daccbca41459dcd8d1fa952e8fbd5dccfb70/markupsafe-3.0.3-cp314-cp314-win32.whl", hash = "sha256:729586769a26dbceff69f7a7dbbf59ab6572b99d94576a5592625d5b411576b9", size = 14747, upload-time = "2025-09-27T18:37:15.36Z" }, + { url = "https://files.pythonhosted.org/packages/28/52/182836104b33b444e400b14f797212f720cbc9ed6ba34c800639d154e821/markupsafe-3.0.3-cp314-cp314-win_amd64.whl", hash = "sha256:bdc919ead48f234740ad807933cdf545180bfbe9342c2bb451556db2ed958581", size = 15341, upload-time = "2025-09-27T18:37:16.496Z" }, + { url = "https://files.pythonhosted.org/packages/6f/18/acf23e91bd94fd7b3031558b1f013adfa21a8e407a3fdb32745538730382/markupsafe-3.0.3-cp314-cp314-win_arm64.whl", hash = "sha256:5a7d5dc5140555cf21a6fefbdbf8723f06fcd2f63ef108f2854de715e4422cb4", size = 14073, upload-time = "2025-09-27T18:37:17.476Z" }, + { url = "https://files.pythonhosted.org/packages/3c/f0/57689aa4076e1b43b15fdfa646b04653969d50cf30c32a102762be2485da/markupsafe-3.0.3-cp314-cp314t-macosx_10_13_x86_64.whl", hash = "sha256:1353ef0c1b138e1907ae78e2f6c63ff67501122006b0f9abad68fda5f4ffc6ab", size = 11661, upload-time = "2025-09-27T18:37:18.453Z" }, + { url = "https://files.pythonhosted.org/packages/89/c3/2e67a7ca217c6912985ec766c6393b636fb0c2344443ff9d91404dc4c79f/markupsafe-3.0.3-cp314-cp314t-macosx_11_0_arm64.whl", hash = "sha256:1085e7fbddd3be5f89cc898938f42c0b3c711fdcb37d75221de2666af647c175", size = 12069, upload-time = "2025-09-27T18:37:19.332Z" }, + { url = "https://files.pythonhosted.org/packages/f0/00/be561dce4e6ca66b15276e184ce4b8aec61fe83662cce2f7d72bd3249d28/markupsafe-3.0.3-cp314-cp314t-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:1b52b4fb9df4eb9ae465f8d0c228a00624de2334f216f178a995ccdcf82c4634", size = 25670, upload-time = "2025-09-27T18:37:20.245Z" }, + { url = "https://files.pythonhosted.org/packages/50/09/c419f6f5a92e5fadde27efd190eca90f05e1261b10dbd8cbcb39cd8ea1dc/markupsafe-3.0.3-cp314-cp314t-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:fed51ac40f757d41b7c48425901843666a6677e3e8eb0abcff09e4ba6e664f50", size = 23598, upload-time = "2025-09-27T18:37:21.177Z" }, + { url = "https://files.pythonhosted.org/packages/22/44/a0681611106e0b2921b3033fc19bc53323e0b50bc70cffdd19f7d679bb66/markupsafe-3.0.3-cp314-cp314t-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:f190daf01f13c72eac4efd5c430a8de82489d9cff23c364c3ea822545032993e", size = 23261, upload-time = "2025-09-27T18:37:22.167Z" }, + { url = "https://files.pythonhosted.org/packages/5f/57/1b0b3f100259dc9fffe780cfb60d4be71375510e435efec3d116b6436d43/markupsafe-3.0.3-cp314-cp314t-musllinux_1_2_aarch64.whl", hash = "sha256:e56b7d45a839a697b5eb268c82a71bd8c7f6c94d6fd50c3d577fa39a9f1409f5", size = 24835, upload-time = "2025-09-27T18:37:23.296Z" }, + { url = "https://files.pythonhosted.org/packages/26/6a/4bf6d0c97c4920f1597cc14dd720705eca0bf7c787aebc6bb4d1bead5388/markupsafe-3.0.3-cp314-cp314t-musllinux_1_2_riscv64.whl", hash = "sha256:f3e98bb3798ead92273dc0e5fd0f31ade220f59a266ffd8a4f6065e0a3ce0523", size = 22733, upload-time = "2025-09-27T18:37:24.237Z" }, + { url = "https://files.pythonhosted.org/packages/14/c7/ca723101509b518797fedc2fdf79ba57f886b4aca8a7d31857ba3ee8281f/markupsafe-3.0.3-cp314-cp314t-musllinux_1_2_x86_64.whl", hash = "sha256:5678211cb9333a6468fb8d8be0305520aa073f50d17f089b5b4b477ea6e67fdc", size = 23672, upload-time = "2025-09-27T18:37:25.271Z" }, + { url = "https://files.pythonhosted.org/packages/fb/df/5bd7a48c256faecd1d36edc13133e51397e41b73bb77e1a69deab746ebac/markupsafe-3.0.3-cp314-cp314t-win32.whl", hash = "sha256:915c04ba3851909ce68ccc2b8e2cd691618c4dc4c4232fb7982bca3f41fd8c3d", size = 14819, upload-time = "2025-09-27T18:37:26.285Z" }, + { url = "https://files.pythonhosted.org/packages/1a/8a/0402ba61a2f16038b48b39bccca271134be00c5c9f0f623208399333c448/markupsafe-3.0.3-cp314-cp314t-win_amd64.whl", hash = "sha256:4faffd047e07c38848ce017e8725090413cd80cbc23d86e55c587bf979e579c9", size = 15426, upload-time = "2025-09-27T18:37:27.316Z" }, + { url = "https://files.pythonhosted.org/packages/70/bc/6f1c2f612465f5fa89b95bead1f44dcb607670fd42891d8fdcd5d039f4f4/markupsafe-3.0.3-cp314-cp314t-win_arm64.whl", hash = "sha256:32001d6a8fc98c8cb5c947787c5d08b0a50663d139f1305bac5885d98d9b40fa", size = 14146, upload-time = "2025-09-27T18:37:28.327Z" }, ] [[package]] name = "mdurl" version = "0.1.2" source = { registry = "https://pypi.org/simple" } -sdist = { url = "https://files.pythonhosted.org/packages/d6/54/cfe61301667036ec958cb99bd3efefba235e65cdeb9c84d24a8293ba1d90/mdurl-0.1.2.tar.gz", hash = "sha256:bb413d29f5eea38f31dd4754dd7377d4465116fb207585f97bf925588687c1ba", size = 8729 } +sdist = { url = "https://files.pythonhosted.org/packages/d6/54/cfe61301667036ec958cb99bd3efefba235e65cdeb9c84d24a8293ba1d90/mdurl-0.1.2.tar.gz", hash = "sha256:bb413d29f5eea38f31dd4754dd7377d4465116fb207585f97bf925588687c1ba", size = 8729, upload-time = "2022-08-14T12:40:10.846Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/b3/38/89ba8ad64ae25be8de66a6d463314cf1eb366222074cfda9ee839c56a4b4/mdurl-0.1.2-py3-none-any.whl", hash = "sha256:84008a41e51615a49fc9966191ff91509e3c40b939176e643fd50a5c2196b8f8", size = 9979 }, + { url = "https://files.pythonhosted.org/packages/b3/38/89ba8ad64ae25be8de66a6d463314cf1eb366222074cfda9ee839c56a4b4/mdurl-0.1.2-py3-none-any.whl", hash = "sha256:84008a41e51615a49fc9966191ff91509e3c40b939176e643fd50a5c2196b8f8", size = 9979, upload-time = "2022-08-14T12:40:09.779Z" }, ] [[package]] name = "mergedeep" version = "1.3.4" source = { registry = "https://pypi.org/simple" } -sdist = { url = "https://files.pythonhosted.org/packages/3a/41/580bb4006e3ed0361b8151a01d324fb03f420815446c7def45d02f74c270/mergedeep-1.3.4.tar.gz", hash = "sha256:0096d52e9dad9939c3d975a774666af186eda617e6ca84df4c94dec30004f2a8", size = 4661 } +sdist = { url = "https://files.pythonhosted.org/packages/3a/41/580bb4006e3ed0361b8151a01d324fb03f420815446c7def45d02f74c270/mergedeep-1.3.4.tar.gz", hash = "sha256:0096d52e9dad9939c3d975a774666af186eda617e6ca84df4c94dec30004f2a8", size = 4661, upload-time = "2021-02-05T18:55:30.623Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/2c/19/04f9b178c2d8a15b076c8b5140708fa6ffc5601fb6f1e975537072df5b2a/mergedeep-1.3.4-py3-none-any.whl", hash = "sha256:70775750742b25c0d8f36c55aed03d24c3384d17c951b3175d898bd778ef0307", size = 6354 }, + { url = "https://files.pythonhosted.org/packages/2c/19/04f9b178c2d8a15b076c8b5140708fa6ffc5601fb6f1e975537072df5b2a/mergedeep-1.3.4-py3-none-any.whl", hash = "sha256:70775750742b25c0d8f36c55aed03d24c3384d17c951b3175d898bd778ef0307", size = 6354, upload-time = "2021-02-05T18:55:29.583Z" }, ] [[package]] @@ -613,23 +773,23 @@ dependencies = [ { name = "pyyaml-env-tag" }, { name = "watchdog" }, ] -sdist = { url = "https://files.pythonhosted.org/packages/bc/c6/bbd4f061bd16b378247f12953ffcb04786a618ce5e904b8c5a01a0309061/mkdocs-1.6.1.tar.gz", hash = "sha256:7b432f01d928c084353ab39c57282f29f92136665bdd6abf7c1ec8d822ef86f2", size = 3889159 } +sdist = { url = "https://files.pythonhosted.org/packages/bc/c6/bbd4f061bd16b378247f12953ffcb04786a618ce5e904b8c5a01a0309061/mkdocs-1.6.1.tar.gz", hash = "sha256:7b432f01d928c084353ab39c57282f29f92136665bdd6abf7c1ec8d822ef86f2", size = 3889159, upload-time = "2024-08-30T12:24:06.899Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/22/5b/dbc6a8cddc9cfa9c4971d59fb12bb8d42e161b7e7f8cc89e49137c5b279c/mkdocs-1.6.1-py3-none-any.whl", hash = "sha256:db91759624d1647f3f34aa0c3f327dd2601beae39a366d6e064c03468d35c20e", size = 3864451 }, + { url = "https://files.pythonhosted.org/packages/22/5b/dbc6a8cddc9cfa9c4971d59fb12bb8d42e161b7e7f8cc89e49137c5b279c/mkdocs-1.6.1-py3-none-any.whl", hash = "sha256:db91759624d1647f3f34aa0c3f327dd2601beae39a366d6e064c03468d35c20e", size = 3864451, upload-time = "2024-08-30T12:24:05.054Z" }, ] [[package]] name = "mkdocs-autorefs" -version = "1.4.2" +version = "1.4.3" source = { registry = "https://pypi.org/simple" } dependencies = [ { name = "markdown" }, { name = "markupsafe" }, { name = "mkdocs" }, ] -sdist = { url = "https://files.pythonhosted.org/packages/47/0c/c9826f35b99c67fa3a7cddfa094c1a6c43fafde558c309c6e4403e5b37dc/mkdocs_autorefs-1.4.2.tar.gz", hash = "sha256:e2ebe1abd2b67d597ed19378c0fff84d73d1dbce411fce7a7cc6f161888b6749", size = 54961 } +sdist = { url = "https://files.pythonhosted.org/packages/51/fa/9124cd63d822e2bcbea1450ae68cdc3faf3655c69b455f3a7ed36ce6c628/mkdocs_autorefs-1.4.3.tar.gz", hash = "sha256:beee715b254455c4aa93b6ef3c67579c399ca092259cc41b7d9342573ff1fc75", size = 55425, upload-time = "2025-08-26T14:23:17.223Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/87/dc/fc063b78f4b769d1956319351704e23ebeba1e9e1d6a41b4b602325fd7e4/mkdocs_autorefs-1.4.2-py3-none-any.whl", hash = "sha256:83d6d777b66ec3c372a1aad4ae0cf77c243ba5bcda5bf0c6b8a2c5e7a3d89f13", size = 24969 }, + { url = "https://files.pythonhosted.org/packages/9f/4d/7123b6fa2278000688ebd338e2a06d16870aaf9eceae6ba047ea05f92df1/mkdocs_autorefs-1.4.3-py3-none-any.whl", hash = "sha256:469d85eb3114801d08e9cc55d102b3ba65917a869b893403b8987b601cf55dc9", size = 25034, upload-time = "2025-08-26T14:23:15.906Z" }, ] [[package]] @@ -641,22 +801,22 @@ dependencies = [ { name = "platformdirs" }, { name = "pyyaml" }, ] -sdist = { url = "https://files.pythonhosted.org/packages/98/f5/ed29cd50067784976f25ed0ed6fcd3c2ce9eb90650aa3b2796ddf7b6870b/mkdocs_get_deps-0.2.0.tar.gz", hash = "sha256:162b3d129c7fad9b19abfdcb9c1458a651628e4b1dea628ac68790fb3061c60c", size = 10239 } +sdist = { url = "https://files.pythonhosted.org/packages/98/f5/ed29cd50067784976f25ed0ed6fcd3c2ce9eb90650aa3b2796ddf7b6870b/mkdocs_get_deps-0.2.0.tar.gz", hash = "sha256:162b3d129c7fad9b19abfdcb9c1458a651628e4b1dea628ac68790fb3061c60c", size = 10239, upload-time = "2023-11-20T17:51:09.981Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/9f/d4/029f984e8d3f3b6b726bd33cafc473b75e9e44c0f7e80a5b29abc466bdea/mkdocs_get_deps-0.2.0-py3-none-any.whl", hash = "sha256:2bf11d0b133e77a0dd036abeeb06dec8775e46efa526dc70667d8863eefc6134", size = 9521 }, + { url = "https://files.pythonhosted.org/packages/9f/d4/029f984e8d3f3b6b726bd33cafc473b75e9e44c0f7e80a5b29abc466bdea/mkdocs_get_deps-0.2.0-py3-none-any.whl", hash = "sha256:2bf11d0b133e77a0dd036abeeb06dec8775e46efa526dc70667d8863eefc6134", size = 9521, upload-time = "2023-11-20T17:51:08.587Z" }, ] [[package]] name = "mkdocs-include-markdown-plugin" -version = "7.1.6" +version = "7.2.0" source = { registry = "https://pypi.org/simple" } dependencies = [ { name = "mkdocs" }, { name = "wcmatch" }, ] -sdist = { url = "https://files.pythonhosted.org/packages/2c/17/988d97ac6849b196f54d45ca9c60ca894880c160a512785f03834704b3d9/mkdocs_include_markdown_plugin-7.1.6.tar.gz", hash = "sha256:a0753cb82704c10a287f1e789fc9848f82b6beb8749814b24b03dd9f67816677", size = 23391 } +sdist = { url = "https://files.pythonhosted.org/packages/90/10/b0b75ac42f4613556a808eee2dad3efe7a7d5079349aa5b9229d863e829f/mkdocs_include_markdown_plugin-7.2.0.tar.gz", hash = "sha256:4a67a91ade680dc0e15f608e5b6343bec03372ffa112c40a4254c1bfb10f42f3", size = 25509, upload-time = "2025-09-28T21:50:50.41Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/e2/a1/6cf1667a05e5f468e1263fcf848772bca8cc9e358cd57ae19a01f92c9f6f/mkdocs_include_markdown_plugin-7.1.6-py3-none-any.whl", hash = "sha256:7975a593514887c18ecb68e11e35c074c5499cfa3e51b18cd16323862e1f7345", size = 27161 }, + { url = "https://files.pythonhosted.org/packages/ba/f9/783338d1d7fd548c7635728b67a0f8f96d9e6c265aa61c51356c03597767/mkdocs_include_markdown_plugin-7.2.0-py3-none-any.whl", hash = "sha256:d56cdaeb2d113fb66ed0fe4fb7af1da889926b0b9872032be24e19bbb09c9f5b", size = 29548, upload-time = "2025-09-28T21:50:49.373Z" }, ] [[package]] @@ -666,14 +826,14 @@ source = { registry = "https://pypi.org/simple" } dependencies = [ { name = "mkdocs" }, ] -sdist = { url = "https://files.pythonhosted.org/packages/f6/5f/99aa379b305cd1c2084d42db3d26f6de0ea9bf2cc1d10ed17f61aff35b9a/mkdocs_literate_nav-0.6.2.tar.gz", hash = "sha256:760e1708aa4be86af81a2b56e82c739d5a8388a0eab1517ecfd8e5aa40810a75", size = 17419 } +sdist = { url = "https://files.pythonhosted.org/packages/f6/5f/99aa379b305cd1c2084d42db3d26f6de0ea9bf2cc1d10ed17f61aff35b9a/mkdocs_literate_nav-0.6.2.tar.gz", hash = "sha256:760e1708aa4be86af81a2b56e82c739d5a8388a0eab1517ecfd8e5aa40810a75", size = 17419, upload-time = "2025-03-18T21:53:09.711Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/8a/84/b5b14d2745e4dd1a90115186284e9ee1b4d0863104011ab46abb7355a1c3/mkdocs_literate_nav-0.6.2-py3-none-any.whl", hash = "sha256:0a6489a26ec7598477b56fa112056a5e3a6c15729f0214bea8a4dbc55bd5f630", size = 13261 }, + { url = "https://files.pythonhosted.org/packages/8a/84/b5b14d2745e4dd1a90115186284e9ee1b4d0863104011ab46abb7355a1c3/mkdocs_literate_nav-0.6.2-py3-none-any.whl", hash = "sha256:0a6489a26ec7598477b56fa112056a5e3a6c15729f0214bea8a4dbc55bd5f630", size = 13261, upload-time = "2025-03-18T21:53:08.1Z" }, ] [[package]] name = "mkdocs-macros-plugin" -version = "1.3.7" +version = "1.4.0" source = { registry = "https://pypi.org/simple" } dependencies = [ { name = "hjson" }, @@ -686,14 +846,14 @@ dependencies = [ { name = "super-collections" }, { name = "termcolor" }, ] -sdist = { url = "https://files.pythonhosted.org/packages/43/65/61a746c56788867221aebf07fe4b6b4c08ac99cf341fd51d728c89d1456e/mkdocs_macros_plugin-1.3.7.tar.gz", hash = "sha256:17c7fd1a49b94defcdb502fd453d17a1e730f8836523379d21292eb2be4cb523", size = 33466 } +sdist = { url = "https://files.pythonhosted.org/packages/f2/8a/1be9f663fff066d68598762e91a9a9e9e4ff901ef1a49fea506847b3b1f5/mkdocs_macros_plugin-1.4.0.tar.gz", hash = "sha256:687e710988736731d1a059633fc34cf66d21e57a07801bdd1991419199e0677c", size = 34758, upload-time = "2025-09-22T14:18:07.258Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/55/cf/f03331298ee50a4da6fb72ccec79078041158c1f8b5fc24835c1be42232e/mkdocs_macros_plugin-1.3.7-py3-none-any.whl", hash = "sha256:02432033a5b77fb247d6ec7924e72fc4ceec264165b1644ab8d0dc159c22ce59", size = 37799 }, + { url = "https://files.pythonhosted.org/packages/c6/88/d20e962f7fddf46094e0e9365bf8167a82a32e3086851b32ef25978ac6cf/mkdocs_macros_plugin-1.4.0-py3-none-any.whl", hash = "sha256:630de99fe14d39c26c7915725b39bb7730058c622f547226432eb371cabff33c", size = 39593, upload-time = "2025-09-22T14:18:06.058Z" }, ] [[package]] name = "mkdocs-material" -version = "9.6.15" +version = "9.6.21" source = { registry = "https://pypi.org/simple" } dependencies = [ { name = "babel" }, @@ -708,23 +868,23 @@ dependencies = [ { name = "pymdown-extensions" }, { name = "requests" }, ] -sdist = { url = "https://files.pythonhosted.org/packages/95/c1/f804ba2db2ddc2183e900befe7dad64339a34fa935034e1ab405289d0a97/mkdocs_material-9.6.15.tar.gz", hash = "sha256:64adf8fa8dba1a17905b6aee1894a5aafd966d4aeb44a11088519b0f5ca4f1b5", size = 3951836 } +sdist = { url = "https://files.pythonhosted.org/packages/ff/d5/ab83ca9aa314954b0a9e8849780bdd01866a3cfcb15ffb7e3a61ca06ff0b/mkdocs_material-9.6.21.tar.gz", hash = "sha256:b01aa6d2731322438056f360f0e623d3faae981f8f2d8c68b1b973f4f2657870", size = 4043097, upload-time = "2025-09-30T19:11:27.517Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/1d/30/dda19f0495a9096b64b6b3c07c4bfcff1c76ee0fc521086d53593f18b4c0/mkdocs_material-9.6.15-py3-none-any.whl", hash = "sha256:ac969c94d4fe5eb7c924b6d2f43d7db41159ea91553d18a9afc4780c34f2717a", size = 8716840 }, + { url = "https://files.pythonhosted.org/packages/cf/4f/98681c2030375fe9b057dbfb9008b68f46c07dddf583f4df09bf8075e37f/mkdocs_material-9.6.21-py3-none-any.whl", hash = "sha256:aa6a5ab6fb4f6d381588ac51da8782a4d3757cb3d1b174f81a2ec126e1f22c92", size = 9203097, upload-time = "2025-09-30T19:11:24.063Z" }, ] [[package]] name = "mkdocs-material-extensions" version = "1.3.1" source = { registry = "https://pypi.org/simple" } -sdist = { url = "https://files.pythonhosted.org/packages/79/9b/9b4c96d6593b2a541e1cb8b34899a6d021d208bb357042823d4d2cabdbe7/mkdocs_material_extensions-1.3.1.tar.gz", hash = "sha256:10c9511cea88f568257f960358a467d12b970e1f7b2c0e5fb2bb48cab1928443", size = 11847 } +sdist = { url = "https://files.pythonhosted.org/packages/79/9b/9b4c96d6593b2a541e1cb8b34899a6d021d208bb357042823d4d2cabdbe7/mkdocs_material_extensions-1.3.1.tar.gz", hash = "sha256:10c9511cea88f568257f960358a467d12b970e1f7b2c0e5fb2bb48cab1928443", size = 11847, upload-time = "2023-11-22T19:09:45.208Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/5b/54/662a4743aa81d9582ee9339d4ffa3c8fd40a4965e033d77b9da9774d3960/mkdocs_material_extensions-1.3.1-py3-none-any.whl", hash = "sha256:adff8b62700b25cb77b53358dad940f3ef973dd6db797907c49e3c2ef3ab4e31", size = 8728 }, + { url = "https://files.pythonhosted.org/packages/5b/54/662a4743aa81d9582ee9339d4ffa3c8fd40a4965e033d77b9da9774d3960/mkdocs_material_extensions-1.3.1-py3-none-any.whl", hash = "sha256:adff8b62700b25cb77b53358dad940f3ef973dd6db797907c49e3c2ef3ab4e31", size = 8728, upload-time = "2023-11-22T19:09:43.465Z" }, ] [[package]] name = "mkdocstrings" -version = "0.29.1" +version = "0.30.1" source = { registry = "https://pypi.org/simple" } dependencies = [ { name = "jinja2" }, @@ -734,14 +894,14 @@ dependencies = [ { name = "mkdocs-autorefs" }, { name = "pymdown-extensions" }, ] -sdist = { url = "https://files.pythonhosted.org/packages/41/e8/d22922664a627a0d3d7ff4a6ca95800f5dde54f411982591b4621a76225d/mkdocstrings-0.29.1.tar.gz", hash = "sha256:8722f8f8c5cd75da56671e0a0c1bbed1df9946c0cef74794d6141b34011abd42", size = 1212686 } +sdist = { url = "https://files.pythonhosted.org/packages/c5/33/2fa3243439f794e685d3e694590d28469a9b8ea733af4b48c250a3ffc9a0/mkdocstrings-0.30.1.tar.gz", hash = "sha256:84a007aae9b707fb0aebfc9da23db4b26fc9ab562eb56e335e9ec480cb19744f", size = 106350, upload-time = "2025-09-19T10:49:26.446Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/98/14/22533a578bf8b187e05d67e2c1721ce10e3f526610eebaf7a149d557ea7a/mkdocstrings-0.29.1-py3-none-any.whl", hash = "sha256:37a9736134934eea89cbd055a513d40a020d87dfcae9e3052c2a6b8cd4af09b6", size = 1631075 }, + { url = "https://files.pythonhosted.org/packages/7b/2c/f0dc4e1ee7f618f5bff7e05898d20bf8b6e7fa612038f768bfa295f136a4/mkdocstrings-0.30.1-py3-none-any.whl", hash = "sha256:41bd71f284ca4d44a668816193e4025c950b002252081e387433656ae9a70a82", size = 36704, upload-time = "2025-09-19T10:49:24.805Z" }, ] [[package]] name = "mkdocstrings-python" -version = "1.16.12" +version = "1.18.2" source = { registry = "https://pypi.org/simple" } dependencies = [ { name = "griffe" }, @@ -749,93 +909,104 @@ dependencies = [ { name = "mkdocstrings" }, { name = "typing-extensions", marker = "python_full_version < '3.11'" }, ] -sdist = { url = "https://files.pythonhosted.org/packages/bf/ed/b886f8c714fd7cccc39b79646b627dbea84cd95c46be43459ef46852caf0/mkdocstrings_python-1.16.12.tar.gz", hash = "sha256:9b9eaa066e0024342d433e332a41095c4e429937024945fea511afe58f63175d", size = 206065 } +sdist = { url = "https://files.pythonhosted.org/packages/95/ae/58ab2bfbee2792e92a98b97e872f7c003deb903071f75d8d83aa55db28fa/mkdocstrings_python-1.18.2.tar.gz", hash = "sha256:4ad536920a07b6336f50d4c6d5603316fafb1172c5c882370cbbc954770ad323", size = 207972, upload-time = "2025-08-28T16:11:19.847Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/3b/dd/a24ee3de56954bfafb6ede7cd63c2413bb842cc48eb45e41c43a05a33074/mkdocstrings_python-1.16.12-py3-none-any.whl", hash = "sha256:22ded3a63b3d823d57457a70ff9860d5a4de9e8b1e482876fc9baabaf6f5f374", size = 124287 }, + { url = "https://files.pythonhosted.org/packages/d5/8f/ce008599d9adebf33ed144e7736914385e8537f5fc686fdb7cceb8c22431/mkdocstrings_python-1.18.2-py3-none-any.whl", hash = "sha256:944fe6deb8f08f33fa936d538233c4036e9f53e840994f6146e8e94eb71b600d", size = 138215, upload-time = "2025-08-28T16:11:18.176Z" }, ] [[package]] name = "ml-dtypes" -version = "0.5.1" +version = "0.5.3" source = { registry = "https://pypi.org/simple" } dependencies = [ { name = "numpy", version = "2.2.6", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version < '3.11'" }, - { name = "numpy", version = "2.3.1", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version >= '3.11'" }, -] -sdist = { url = "https://files.pythonhosted.org/packages/32/49/6e67c334872d2c114df3020e579f3718c333198f8312290e09ec0216703a/ml_dtypes-0.5.1.tar.gz", hash = "sha256:ac5b58559bb84a95848ed6984eb8013249f90b6bab62aa5acbad876e256002c9", size = 698772 } -wheels = [ - { url = "https://files.pythonhosted.org/packages/f4/88/11ebdbc75445eeb5b6869b708a0d787d1ed812ff86c2170bbfb95febdce1/ml_dtypes-0.5.1-cp310-cp310-macosx_10_9_universal2.whl", hash = "sha256:bd73f51957949069573ff783563486339a9285d72e2f36c18e0c1aa9ca7eb190", size = 671450 }, - { url = "https://files.pythonhosted.org/packages/a4/a4/9321cae435d6140f9b0e7af8334456a854b60e3a9c6101280a16e3594965/ml_dtypes-0.5.1-cp310-cp310-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:810512e2eccdfc3b41eefa3a27402371a3411453a1efc7e9c000318196140fed", size = 4621075 }, - { url = "https://files.pythonhosted.org/packages/16/d8/4502e12c6a10d42e13a552e8d97f20198e3cf82a0d1411ad50be56a5077c/ml_dtypes-0.5.1-cp310-cp310-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:141b2ea2f20bb10802ddca55d91fe21231ef49715cfc971998e8f2a9838f3dbe", size = 4738414 }, - { url = "https://files.pythonhosted.org/packages/6b/7e/bc54ae885e4d702e60a4bf50aa9066ff35e9c66b5213d11091f6bffb3036/ml_dtypes-0.5.1-cp310-cp310-win_amd64.whl", hash = "sha256:26ebcc69d7b779c8f129393e99732961b5cc33fcff84090451f448c89b0e01b4", size = 209718 }, - { url = "https://files.pythonhosted.org/packages/c9/fd/691335926126bb9beeb030b61a28f462773dcf16b8e8a2253b599013a303/ml_dtypes-0.5.1-cp311-cp311-macosx_10_9_universal2.whl", hash = "sha256:023ce2f502efd4d6c1e0472cc58ce3640d051d40e71e27386bed33901e201327", size = 671448 }, - { url = "https://files.pythonhosted.org/packages/ff/a6/63832d91f2feb250d865d069ba1a5d0c686b1f308d1c74ce9764472c5e22/ml_dtypes-0.5.1-cp311-cp311-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:7000b6e4d8ef07542c05044ec5d8bbae1df083b3f56822c3da63993a113e716f", size = 4625792 }, - { url = "https://files.pythonhosted.org/packages/cc/2a/5421fd3dbe6eef9b844cc9d05f568b9fb568503a2e51cb1eb4443d9fc56b/ml_dtypes-0.5.1-cp311-cp311-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:c09526488c3a9e8b7a23a388d4974b670a9a3dd40c5c8a61db5593ce9b725bab", size = 4743893 }, - { url = "https://files.pythonhosted.org/packages/60/30/d3f0fc9499a22801219679a7f3f8d59f1429943c6261f445fb4bfce20718/ml_dtypes-0.5.1-cp311-cp311-win_amd64.whl", hash = "sha256:15ad0f3b0323ce96c24637a88a6f44f6713c64032f27277b069f285c3cf66478", size = 209712 }, - { url = "https://files.pythonhosted.org/packages/47/56/1bb21218e1e692506c220ffabd456af9733fba7aa1b14f73899979f4cc20/ml_dtypes-0.5.1-cp312-cp312-macosx_10_9_universal2.whl", hash = "sha256:6f462f5eca22fb66d7ff9c4744a3db4463af06c49816c4b6ac89b16bfcdc592e", size = 670372 }, - { url = "https://files.pythonhosted.org/packages/20/95/d8bd96a3b60e00bf31bd78ca4bdd2d6bbaf5acb09b42844432d719d34061/ml_dtypes-0.5.1-cp312-cp312-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:6f76232163b5b9c34291b54621ee60417601e2e4802a188a0ea7157cd9b323f4", size = 4635946 }, - { url = "https://files.pythonhosted.org/packages/08/57/5d58fad4124192b1be42f68bd0c0ddaa26e44a730ff8c9337adade2f5632/ml_dtypes-0.5.1-cp312-cp312-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:ad4953c5eb9c25a56d11a913c2011d7e580a435ef5145f804d98efa14477d390", size = 4694804 }, - { url = "https://files.pythonhosted.org/packages/38/bc/c4260e4a6c6bf684d0313308de1c860467275221d5e7daf69b3fcddfdd0b/ml_dtypes-0.5.1-cp312-cp312-win_amd64.whl", hash = "sha256:9626d0bca1fb387d5791ca36bacbba298c5ef554747b7ebeafefb4564fc83566", size = 210853 }, - { url = "https://files.pythonhosted.org/packages/0f/92/bb6a3d18e16fddd18ce6d5f480e1919b33338c70e18cba831c6ae59812ee/ml_dtypes-0.5.1-cp313-cp313-macosx_10_13_universal2.whl", hash = "sha256:12651420130ee7cc13059fc56dac6ad300c3af3848b802d475148c9defd27c23", size = 667696 }, - { url = "https://files.pythonhosted.org/packages/6d/29/cfc89d842767e9a51146043b0fa18332c2b38f8831447e6cb1160e3c6102/ml_dtypes-0.5.1-cp313-cp313-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:c9945669d3dadf8acb40ec2e57d38c985d8c285ea73af57fc5b09872c516106d", size = 4638365 }, - { url = "https://files.pythonhosted.org/packages/be/26/adc36e3ea09603d9f6d114894e1c1b7b8e8a9ef6d0b031cc270c6624a37c/ml_dtypes-0.5.1-cp313-cp313-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:bf9975bda82a99dc935f2ae4c83846d86df8fd6ba179614acac8e686910851da", size = 4702722 }, - { url = "https://files.pythonhosted.org/packages/da/8a/a2b9375c94077e5a488a624a195621407846f504068ce22ccf805c674156/ml_dtypes-0.5.1-cp313-cp313-win_amd64.whl", hash = "sha256:fd918d4e6a4e0c110e2e05be7a7814d10dc1b95872accbf6512b80a109b71ae1", size = 210850 }, - { url = "https://files.pythonhosted.org/packages/52/38/703169100fdde27957f061d4d0ea3e00525775a09acaccf7e655d9609d55/ml_dtypes-0.5.1-cp313-cp313t-macosx_10_13_universal2.whl", hash = "sha256:05f23447a1c20ddf4dc7c2c661aa9ed93fcb2658f1017c204d1e758714dc28a8", size = 693043 }, - { url = "https://files.pythonhosted.org/packages/28/ff/4e234c9c23e0d456f5da5a326c103bf890c746d93351524d987e41f438b3/ml_dtypes-0.5.1-cp313-cp313t-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:1b7fbe5571fdf28fd3aaab3ef4aafc847de9ebf263be959958c1ca58ec8eadf5", size = 4903946 }, - { url = "https://files.pythonhosted.org/packages/b7/45/c1a1ccfdd02bc4173ca0f4a2d327683a27df85797b885eb1da1ca325b85c/ml_dtypes-0.5.1-cp313-cp313t-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:d13755f8e8445b3870114e5b6240facaa7cb0c3361e54beba3e07fa912a6e12b", size = 5052731 }, + { name = "numpy", version = "2.3.3", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version >= '3.11'" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/78/a7/aad060393123cfb383956dca68402aff3db1e1caffd5764887ed5153f41b/ml_dtypes-0.5.3.tar.gz", hash = "sha256:95ce33057ba4d05df50b1f3cfefab22e351868a843b3b15a46c65836283670c9", size = 692316, upload-time = "2025-07-29T18:39:19.454Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/ac/bb/1f32124ab6d3a279ea39202fe098aea95b2d81ef0ce1d48612b6bf715e82/ml_dtypes-0.5.3-cp310-cp310-macosx_10_9_universal2.whl", hash = "sha256:0a1d68a7cb53e3f640b2b6a34d12c0542da3dd935e560fdf463c0c77f339fc20", size = 667409, upload-time = "2025-07-29T18:38:17.321Z" }, + { url = "https://files.pythonhosted.org/packages/1d/ac/e002d12ae19136e25bb41c7d14d7e1a1b08f3c0e99a44455ff6339796507/ml_dtypes-0.5.3-cp310-cp310-manylinux_2_27_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:0cd5a6c711b5350f3cbc2ac28def81cd1c580075ccb7955e61e9d8f4bfd40d24", size = 4960702, upload-time = "2025-07-29T18:38:19.616Z" }, + { url = "https://files.pythonhosted.org/packages/dd/12/79e9954e6b3255a4b1becb191a922d6e2e94d03d16a06341ae9261963ae8/ml_dtypes-0.5.3-cp310-cp310-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:bdcf26c2dbc926b8a35ec8cbfad7eff1a8bd8239e12478caca83a1fc2c400dc2", size = 4933471, upload-time = "2025-07-29T18:38:21.809Z" }, + { url = "https://files.pythonhosted.org/packages/d5/aa/d1eff619e83cd1ddf6b561d8240063d978e5d887d1861ba09ef01778ec3a/ml_dtypes-0.5.3-cp310-cp310-win_amd64.whl", hash = "sha256:aecbd7c5272c82e54d5b99d8435fd10915d1bc704b7df15e4d9ca8dc3902be61", size = 206330, upload-time = "2025-07-29T18:38:23.663Z" }, + { url = "https://files.pythonhosted.org/packages/af/f1/720cb1409b5d0c05cff9040c0e9fba73fa4c67897d33babf905d5d46a070/ml_dtypes-0.5.3-cp311-cp311-macosx_10_9_universal2.whl", hash = "sha256:4a177b882667c69422402df6ed5c3428ce07ac2c1f844d8a1314944651439458", size = 667412, upload-time = "2025-07-29T18:38:25.275Z" }, + { url = "https://files.pythonhosted.org/packages/6a/d5/05861ede5d299f6599f86e6bc1291714e2116d96df003cfe23cc54bcc568/ml_dtypes-0.5.3-cp311-cp311-manylinux_2_27_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:9849ce7267444c0a717c80c6900997de4f36e2815ce34ac560a3edb2d9a64cd2", size = 4964606, upload-time = "2025-07-29T18:38:27.045Z" }, + { url = "https://files.pythonhosted.org/packages/db/dc/72992b68de367741bfab8df3b3fe7c29f982b7279d341aa5bf3e7ef737ea/ml_dtypes-0.5.3-cp311-cp311-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:c3f5ae0309d9f888fd825c2e9d0241102fadaca81d888f26f845bc8c13c1e4ee", size = 4938435, upload-time = "2025-07-29T18:38:29.193Z" }, + { url = "https://files.pythonhosted.org/packages/81/1c/d27a930bca31fb07d975a2d7eaf3404f9388114463b9f15032813c98f893/ml_dtypes-0.5.3-cp311-cp311-win_amd64.whl", hash = "sha256:58e39349d820b5702bb6f94ea0cb2dc8ec62ee81c0267d9622067d8333596a46", size = 206334, upload-time = "2025-07-29T18:38:30.687Z" }, + { url = "https://files.pythonhosted.org/packages/1a/d8/6922499effa616012cb8dc445280f66d100a7ff39b35c864cfca019b3f89/ml_dtypes-0.5.3-cp311-cp311-win_arm64.whl", hash = "sha256:66c2756ae6cfd7f5224e355c893cfd617fa2f747b8bbd8996152cbdebad9a184", size = 157584, upload-time = "2025-07-29T18:38:32.187Z" }, + { url = "https://files.pythonhosted.org/packages/0d/eb/bc07c88a6ab002b4635e44585d80fa0b350603f11a2097c9d1bfacc03357/ml_dtypes-0.5.3-cp312-cp312-macosx_10_13_universal2.whl", hash = "sha256:156418abeeda48ea4797db6776db3c5bdab9ac7be197c1233771e0880c304057", size = 663864, upload-time = "2025-07-29T18:38:33.777Z" }, + { url = "https://files.pythonhosted.org/packages/cf/89/11af9b0f21b99e6386b6581ab40fb38d03225f9de5f55cf52097047e2826/ml_dtypes-0.5.3-cp312-cp312-manylinux_2_27_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:1db60c154989af253f6c4a34e8a540c2c9dce4d770784d426945e09908fbb177", size = 4951313, upload-time = "2025-07-29T18:38:36.45Z" }, + { url = "https://files.pythonhosted.org/packages/d8/a9/b98b86426c24900b0c754aad006dce2863df7ce0bb2bcc2c02f9cc7e8489/ml_dtypes-0.5.3-cp312-cp312-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:1b255acada256d1fa8c35ed07b5f6d18bc21d1556f842fbc2d5718aea2cd9e55", size = 4928805, upload-time = "2025-07-29T18:38:38.29Z" }, + { url = "https://files.pythonhosted.org/packages/50/c1/85e6be4fc09c6175f36fb05a45917837f30af9a5146a5151cb3a3f0f9e09/ml_dtypes-0.5.3-cp312-cp312-win_amd64.whl", hash = "sha256:da65e5fd3eea434ccb8984c3624bc234ddcc0d9f4c81864af611aaebcc08a50e", size = 208182, upload-time = "2025-07-29T18:38:39.72Z" }, + { url = "https://files.pythonhosted.org/packages/9e/17/cf5326d6867be057f232d0610de1458f70a8ce7b6290e4b4a277ea62b4cd/ml_dtypes-0.5.3-cp312-cp312-win_arm64.whl", hash = "sha256:8bb9cd1ce63096567f5f42851f5843b5a0ea11511e50039a7649619abfb4ba6d", size = 161560, upload-time = "2025-07-29T18:38:41.072Z" }, + { url = "https://files.pythonhosted.org/packages/2d/87/1bcc98a66de7b2455dfb292f271452cac9edc4e870796e0d87033524d790/ml_dtypes-0.5.3-cp313-cp313-macosx_10_13_universal2.whl", hash = "sha256:5103856a225465371fe119f2fef737402b705b810bd95ad5f348e6e1a6ae21af", size = 663781, upload-time = "2025-07-29T18:38:42.984Z" }, + { url = "https://files.pythonhosted.org/packages/fd/2c/bd2a79ba7c759ee192b5601b675b180a3fd6ccf48ffa27fe1782d280f1a7/ml_dtypes-0.5.3-cp313-cp313-manylinux_2_27_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:4cae435a68861660af81fa3c5af16b70ca11a17275c5b662d9c6f58294e0f113", size = 4956217, upload-time = "2025-07-29T18:38:44.65Z" }, + { url = "https://files.pythonhosted.org/packages/14/f3/091ba84e5395d7fe5b30c081a44dec881cd84b408db1763ee50768b2ab63/ml_dtypes-0.5.3-cp313-cp313-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:6936283b56d74fbec431ca57ce58a90a908fdbd14d4e2d22eea6d72bb208a7b7", size = 4933109, upload-time = "2025-07-29T18:38:46.405Z" }, + { url = "https://files.pythonhosted.org/packages/bc/24/054036dbe32c43295382c90a1363241684c4d6aaa1ecc3df26bd0c8d5053/ml_dtypes-0.5.3-cp313-cp313-win_amd64.whl", hash = "sha256:d0f730a17cf4f343b2c7ad50cee3bd19e969e793d2be6ed911f43086460096e4", size = 208187, upload-time = "2025-07-29T18:38:48.24Z" }, + { url = "https://files.pythonhosted.org/packages/a6/3d/7dc3ec6794a4a9004c765e0c341e32355840b698f73fd2daff46f128afc1/ml_dtypes-0.5.3-cp313-cp313-win_arm64.whl", hash = "sha256:2db74788fc01914a3c7f7da0763427280adfc9cd377e9604b6b64eb8097284bd", size = 161559, upload-time = "2025-07-29T18:38:50.493Z" }, + { url = "https://files.pythonhosted.org/packages/12/91/e6c7a0d67a152b9330445f9f0cf8ae6eee9b83f990b8c57fe74631e42a90/ml_dtypes-0.5.3-cp313-cp313t-macosx_10_13_universal2.whl", hash = "sha256:93c36a08a6d158db44f2eb9ce3258e53f24a9a4a695325a689494f0fdbc71770", size = 689321, upload-time = "2025-07-29T18:38:52.03Z" }, + { url = "https://files.pythonhosted.org/packages/9e/6c/b7b94b84a104a5be1883305b87d4c6bd6ae781504474b4cca067cb2340ec/ml_dtypes-0.5.3-cp313-cp313t-manylinux_2_27_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:0e44a3761f64bc009d71ddb6d6c71008ba21b53ab6ee588dadab65e2fa79eafc", size = 5274495, upload-time = "2025-07-29T18:38:53.797Z" }, + { url = "https://files.pythonhosted.org/packages/5b/38/6266604dffb43378055394ea110570cf261a49876fc48f548dfe876f34cc/ml_dtypes-0.5.3-cp313-cp313t-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:bdf40d2aaabd3913dec11840f0d0ebb1b93134f99af6a0a4fd88ffe924928ab4", size = 5285422, upload-time = "2025-07-29T18:38:56.603Z" }, + { url = "https://files.pythonhosted.org/packages/7c/88/8612ff177d043a474b9408f0382605d881eeb4125ba89d4d4b3286573a83/ml_dtypes-0.5.3-cp314-cp314-macosx_10_13_universal2.whl", hash = "sha256:aec640bd94c4c85c0d11e2733bd13cbb10438fb004852996ec0efbc6cacdaf70", size = 661182, upload-time = "2025-07-29T18:38:58.414Z" }, + { url = "https://files.pythonhosted.org/packages/6f/2b/0569a5e88b29240d373e835107c94ae9256fb2191d3156b43b2601859eff/ml_dtypes-0.5.3-cp314-cp314-manylinux_2_27_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:bda32ce212baa724e03c68771e5c69f39e584ea426bfe1a701cb01508ffc7035", size = 4956187, upload-time = "2025-07-29T18:39:00.611Z" }, + { url = "https://files.pythonhosted.org/packages/51/66/273c2a06ae44562b104b61e6b14444da00061fd87652506579d7eb2c40b1/ml_dtypes-0.5.3-cp314-cp314-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:c205cac07d24a29840c163d6469f61069ce4b065518519216297fc2f261f8db9", size = 4930911, upload-time = "2025-07-29T18:39:02.405Z" }, + { url = "https://files.pythonhosted.org/packages/93/ab/606be3e87dc0821bd360c8c1ee46108025c31a4f96942b63907bb441b87d/ml_dtypes-0.5.3-cp314-cp314-win_amd64.whl", hash = "sha256:cd7c0bb22d4ff86d65ad61b5dd246812e8993fbc95b558553624c33e8b6903ea", size = 216664, upload-time = "2025-07-29T18:39:03.927Z" }, + { url = "https://files.pythonhosted.org/packages/30/a2/e900690ca47d01dffffd66375c5de8c4f8ced0f1ef809ccd3b25b3e6b8fa/ml_dtypes-0.5.3-cp314-cp314-win_arm64.whl", hash = "sha256:9d55ea7f7baf2aed61bf1872116cefc9d0c3693b45cae3916897ee27ef4b835e", size = 160203, upload-time = "2025-07-29T18:39:05.671Z" }, + { url = "https://files.pythonhosted.org/packages/53/21/783dfb51f40d2660afeb9bccf3612b99f6a803d980d2a09132b0f9d216ab/ml_dtypes-0.5.3-cp314-cp314t-macosx_10_13_universal2.whl", hash = "sha256:e12e29764a0e66a7a31e9b8bf1de5cc0423ea72979f45909acd4292de834ccd3", size = 689324, upload-time = "2025-07-29T18:39:07.567Z" }, + { url = "https://files.pythonhosted.org/packages/09/f7/a82d249c711abf411ac027b7163f285487f5e615c3e0716c61033ce996ab/ml_dtypes-0.5.3-cp314-cp314t-manylinux_2_27_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:19f6c3a4f635c2fc9e2aa7d91416bd7a3d649b48350c51f7f715a09370a90d93", size = 5275917, upload-time = "2025-07-29T18:39:09.339Z" }, + { url = "https://files.pythonhosted.org/packages/7f/3c/541c4b30815ab90ebfbb51df15d0b4254f2f9f1e2b4907ab229300d5e6f2/ml_dtypes-0.5.3-cp314-cp314t-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:5ab039ffb40f3dc0aeeeba84fd6c3452781b5e15bef72e2d10bcb33e4bbffc39", size = 5285284, upload-time = "2025-07-29T18:39:11.532Z" }, ] [[package]] name = "msgpack" version = "1.1.1" source = { registry = "https://pypi.org/simple" } -sdist = { url = "https://files.pythonhosted.org/packages/45/b1/ea4f68038a18c77c9467400d166d74c4ffa536f34761f7983a104357e614/msgpack-1.1.1.tar.gz", hash = "sha256:77b79ce34a2bdab2594f490c8e80dd62a02d650b91a75159a63ec413b8d104cd", size = 173555 } -wheels = [ - { url = "https://files.pythonhosted.org/packages/33/52/f30da112c1dc92cf64f57d08a273ac771e7b29dea10b4b30369b2d7e8546/msgpack-1.1.1-cp310-cp310-macosx_10_9_x86_64.whl", hash = "sha256:353b6fc0c36fde68b661a12949d7d49f8f51ff5fa019c1e47c87c4ff34b080ed", size = 81799 }, - { url = "https://files.pythonhosted.org/packages/e4/35/7bfc0def2f04ab4145f7f108e3563f9b4abae4ab0ed78a61f350518cc4d2/msgpack-1.1.1-cp310-cp310-macosx_11_0_arm64.whl", hash = "sha256:79c408fcf76a958491b4e3b103d1c417044544b68e96d06432a189b43d1215c8", size = 78278 }, - { url = "https://files.pythonhosted.org/packages/e8/c5/df5d6c1c39856bc55f800bf82778fd4c11370667f9b9e9d51b2f5da88f20/msgpack-1.1.1-cp310-cp310-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:78426096939c2c7482bf31ef15ca219a9e24460289c00dd0b94411040bb73ad2", size = 402805 }, - { url = "https://files.pythonhosted.org/packages/20/8e/0bb8c977efecfe6ea7116e2ed73a78a8d32a947f94d272586cf02a9757db/msgpack-1.1.1-cp310-cp310-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:8b17ba27727a36cb73aabacaa44b13090feb88a01d012c0f4be70c00f75048b4", size = 408642 }, - { url = "https://files.pythonhosted.org/packages/59/a1/731d52c1aeec52006be6d1f8027c49fdc2cfc3ab7cbe7c28335b2910d7b6/msgpack-1.1.1-cp310-cp310-manylinux_2_5_i686.manylinux1_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:7a17ac1ea6ec3c7687d70201cfda3b1e8061466f28f686c24f627cae4ea8efd0", size = 395143 }, - { url = "https://files.pythonhosted.org/packages/2b/92/b42911c52cda2ba67a6418ffa7d08969edf2e760b09015593c8a8a27a97d/msgpack-1.1.1-cp310-cp310-musllinux_1_2_aarch64.whl", hash = "sha256:88d1e966c9235c1d4e2afac21ca83933ba59537e2e2727a999bf3f515ca2af26", size = 395986 }, - { url = "https://files.pythonhosted.org/packages/61/dc/8ae165337e70118d4dab651b8b562dd5066dd1e6dd57b038f32ebc3e2f07/msgpack-1.1.1-cp310-cp310-musllinux_1_2_i686.whl", hash = "sha256:f6d58656842e1b2ddbe07f43f56b10a60f2ba5826164910968f5933e5178af75", size = 402682 }, - { url = "https://files.pythonhosted.org/packages/58/27/555851cb98dcbd6ce041df1eacb25ac30646575e9cd125681aa2f4b1b6f1/msgpack-1.1.1-cp310-cp310-musllinux_1_2_x86_64.whl", hash = "sha256:96decdfc4adcbc087f5ea7ebdcfd3dee9a13358cae6e81d54be962efc38f6338", size = 406368 }, - { url = "https://files.pythonhosted.org/packages/d4/64/39a26add4ce16f24e99eabb9005e44c663db00e3fce17d4ae1ae9d61df99/msgpack-1.1.1-cp310-cp310-win32.whl", hash = "sha256:6640fd979ca9a212e4bcdf6eb74051ade2c690b862b679bfcb60ae46e6dc4bfd", size = 65004 }, - { url = "https://files.pythonhosted.org/packages/7d/18/73dfa3e9d5d7450d39debde5b0d848139f7de23bd637a4506e36c9800fd6/msgpack-1.1.1-cp310-cp310-win_amd64.whl", hash = "sha256:8b65b53204fe1bd037c40c4148d00ef918eb2108d24c9aaa20bc31f9810ce0a8", size = 71548 }, - { url = "https://files.pythonhosted.org/packages/7f/83/97f24bf9848af23fe2ba04380388216defc49a8af6da0c28cc636d722502/msgpack-1.1.1-cp311-cp311-macosx_10_9_x86_64.whl", hash = "sha256:71ef05c1726884e44f8b1d1773604ab5d4d17729d8491403a705e649116c9558", size = 82728 }, - { url = "https://files.pythonhosted.org/packages/aa/7f/2eaa388267a78401f6e182662b08a588ef4f3de6f0eab1ec09736a7aaa2b/msgpack-1.1.1-cp311-cp311-macosx_11_0_arm64.whl", hash = "sha256:36043272c6aede309d29d56851f8841ba907a1a3d04435e43e8a19928e243c1d", size = 79279 }, - { url = "https://files.pythonhosted.org/packages/f8/46/31eb60f4452c96161e4dfd26dbca562b4ec68c72e4ad07d9566d7ea35e8a/msgpack-1.1.1-cp311-cp311-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:a32747b1b39c3ac27d0670122b57e6e57f28eefb725e0b625618d1b59bf9d1e0", size = 423859 }, - { url = "https://files.pythonhosted.org/packages/45/16/a20fa8c32825cc7ae8457fab45670c7a8996d7746ce80ce41cc51e3b2bd7/msgpack-1.1.1-cp311-cp311-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:8a8b10fdb84a43e50d38057b06901ec9da52baac6983d3f709d8507f3889d43f", size = 429975 }, - { url = "https://files.pythonhosted.org/packages/86/ea/6c958e07692367feeb1a1594d35e22b62f7f476f3c568b002a5ea09d443d/msgpack-1.1.1-cp311-cp311-manylinux_2_5_i686.manylinux1_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:ba0c325c3f485dc54ec298d8b024e134acf07c10d494ffa24373bea729acf704", size = 413528 }, - { url = "https://files.pythonhosted.org/packages/75/05/ac84063c5dae79722bda9f68b878dc31fc3059adb8633c79f1e82c2cd946/msgpack-1.1.1-cp311-cp311-musllinux_1_2_aarch64.whl", hash = "sha256:88daaf7d146e48ec71212ce21109b66e06a98e5e44dca47d853cbfe171d6c8d2", size = 413338 }, - { url = "https://files.pythonhosted.org/packages/69/e8/fe86b082c781d3e1c09ca0f4dacd457ede60a13119b6ce939efe2ea77b76/msgpack-1.1.1-cp311-cp311-musllinux_1_2_i686.whl", hash = "sha256:d8b55ea20dc59b181d3f47103f113e6f28a5e1c89fd5b67b9140edb442ab67f2", size = 422658 }, - { url = "https://files.pythonhosted.org/packages/3b/2b/bafc9924df52d8f3bb7c00d24e57be477f4d0f967c0a31ef5e2225e035c7/msgpack-1.1.1-cp311-cp311-musllinux_1_2_x86_64.whl", hash = "sha256:4a28e8072ae9779f20427af07f53bbb8b4aa81151054e882aee333b158da8752", size = 427124 }, - { url = "https://files.pythonhosted.org/packages/a2/3b/1f717e17e53e0ed0b68fa59e9188f3f610c79d7151f0e52ff3cd8eb6b2dc/msgpack-1.1.1-cp311-cp311-win32.whl", hash = "sha256:7da8831f9a0fdb526621ba09a281fadc58ea12701bc709e7b8cbc362feabc295", size = 65016 }, - { url = "https://files.pythonhosted.org/packages/48/45/9d1780768d3b249accecc5a38c725eb1e203d44a191f7b7ff1941f7df60c/msgpack-1.1.1-cp311-cp311-win_amd64.whl", hash = "sha256:5fd1b58e1431008a57247d6e7cc4faa41c3607e8e7d4aaf81f7c29ea013cb458", size = 72267 }, - { url = "https://files.pythonhosted.org/packages/e3/26/389b9c593eda2b8551b2e7126ad3a06af6f9b44274eb3a4f054d48ff7e47/msgpack-1.1.1-cp312-cp312-macosx_10_13_x86_64.whl", hash = "sha256:ae497b11f4c21558d95de9f64fff7053544f4d1a17731c866143ed6bb4591238", size = 82359 }, - { url = "https://files.pythonhosted.org/packages/ab/65/7d1de38c8a22cf8b1551469159d4b6cf49be2126adc2482de50976084d78/msgpack-1.1.1-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:33be9ab121df9b6b461ff91baac6f2731f83d9b27ed948c5b9d1978ae28bf157", size = 79172 }, - { url = "https://files.pythonhosted.org/packages/0f/bd/cacf208b64d9577a62c74b677e1ada005caa9b69a05a599889d6fc2ab20a/msgpack-1.1.1-cp312-cp312-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:6f64ae8fe7ffba251fecb8408540c34ee9df1c26674c50c4544d72dbf792e5ce", size = 425013 }, - { url = "https://files.pythonhosted.org/packages/4d/ec/fd869e2567cc9c01278a736cfd1697941ba0d4b81a43e0aa2e8d71dab208/msgpack-1.1.1-cp312-cp312-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:a494554874691720ba5891c9b0b39474ba43ffb1aaf32a5dac874effb1619e1a", size = 426905 }, - { url = "https://files.pythonhosted.org/packages/55/2a/35860f33229075bce803a5593d046d8b489d7ba2fc85701e714fc1aaf898/msgpack-1.1.1-cp312-cp312-manylinux_2_5_i686.manylinux1_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:cb643284ab0ed26f6957d969fe0dd8bb17beb567beb8998140b5e38a90974f6c", size = 407336 }, - { url = "https://files.pythonhosted.org/packages/8c/16/69ed8f3ada150bf92745fb4921bd621fd2cdf5a42e25eb50bcc57a5328f0/msgpack-1.1.1-cp312-cp312-musllinux_1_2_aarch64.whl", hash = "sha256:d275a9e3c81b1093c060c3837e580c37f47c51eca031f7b5fb76f7b8470f5f9b", size = 409485 }, - { url = "https://files.pythonhosted.org/packages/c6/b6/0c398039e4c6d0b2e37c61d7e0e9d13439f91f780686deb8ee64ecf1ae71/msgpack-1.1.1-cp312-cp312-musllinux_1_2_i686.whl", hash = "sha256:4fd6b577e4541676e0cc9ddc1709d25014d3ad9a66caa19962c4f5de30fc09ef", size = 412182 }, - { url = "https://files.pythonhosted.org/packages/b8/d0/0cf4a6ecb9bc960d624c93effaeaae75cbf00b3bc4a54f35c8507273cda1/msgpack-1.1.1-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:bb29aaa613c0a1c40d1af111abf025f1732cab333f96f285d6a93b934738a68a", size = 419883 }, - { url = "https://files.pythonhosted.org/packages/62/83/9697c211720fa71a2dfb632cad6196a8af3abea56eece220fde4674dc44b/msgpack-1.1.1-cp312-cp312-win32.whl", hash = "sha256:870b9a626280c86cff9c576ec0d9cbcc54a1e5ebda9cd26dab12baf41fee218c", size = 65406 }, - { url = "https://files.pythonhosted.org/packages/c0/23/0abb886e80eab08f5e8c485d6f13924028602829f63b8f5fa25a06636628/msgpack-1.1.1-cp312-cp312-win_amd64.whl", hash = "sha256:5692095123007180dca3e788bb4c399cc26626da51629a31d40207cb262e67f4", size = 72558 }, - { url = "https://files.pythonhosted.org/packages/a1/38/561f01cf3577430b59b340b51329803d3a5bf6a45864a55f4ef308ac11e3/msgpack-1.1.1-cp313-cp313-macosx_10_13_x86_64.whl", hash = "sha256:3765afa6bd4832fc11c3749be4ba4b69a0e8d7b728f78e68120a157a4c5d41f0", size = 81677 }, - { url = "https://files.pythonhosted.org/packages/09/48/54a89579ea36b6ae0ee001cba8c61f776451fad3c9306cd80f5b5c55be87/msgpack-1.1.1-cp313-cp313-macosx_11_0_arm64.whl", hash = "sha256:8ddb2bcfd1a8b9e431c8d6f4f7db0773084e107730ecf3472f1dfe9ad583f3d9", size = 78603 }, - { url = "https://files.pythonhosted.org/packages/a0/60/daba2699b308e95ae792cdc2ef092a38eb5ee422f9d2fbd4101526d8a210/msgpack-1.1.1-cp313-cp313-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:196a736f0526a03653d829d7d4c5500a97eea3648aebfd4b6743875f28aa2af8", size = 420504 }, - { url = "https://files.pythonhosted.org/packages/20/22/2ebae7ae43cd8f2debc35c631172ddf14e2a87ffcc04cf43ff9df9fff0d3/msgpack-1.1.1-cp313-cp313-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:9d592d06e3cc2f537ceeeb23d38799c6ad83255289bb84c2e5792e5a8dea268a", size = 423749 }, - { url = "https://files.pythonhosted.org/packages/40/1b/54c08dd5452427e1179a40b4b607e37e2664bca1c790c60c442c8e972e47/msgpack-1.1.1-cp313-cp313-manylinux_2_5_i686.manylinux1_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:4df2311b0ce24f06ba253fda361f938dfecd7b961576f9be3f3fbd60e87130ac", size = 404458 }, - { url = "https://files.pythonhosted.org/packages/2e/60/6bb17e9ffb080616a51f09928fdd5cac1353c9becc6c4a8abd4e57269a16/msgpack-1.1.1-cp313-cp313-musllinux_1_2_aarch64.whl", hash = "sha256:e4141c5a32b5e37905b5940aacbc59739f036930367d7acce7a64e4dec1f5e0b", size = 405976 }, - { url = "https://files.pythonhosted.org/packages/ee/97/88983e266572e8707c1f4b99c8fd04f9eb97b43f2db40e3172d87d8642db/msgpack-1.1.1-cp313-cp313-musllinux_1_2_i686.whl", hash = "sha256:b1ce7f41670c5a69e1389420436f41385b1aa2504c3b0c30620764b15dded2e7", size = 408607 }, - { url = "https://files.pythonhosted.org/packages/bc/66/36c78af2efaffcc15a5a61ae0df53a1d025f2680122e2a9eb8442fed3ae4/msgpack-1.1.1-cp313-cp313-musllinux_1_2_x86_64.whl", hash = "sha256:4147151acabb9caed4e474c3344181e91ff7a388b888f1e19ea04f7e73dc7ad5", size = 424172 }, - { url = "https://files.pythonhosted.org/packages/8c/87/a75eb622b555708fe0427fab96056d39d4c9892b0c784b3a721088c7ee37/msgpack-1.1.1-cp313-cp313-win32.whl", hash = "sha256:500e85823a27d6d9bba1d057c871b4210c1dd6fb01fbb764e37e4e8847376323", size = 65347 }, - { url = "https://files.pythonhosted.org/packages/ca/91/7dc28d5e2a11a5ad804cf2b7f7a5fcb1eb5a4966d66a5d2b41aee6376543/msgpack-1.1.1-cp313-cp313-win_amd64.whl", hash = "sha256:6d489fba546295983abd142812bda76b57e33d0b9f5d5b71c09a583285506f69", size = 72341 }, +sdist = { url = "https://files.pythonhosted.org/packages/45/b1/ea4f68038a18c77c9467400d166d74c4ffa536f34761f7983a104357e614/msgpack-1.1.1.tar.gz", hash = "sha256:77b79ce34a2bdab2594f490c8e80dd62a02d650b91a75159a63ec413b8d104cd", size = 173555, upload-time = "2025-06-13T06:52:51.324Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/33/52/f30da112c1dc92cf64f57d08a273ac771e7b29dea10b4b30369b2d7e8546/msgpack-1.1.1-cp310-cp310-macosx_10_9_x86_64.whl", hash = "sha256:353b6fc0c36fde68b661a12949d7d49f8f51ff5fa019c1e47c87c4ff34b080ed", size = 81799, upload-time = "2025-06-13T06:51:37.228Z" }, + { url = "https://files.pythonhosted.org/packages/e4/35/7bfc0def2f04ab4145f7f108e3563f9b4abae4ab0ed78a61f350518cc4d2/msgpack-1.1.1-cp310-cp310-macosx_11_0_arm64.whl", hash = "sha256:79c408fcf76a958491b4e3b103d1c417044544b68e96d06432a189b43d1215c8", size = 78278, upload-time = "2025-06-13T06:51:38.534Z" }, + { url = "https://files.pythonhosted.org/packages/e8/c5/df5d6c1c39856bc55f800bf82778fd4c11370667f9b9e9d51b2f5da88f20/msgpack-1.1.1-cp310-cp310-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:78426096939c2c7482bf31ef15ca219a9e24460289c00dd0b94411040bb73ad2", size = 402805, upload-time = "2025-06-13T06:51:39.538Z" }, + { url = "https://files.pythonhosted.org/packages/20/8e/0bb8c977efecfe6ea7116e2ed73a78a8d32a947f94d272586cf02a9757db/msgpack-1.1.1-cp310-cp310-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:8b17ba27727a36cb73aabacaa44b13090feb88a01d012c0f4be70c00f75048b4", size = 408642, upload-time = "2025-06-13T06:51:41.092Z" }, + { url = "https://files.pythonhosted.org/packages/59/a1/731d52c1aeec52006be6d1f8027c49fdc2cfc3ab7cbe7c28335b2910d7b6/msgpack-1.1.1-cp310-cp310-manylinux_2_5_i686.manylinux1_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:7a17ac1ea6ec3c7687d70201cfda3b1e8061466f28f686c24f627cae4ea8efd0", size = 395143, upload-time = "2025-06-13T06:51:42.575Z" }, + { url = "https://files.pythonhosted.org/packages/2b/92/b42911c52cda2ba67a6418ffa7d08969edf2e760b09015593c8a8a27a97d/msgpack-1.1.1-cp310-cp310-musllinux_1_2_aarch64.whl", hash = "sha256:88d1e966c9235c1d4e2afac21ca83933ba59537e2e2727a999bf3f515ca2af26", size = 395986, upload-time = "2025-06-13T06:51:43.807Z" }, + { url = "https://files.pythonhosted.org/packages/61/dc/8ae165337e70118d4dab651b8b562dd5066dd1e6dd57b038f32ebc3e2f07/msgpack-1.1.1-cp310-cp310-musllinux_1_2_i686.whl", hash = "sha256:f6d58656842e1b2ddbe07f43f56b10a60f2ba5826164910968f5933e5178af75", size = 402682, upload-time = "2025-06-13T06:51:45.534Z" }, + { url = "https://files.pythonhosted.org/packages/58/27/555851cb98dcbd6ce041df1eacb25ac30646575e9cd125681aa2f4b1b6f1/msgpack-1.1.1-cp310-cp310-musllinux_1_2_x86_64.whl", hash = "sha256:96decdfc4adcbc087f5ea7ebdcfd3dee9a13358cae6e81d54be962efc38f6338", size = 406368, upload-time = "2025-06-13T06:51:46.97Z" }, + { url = "https://files.pythonhosted.org/packages/d4/64/39a26add4ce16f24e99eabb9005e44c663db00e3fce17d4ae1ae9d61df99/msgpack-1.1.1-cp310-cp310-win32.whl", hash = "sha256:6640fd979ca9a212e4bcdf6eb74051ade2c690b862b679bfcb60ae46e6dc4bfd", size = 65004, upload-time = "2025-06-13T06:51:48.582Z" }, + { url = "https://files.pythonhosted.org/packages/7d/18/73dfa3e9d5d7450d39debde5b0d848139f7de23bd637a4506e36c9800fd6/msgpack-1.1.1-cp310-cp310-win_amd64.whl", hash = "sha256:8b65b53204fe1bd037c40c4148d00ef918eb2108d24c9aaa20bc31f9810ce0a8", size = 71548, upload-time = "2025-06-13T06:51:49.558Z" }, + { url = "https://files.pythonhosted.org/packages/7f/83/97f24bf9848af23fe2ba04380388216defc49a8af6da0c28cc636d722502/msgpack-1.1.1-cp311-cp311-macosx_10_9_x86_64.whl", hash = "sha256:71ef05c1726884e44f8b1d1773604ab5d4d17729d8491403a705e649116c9558", size = 82728, upload-time = "2025-06-13T06:51:50.68Z" }, + { url = "https://files.pythonhosted.org/packages/aa/7f/2eaa388267a78401f6e182662b08a588ef4f3de6f0eab1ec09736a7aaa2b/msgpack-1.1.1-cp311-cp311-macosx_11_0_arm64.whl", hash = "sha256:36043272c6aede309d29d56851f8841ba907a1a3d04435e43e8a19928e243c1d", size = 79279, upload-time = "2025-06-13T06:51:51.72Z" }, + { url = "https://files.pythonhosted.org/packages/f8/46/31eb60f4452c96161e4dfd26dbca562b4ec68c72e4ad07d9566d7ea35e8a/msgpack-1.1.1-cp311-cp311-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:a32747b1b39c3ac27d0670122b57e6e57f28eefb725e0b625618d1b59bf9d1e0", size = 423859, upload-time = "2025-06-13T06:51:52.749Z" }, + { url = "https://files.pythonhosted.org/packages/45/16/a20fa8c32825cc7ae8457fab45670c7a8996d7746ce80ce41cc51e3b2bd7/msgpack-1.1.1-cp311-cp311-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:8a8b10fdb84a43e50d38057b06901ec9da52baac6983d3f709d8507f3889d43f", size = 429975, upload-time = "2025-06-13T06:51:53.97Z" }, + { url = "https://files.pythonhosted.org/packages/86/ea/6c958e07692367feeb1a1594d35e22b62f7f476f3c568b002a5ea09d443d/msgpack-1.1.1-cp311-cp311-manylinux_2_5_i686.manylinux1_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:ba0c325c3f485dc54ec298d8b024e134acf07c10d494ffa24373bea729acf704", size = 413528, upload-time = "2025-06-13T06:51:55.507Z" }, + { url = "https://files.pythonhosted.org/packages/75/05/ac84063c5dae79722bda9f68b878dc31fc3059adb8633c79f1e82c2cd946/msgpack-1.1.1-cp311-cp311-musllinux_1_2_aarch64.whl", hash = "sha256:88daaf7d146e48ec71212ce21109b66e06a98e5e44dca47d853cbfe171d6c8d2", size = 413338, upload-time = "2025-06-13T06:51:57.023Z" }, + { url = "https://files.pythonhosted.org/packages/69/e8/fe86b082c781d3e1c09ca0f4dacd457ede60a13119b6ce939efe2ea77b76/msgpack-1.1.1-cp311-cp311-musllinux_1_2_i686.whl", hash = "sha256:d8b55ea20dc59b181d3f47103f113e6f28a5e1c89fd5b67b9140edb442ab67f2", size = 422658, upload-time = "2025-06-13T06:51:58.419Z" }, + { url = "https://files.pythonhosted.org/packages/3b/2b/bafc9924df52d8f3bb7c00d24e57be477f4d0f967c0a31ef5e2225e035c7/msgpack-1.1.1-cp311-cp311-musllinux_1_2_x86_64.whl", hash = "sha256:4a28e8072ae9779f20427af07f53bbb8b4aa81151054e882aee333b158da8752", size = 427124, upload-time = "2025-06-13T06:51:59.969Z" }, + { url = "https://files.pythonhosted.org/packages/a2/3b/1f717e17e53e0ed0b68fa59e9188f3f610c79d7151f0e52ff3cd8eb6b2dc/msgpack-1.1.1-cp311-cp311-win32.whl", hash = "sha256:7da8831f9a0fdb526621ba09a281fadc58ea12701bc709e7b8cbc362feabc295", size = 65016, upload-time = "2025-06-13T06:52:01.294Z" }, + { url = "https://files.pythonhosted.org/packages/48/45/9d1780768d3b249accecc5a38c725eb1e203d44a191f7b7ff1941f7df60c/msgpack-1.1.1-cp311-cp311-win_amd64.whl", hash = "sha256:5fd1b58e1431008a57247d6e7cc4faa41c3607e8e7d4aaf81f7c29ea013cb458", size = 72267, upload-time = "2025-06-13T06:52:02.568Z" }, + { url = "https://files.pythonhosted.org/packages/e3/26/389b9c593eda2b8551b2e7126ad3a06af6f9b44274eb3a4f054d48ff7e47/msgpack-1.1.1-cp312-cp312-macosx_10_13_x86_64.whl", hash = "sha256:ae497b11f4c21558d95de9f64fff7053544f4d1a17731c866143ed6bb4591238", size = 82359, upload-time = "2025-06-13T06:52:03.909Z" }, + { url = "https://files.pythonhosted.org/packages/ab/65/7d1de38c8a22cf8b1551469159d4b6cf49be2126adc2482de50976084d78/msgpack-1.1.1-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:33be9ab121df9b6b461ff91baac6f2731f83d9b27ed948c5b9d1978ae28bf157", size = 79172, upload-time = "2025-06-13T06:52:05.246Z" }, + { url = "https://files.pythonhosted.org/packages/0f/bd/cacf208b64d9577a62c74b677e1ada005caa9b69a05a599889d6fc2ab20a/msgpack-1.1.1-cp312-cp312-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:6f64ae8fe7ffba251fecb8408540c34ee9df1c26674c50c4544d72dbf792e5ce", size = 425013, upload-time = "2025-06-13T06:52:06.341Z" }, + { url = "https://files.pythonhosted.org/packages/4d/ec/fd869e2567cc9c01278a736cfd1697941ba0d4b81a43e0aa2e8d71dab208/msgpack-1.1.1-cp312-cp312-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:a494554874691720ba5891c9b0b39474ba43ffb1aaf32a5dac874effb1619e1a", size = 426905, upload-time = "2025-06-13T06:52:07.501Z" }, + { url = "https://files.pythonhosted.org/packages/55/2a/35860f33229075bce803a5593d046d8b489d7ba2fc85701e714fc1aaf898/msgpack-1.1.1-cp312-cp312-manylinux_2_5_i686.manylinux1_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:cb643284ab0ed26f6957d969fe0dd8bb17beb567beb8998140b5e38a90974f6c", size = 407336, upload-time = "2025-06-13T06:52:09.047Z" }, + { url = "https://files.pythonhosted.org/packages/8c/16/69ed8f3ada150bf92745fb4921bd621fd2cdf5a42e25eb50bcc57a5328f0/msgpack-1.1.1-cp312-cp312-musllinux_1_2_aarch64.whl", hash = "sha256:d275a9e3c81b1093c060c3837e580c37f47c51eca031f7b5fb76f7b8470f5f9b", size = 409485, upload-time = "2025-06-13T06:52:10.382Z" }, + { url = "https://files.pythonhosted.org/packages/c6/b6/0c398039e4c6d0b2e37c61d7e0e9d13439f91f780686deb8ee64ecf1ae71/msgpack-1.1.1-cp312-cp312-musllinux_1_2_i686.whl", hash = "sha256:4fd6b577e4541676e0cc9ddc1709d25014d3ad9a66caa19962c4f5de30fc09ef", size = 412182, upload-time = "2025-06-13T06:52:11.644Z" }, + { url = "https://files.pythonhosted.org/packages/b8/d0/0cf4a6ecb9bc960d624c93effaeaae75cbf00b3bc4a54f35c8507273cda1/msgpack-1.1.1-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:bb29aaa613c0a1c40d1af111abf025f1732cab333f96f285d6a93b934738a68a", size = 419883, upload-time = "2025-06-13T06:52:12.806Z" }, + { url = "https://files.pythonhosted.org/packages/62/83/9697c211720fa71a2dfb632cad6196a8af3abea56eece220fde4674dc44b/msgpack-1.1.1-cp312-cp312-win32.whl", hash = "sha256:870b9a626280c86cff9c576ec0d9cbcc54a1e5ebda9cd26dab12baf41fee218c", size = 65406, upload-time = "2025-06-13T06:52:14.271Z" }, + { url = "https://files.pythonhosted.org/packages/c0/23/0abb886e80eab08f5e8c485d6f13924028602829f63b8f5fa25a06636628/msgpack-1.1.1-cp312-cp312-win_amd64.whl", hash = "sha256:5692095123007180dca3e788bb4c399cc26626da51629a31d40207cb262e67f4", size = 72558, upload-time = "2025-06-13T06:52:15.252Z" }, + { url = "https://files.pythonhosted.org/packages/a1/38/561f01cf3577430b59b340b51329803d3a5bf6a45864a55f4ef308ac11e3/msgpack-1.1.1-cp313-cp313-macosx_10_13_x86_64.whl", hash = "sha256:3765afa6bd4832fc11c3749be4ba4b69a0e8d7b728f78e68120a157a4c5d41f0", size = 81677, upload-time = "2025-06-13T06:52:16.64Z" }, + { url = "https://files.pythonhosted.org/packages/09/48/54a89579ea36b6ae0ee001cba8c61f776451fad3c9306cd80f5b5c55be87/msgpack-1.1.1-cp313-cp313-macosx_11_0_arm64.whl", hash = "sha256:8ddb2bcfd1a8b9e431c8d6f4f7db0773084e107730ecf3472f1dfe9ad583f3d9", size = 78603, upload-time = "2025-06-13T06:52:17.843Z" }, + { url = "https://files.pythonhosted.org/packages/a0/60/daba2699b308e95ae792cdc2ef092a38eb5ee422f9d2fbd4101526d8a210/msgpack-1.1.1-cp313-cp313-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:196a736f0526a03653d829d7d4c5500a97eea3648aebfd4b6743875f28aa2af8", size = 420504, upload-time = "2025-06-13T06:52:18.982Z" }, + { url = "https://files.pythonhosted.org/packages/20/22/2ebae7ae43cd8f2debc35c631172ddf14e2a87ffcc04cf43ff9df9fff0d3/msgpack-1.1.1-cp313-cp313-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:9d592d06e3cc2f537ceeeb23d38799c6ad83255289bb84c2e5792e5a8dea268a", size = 423749, upload-time = "2025-06-13T06:52:20.211Z" }, + { url = "https://files.pythonhosted.org/packages/40/1b/54c08dd5452427e1179a40b4b607e37e2664bca1c790c60c442c8e972e47/msgpack-1.1.1-cp313-cp313-manylinux_2_5_i686.manylinux1_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:4df2311b0ce24f06ba253fda361f938dfecd7b961576f9be3f3fbd60e87130ac", size = 404458, upload-time = "2025-06-13T06:52:21.429Z" }, + { url = "https://files.pythonhosted.org/packages/2e/60/6bb17e9ffb080616a51f09928fdd5cac1353c9becc6c4a8abd4e57269a16/msgpack-1.1.1-cp313-cp313-musllinux_1_2_aarch64.whl", hash = "sha256:e4141c5a32b5e37905b5940aacbc59739f036930367d7acce7a64e4dec1f5e0b", size = 405976, upload-time = "2025-06-13T06:52:22.995Z" }, + { url = "https://files.pythonhosted.org/packages/ee/97/88983e266572e8707c1f4b99c8fd04f9eb97b43f2db40e3172d87d8642db/msgpack-1.1.1-cp313-cp313-musllinux_1_2_i686.whl", hash = "sha256:b1ce7f41670c5a69e1389420436f41385b1aa2504c3b0c30620764b15dded2e7", size = 408607, upload-time = "2025-06-13T06:52:24.152Z" }, + { url = "https://files.pythonhosted.org/packages/bc/66/36c78af2efaffcc15a5a61ae0df53a1d025f2680122e2a9eb8442fed3ae4/msgpack-1.1.1-cp313-cp313-musllinux_1_2_x86_64.whl", hash = "sha256:4147151acabb9caed4e474c3344181e91ff7a388b888f1e19ea04f7e73dc7ad5", size = 424172, upload-time = "2025-06-13T06:52:25.704Z" }, + { url = "https://files.pythonhosted.org/packages/8c/87/a75eb622b555708fe0427fab96056d39d4c9892b0c784b3a721088c7ee37/msgpack-1.1.1-cp313-cp313-win32.whl", hash = "sha256:500e85823a27d6d9bba1d057c871b4210c1dd6fb01fbb764e37e4e8847376323", size = 65347, upload-time = "2025-06-13T06:52:26.846Z" }, + { url = "https://files.pythonhosted.org/packages/ca/91/7dc28d5e2a11a5ad804cf2b7f7a5fcb1eb5a4966d66a5d2b41aee6376543/msgpack-1.1.1-cp313-cp313-win_amd64.whl", hash = "sha256:6d489fba546295983abd142812bda76b57e33d0b9f5d5b71c09a583285506f69", size = 72341, upload-time = "2025-06-13T06:52:27.835Z" }, ] [[package]] name = "mypy" -version = "1.16.1" +version = "1.18.2" source = { registry = "https://pypi.org/simple" } dependencies = [ { name = "mypy-extensions" }, @@ -843,60 +1014,66 @@ dependencies = [ { name = "tomli", marker = "python_full_version < '3.11'" }, { name = "typing-extensions" }, ] -sdist = { url = "https://files.pythonhosted.org/packages/81/69/92c7fa98112e4d9eb075a239caa4ef4649ad7d441545ccffbd5e34607cbb/mypy-1.16.1.tar.gz", hash = "sha256:6bd00a0a2094841c5e47e7374bb42b83d64c527a502e3334e1173a0c24437bab", size = 3324747 } -wheels = [ - { url = "https://files.pythonhosted.org/packages/8e/12/2bf23a80fcef5edb75de9a1e295d778e0f46ea89eb8b115818b663eff42b/mypy-1.16.1-cp310-cp310-macosx_10_9_x86_64.whl", hash = "sha256:b4f0fed1022a63c6fec38f28b7fc77fca47fd490445c69d0a66266c59dd0b88a", size = 10958644 }, - { url = "https://files.pythonhosted.org/packages/08/50/bfe47b3b278eacf348291742fd5e6613bbc4b3434b72ce9361896417cfe5/mypy-1.16.1-cp310-cp310-macosx_11_0_arm64.whl", hash = "sha256:86042bbf9f5a05ea000d3203cf87aa9d0ccf9a01f73f71c58979eb9249f46d72", size = 10087033 }, - { url = "https://files.pythonhosted.org/packages/21/de/40307c12fe25675a0776aaa2cdd2879cf30d99eec91b898de00228dc3ab5/mypy-1.16.1-cp310-cp310-manylinux_2_17_aarch64.manylinux2014_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:ea7469ee5902c95542bea7ee545f7006508c65c8c54b06dc2c92676ce526f3ea", size = 11875645 }, - { url = "https://files.pythonhosted.org/packages/a6/d8/85bdb59e4a98b7a31495bd8f1a4445d8ffc86cde4ab1f8c11d247c11aedc/mypy-1.16.1-cp310-cp310-manylinux_2_17_x86_64.manylinux2014_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:352025753ef6a83cb9e7f2427319bb7875d1fdda8439d1e23de12ab164179574", size = 12616986 }, - { url = "https://files.pythonhosted.org/packages/0e/d0/bb25731158fa8f8ee9e068d3e94fcceb4971fedf1424248496292512afe9/mypy-1.16.1-cp310-cp310-musllinux_1_2_x86_64.whl", hash = "sha256:ff9fa5b16e4c1364eb89a4d16bcda9987f05d39604e1e6c35378a2987c1aac2d", size = 12878632 }, - { url = "https://files.pythonhosted.org/packages/2d/11/822a9beb7a2b825c0cb06132ca0a5183f8327a5e23ef89717c9474ba0bc6/mypy-1.16.1-cp310-cp310-win_amd64.whl", hash = "sha256:1256688e284632382f8f3b9e2123df7d279f603c561f099758e66dd6ed4e8bd6", size = 9484391 }, - { url = "https://files.pythonhosted.org/packages/9a/61/ec1245aa1c325cb7a6c0f8570a2eee3bfc40fa90d19b1267f8e50b5c8645/mypy-1.16.1-cp311-cp311-macosx_10_9_x86_64.whl", hash = "sha256:472e4e4c100062488ec643f6162dd0d5208e33e2f34544e1fc931372e806c0cc", size = 10890557 }, - { url = "https://files.pythonhosted.org/packages/6b/bb/6eccc0ba0aa0c7a87df24e73f0ad34170514abd8162eb0c75fd7128171fb/mypy-1.16.1-cp311-cp311-macosx_11_0_arm64.whl", hash = "sha256:ea16e2a7d2714277e349e24d19a782a663a34ed60864006e8585db08f8ad1782", size = 10012921 }, - { url = "https://files.pythonhosted.org/packages/5f/80/b337a12e2006715f99f529e732c5f6a8c143bb58c92bb142d5ab380963a5/mypy-1.16.1-cp311-cp311-manylinux_2_17_aarch64.manylinux2014_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:08e850ea22adc4d8a4014651575567b0318ede51e8e9fe7a68f25391af699507", size = 11802887 }, - { url = "https://files.pythonhosted.org/packages/d9/59/f7af072d09793d581a745a25737c7c0a945760036b16aeb620f658a017af/mypy-1.16.1-cp311-cp311-manylinux_2_17_x86_64.manylinux2014_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:22d76a63a42619bfb90122889b903519149879ddbf2ba4251834727944c8baca", size = 12531658 }, - { url = "https://files.pythonhosted.org/packages/82/c4/607672f2d6c0254b94a646cfc45ad589dd71b04aa1f3d642b840f7cce06c/mypy-1.16.1-cp311-cp311-musllinux_1_2_x86_64.whl", hash = "sha256:2c7ce0662b6b9dc8f4ed86eb7a5d505ee3298c04b40ec13b30e572c0e5ae17c4", size = 12732486 }, - { url = "https://files.pythonhosted.org/packages/b6/5e/136555ec1d80df877a707cebf9081bd3a9f397dedc1ab9750518d87489ec/mypy-1.16.1-cp311-cp311-win_amd64.whl", hash = "sha256:211287e98e05352a2e1d4e8759c5490925a7c784ddc84207f4714822f8cf99b6", size = 9479482 }, - { url = "https://files.pythonhosted.org/packages/b4/d6/39482e5fcc724c15bf6280ff5806548c7185e0c090712a3736ed4d07e8b7/mypy-1.16.1-cp312-cp312-macosx_10_13_x86_64.whl", hash = "sha256:af4792433f09575d9eeca5c63d7d90ca4aeceda9d8355e136f80f8967639183d", size = 11066493 }, - { url = "https://files.pythonhosted.org/packages/e6/e5/26c347890efc6b757f4d5bb83f4a0cf5958b8cf49c938ac99b8b72b420a6/mypy-1.16.1-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:66df38405fd8466ce3517eda1f6640611a0b8e70895e2a9462d1d4323c5eb4b9", size = 10081687 }, - { url = "https://files.pythonhosted.org/packages/44/c7/b5cb264c97b86914487d6a24bd8688c0172e37ec0f43e93b9691cae9468b/mypy-1.16.1-cp312-cp312-manylinux_2_17_aarch64.manylinux2014_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:44e7acddb3c48bd2713994d098729494117803616e116032af192871aed80b79", size = 11839723 }, - { url = "https://files.pythonhosted.org/packages/15/f8/491997a9b8a554204f834ed4816bda813aefda31cf873bb099deee3c9a99/mypy-1.16.1-cp312-cp312-manylinux_2_17_x86_64.manylinux2014_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:0ab5eca37b50188163fa7c1b73c685ac66c4e9bdee4a85c9adac0e91d8895e15", size = 12722980 }, - { url = "https://files.pythonhosted.org/packages/df/f0/2bd41e174b5fd93bc9de9a28e4fb673113633b8a7f3a607fa4a73595e468/mypy-1.16.1-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:dedb6229b2c9086247e21a83c309754b9058b438704ad2f6807f0d8227f6ebdd", size = 12903328 }, - { url = "https://files.pythonhosted.org/packages/61/81/5572108a7bec2c46b8aff7e9b524f371fe6ab5efb534d38d6b37b5490da8/mypy-1.16.1-cp312-cp312-win_amd64.whl", hash = "sha256:1f0435cf920e287ff68af3d10a118a73f212deb2ce087619eb4e648116d1fe9b", size = 9562321 }, - { url = "https://files.pythonhosted.org/packages/28/e3/96964af4a75a949e67df4b95318fe2b7427ac8189bbc3ef28f92a1c5bc56/mypy-1.16.1-cp313-cp313-macosx_10_13_x86_64.whl", hash = "sha256:ddc91eb318c8751c69ddb200a5937f1232ee8efb4e64e9f4bc475a33719de438", size = 11063480 }, - { url = "https://files.pythonhosted.org/packages/f5/4d/cd1a42b8e5be278fab7010fb289d9307a63e07153f0ae1510a3d7b703193/mypy-1.16.1-cp313-cp313-macosx_11_0_arm64.whl", hash = "sha256:87ff2c13d58bdc4bbe7dc0dedfe622c0f04e2cb2a492269f3b418df2de05c536", size = 10090538 }, - { url = "https://files.pythonhosted.org/packages/c9/4f/c3c6b4b66374b5f68bab07c8cabd63a049ff69796b844bc759a0ca99bb2a/mypy-1.16.1-cp313-cp313-manylinux_2_17_aarch64.manylinux2014_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:0a7cfb0fe29fe5a9841b7c8ee6dffb52382c45acdf68f032145b75620acfbd6f", size = 11836839 }, - { url = "https://files.pythonhosted.org/packages/b4/7e/81ca3b074021ad9775e5cb97ebe0089c0f13684b066a750b7dc208438403/mypy-1.16.1-cp313-cp313-manylinux_2_17_x86_64.manylinux2014_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:051e1677689c9d9578b9c7f4d206d763f9bbd95723cd1416fad50db49d52f359", size = 12715634 }, - { url = "https://files.pythonhosted.org/packages/e9/95/bdd40c8be346fa4c70edb4081d727a54d0a05382d84966869738cfa8a497/mypy-1.16.1-cp313-cp313-musllinux_1_2_x86_64.whl", hash = "sha256:d5d2309511cc56c021b4b4e462907c2b12f669b2dbeb68300110ec27723971be", size = 12895584 }, - { url = "https://files.pythonhosted.org/packages/5a/fd/d486a0827a1c597b3b48b1bdef47228a6e9ee8102ab8c28f944cb83b65dc/mypy-1.16.1-cp313-cp313-win_amd64.whl", hash = "sha256:4f58ac32771341e38a853c5d0ec0dfe27e18e27da9cdb8bbc882d2249c71a3ee", size = 9573886 }, - { url = "https://files.pythonhosted.org/packages/cf/d3/53e684e78e07c1a2bf7105715e5edd09ce951fc3f47cf9ed095ec1b7a037/mypy-1.16.1-py3-none-any.whl", hash = "sha256:5fc2ac4027d0ef28d6ba69a0343737a23c4d1b83672bf38d1fe237bdc0643b37", size = 2265923 }, +sdist = { url = "https://files.pythonhosted.org/packages/c0/77/8f0d0001ffad290cef2f7f216f96c814866248a0b92a722365ed54648e7e/mypy-1.18.2.tar.gz", hash = "sha256:06a398102a5f203d7477b2923dda3634c36727fa5c237d8f859ef90c42a9924b", size = 3448846, upload-time = "2025-09-19T00:11:10.519Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/03/6f/657961a0743cff32e6c0611b63ff1c1970a0b482ace35b069203bf705187/mypy-1.18.2-cp310-cp310-macosx_10_9_x86_64.whl", hash = "sha256:c1eab0cf6294dafe397c261a75f96dc2c31bffe3b944faa24db5def4e2b0f77c", size = 12807973, upload-time = "2025-09-19T00:10:35.282Z" }, + { url = "https://files.pythonhosted.org/packages/10/e9/420822d4f661f13ca8900f5fa239b40ee3be8b62b32f3357df9a3045a08b/mypy-1.18.2-cp310-cp310-macosx_11_0_arm64.whl", hash = "sha256:7a780ca61fc239e4865968ebc5240bb3bf610ef59ac398de9a7421b54e4a207e", size = 11896527, upload-time = "2025-09-19T00:10:55.791Z" }, + { url = "https://files.pythonhosted.org/packages/aa/73/a05b2bbaa7005f4642fcfe40fb73f2b4fb6bb44229bd585b5878e9a87ef8/mypy-1.18.2-cp310-cp310-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:448acd386266989ef11662ce3c8011fd2a7b632e0ec7d61a98edd8e27472225b", size = 12507004, upload-time = "2025-09-19T00:11:05.411Z" }, + { url = "https://files.pythonhosted.org/packages/4f/01/f6e4b9f0d031c11ccbd6f17da26564f3a0f3c4155af344006434b0a05a9d/mypy-1.18.2-cp310-cp310-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:f9e171c465ad3901dc652643ee4bffa8e9fef4d7d0eece23b428908c77a76a66", size = 13245947, upload-time = "2025-09-19T00:10:46.923Z" }, + { url = "https://files.pythonhosted.org/packages/d7/97/19727e7499bfa1ae0773d06afd30ac66a58ed7437d940c70548634b24185/mypy-1.18.2-cp310-cp310-musllinux_1_2_x86_64.whl", hash = "sha256:592ec214750bc00741af1f80cbf96b5013d81486b7bb24cb052382c19e40b428", size = 13499217, upload-time = "2025-09-19T00:09:39.472Z" }, + { url = "https://files.pythonhosted.org/packages/9f/4f/90dc8c15c1441bf31cf0f9918bb077e452618708199e530f4cbd5cede6ff/mypy-1.18.2-cp310-cp310-win_amd64.whl", hash = "sha256:7fb95f97199ea11769ebe3638c29b550b5221e997c63b14ef93d2e971606ebed", size = 9766753, upload-time = "2025-09-19T00:10:49.161Z" }, + { url = "https://files.pythonhosted.org/packages/88/87/cafd3ae563f88f94eec33f35ff722d043e09832ea8530ef149ec1efbaf08/mypy-1.18.2-cp311-cp311-macosx_10_9_x86_64.whl", hash = "sha256:807d9315ab9d464125aa9fcf6d84fde6e1dc67da0b6f80e7405506b8ac72bc7f", size = 12731198, upload-time = "2025-09-19T00:09:44.857Z" }, + { url = "https://files.pythonhosted.org/packages/0f/e0/1e96c3d4266a06d4b0197ace5356d67d937d8358e2ee3ffac71faa843724/mypy-1.18.2-cp311-cp311-macosx_11_0_arm64.whl", hash = "sha256:776bb00de1778caf4db739c6e83919c1d85a448f71979b6a0edd774ea8399341", size = 11817879, upload-time = "2025-09-19T00:09:47.131Z" }, + { url = "https://files.pythonhosted.org/packages/72/ef/0c9ba89eb03453e76bdac5a78b08260a848c7bfc5d6603634774d9cd9525/mypy-1.18.2-cp311-cp311-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:1379451880512ffce14505493bd9fe469e0697543717298242574882cf8cdb8d", size = 12427292, upload-time = "2025-09-19T00:10:22.472Z" }, + { url = "https://files.pythonhosted.org/packages/1a/52/ec4a061dd599eb8179d5411d99775bec2a20542505988f40fc2fee781068/mypy-1.18.2-cp311-cp311-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:1331eb7fd110d60c24999893320967594ff84c38ac6d19e0a76c5fd809a84c86", size = 13163750, upload-time = "2025-09-19T00:09:51.472Z" }, + { url = "https://files.pythonhosted.org/packages/c4/5f/2cf2ceb3b36372d51568f2208c021870fe7834cf3186b653ac6446511839/mypy-1.18.2-cp311-cp311-musllinux_1_2_x86_64.whl", hash = "sha256:3ca30b50a51e7ba93b00422e486cbb124f1c56a535e20eff7b2d6ab72b3b2e37", size = 13351827, upload-time = "2025-09-19T00:09:58.311Z" }, + { url = "https://files.pythonhosted.org/packages/c8/7d/2697b930179e7277529eaaec1513f8de622818696857f689e4a5432e5e27/mypy-1.18.2-cp311-cp311-win_amd64.whl", hash = "sha256:664dc726e67fa54e14536f6e1224bcfce1d9e5ac02426d2326e2bb4e081d1ce8", size = 9757983, upload-time = "2025-09-19T00:10:09.071Z" }, + { url = "https://files.pythonhosted.org/packages/07/06/dfdd2bc60c66611dd8335f463818514733bc763e4760dee289dcc33df709/mypy-1.18.2-cp312-cp312-macosx_10_13_x86_64.whl", hash = "sha256:33eca32dd124b29400c31d7cf784e795b050ace0e1f91b8dc035672725617e34", size = 12908273, upload-time = "2025-09-19T00:10:58.321Z" }, + { url = "https://files.pythonhosted.org/packages/81/14/6a9de6d13a122d5608e1a04130724caf9170333ac5a924e10f670687d3eb/mypy-1.18.2-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:a3c47adf30d65e89b2dcd2fa32f3aeb5e94ca970d2c15fcb25e297871c8e4764", size = 11920910, upload-time = "2025-09-19T00:10:20.043Z" }, + { url = "https://files.pythonhosted.org/packages/5f/a9/b29de53e42f18e8cc547e38daa9dfa132ffdc64f7250e353f5c8cdd44bee/mypy-1.18.2-cp312-cp312-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:5d6c838e831a062f5f29d11c9057c6009f60cb294fea33a98422688181fe2893", size = 12465585, upload-time = "2025-09-19T00:10:33.005Z" }, + { url = "https://files.pythonhosted.org/packages/77/ae/6c3d2c7c61ff21f2bee938c917616c92ebf852f015fb55917fd6e2811db2/mypy-1.18.2-cp312-cp312-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:01199871b6110a2ce984bde85acd481232d17413868c9807e95c1b0739a58914", size = 13348562, upload-time = "2025-09-19T00:10:11.51Z" }, + { url = "https://files.pythonhosted.org/packages/4d/31/aec68ab3b4aebdf8f36d191b0685d99faa899ab990753ca0fee60fb99511/mypy-1.18.2-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:a2afc0fa0b0e91b4599ddfe0f91e2c26c2b5a5ab263737e998d6817874c5f7c8", size = 13533296, upload-time = "2025-09-19T00:10:06.568Z" }, + { url = "https://files.pythonhosted.org/packages/9f/83/abcb3ad9478fca3ebeb6a5358bb0b22c95ea42b43b7789c7fb1297ca44f4/mypy-1.18.2-cp312-cp312-win_amd64.whl", hash = "sha256:d8068d0afe682c7c4897c0f7ce84ea77f6de953262b12d07038f4d296d547074", size = 9828828, upload-time = "2025-09-19T00:10:28.203Z" }, + { url = "https://files.pythonhosted.org/packages/5f/04/7f462e6fbba87a72bc8097b93f6842499c428a6ff0c81dd46948d175afe8/mypy-1.18.2-cp313-cp313-macosx_10_13_x86_64.whl", hash = "sha256:07b8b0f580ca6d289e69209ec9d3911b4a26e5abfde32228a288eb79df129fcc", size = 12898728, upload-time = "2025-09-19T00:10:01.33Z" }, + { url = "https://files.pythonhosted.org/packages/99/5b/61ed4efb64f1871b41fd0b82d29a64640f3516078f6c7905b68ab1ad8b13/mypy-1.18.2-cp313-cp313-macosx_11_0_arm64.whl", hash = "sha256:ed4482847168439651d3feee5833ccedbf6657e964572706a2adb1f7fa4dfe2e", size = 11910758, upload-time = "2025-09-19T00:10:42.607Z" }, + { url = "https://files.pythonhosted.org/packages/3c/46/d297d4b683cc89a6e4108c4250a6a6b717f5fa96e1a30a7944a6da44da35/mypy-1.18.2-cp313-cp313-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:c3ad2afadd1e9fea5cf99a45a822346971ede8685cc581ed9cd4d42eaf940986", size = 12475342, upload-time = "2025-09-19T00:11:00.371Z" }, + { url = "https://files.pythonhosted.org/packages/83/45/4798f4d00df13eae3bfdf726c9244bcb495ab5bd588c0eed93a2f2dd67f3/mypy-1.18.2-cp313-cp313-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:a431a6f1ef14cf8c144c6b14793a23ec4eae3db28277c358136e79d7d062f62d", size = 13338709, upload-time = "2025-09-19T00:11:03.358Z" }, + { url = "https://files.pythonhosted.org/packages/d7/09/479f7358d9625172521a87a9271ddd2441e1dab16a09708f056e97007207/mypy-1.18.2-cp313-cp313-musllinux_1_2_x86_64.whl", hash = "sha256:7ab28cc197f1dd77a67e1c6f35cd1f8e8b73ed2217e4fc005f9e6a504e46e7ba", size = 13529806, upload-time = "2025-09-19T00:10:26.073Z" }, + { url = "https://files.pythonhosted.org/packages/71/cf/ac0f2c7e9d0ea3c75cd99dff7aec1c9df4a1376537cb90e4c882267ee7e9/mypy-1.18.2-cp313-cp313-win_amd64.whl", hash = "sha256:0e2785a84b34a72ba55fb5daf079a1003a34c05b22238da94fcae2bbe46f3544", size = 9833262, upload-time = "2025-09-19T00:10:40.035Z" }, + { url = "https://files.pythonhosted.org/packages/5a/0c/7d5300883da16f0063ae53996358758b2a2df2a09c72a5061fa79a1f5006/mypy-1.18.2-cp314-cp314-macosx_10_13_x86_64.whl", hash = "sha256:62f0e1e988ad41c2a110edde6c398383a889d95b36b3e60bcf155f5164c4fdce", size = 12893775, upload-time = "2025-09-19T00:10:03.814Z" }, + { url = "https://files.pythonhosted.org/packages/50/df/2cffbf25737bdb236f60c973edf62e3e7b4ee1c25b6878629e88e2cde967/mypy-1.18.2-cp314-cp314-macosx_11_0_arm64.whl", hash = "sha256:8795a039bab805ff0c1dfdb8cd3344642c2b99b8e439d057aba30850b8d3423d", size = 11936852, upload-time = "2025-09-19T00:10:51.631Z" }, + { url = "https://files.pythonhosted.org/packages/be/50/34059de13dd269227fb4a03be1faee6e2a4b04a2051c82ac0a0b5a773c9a/mypy-1.18.2-cp314-cp314-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:6ca1e64b24a700ab5ce10133f7ccd956a04715463d30498e64ea8715236f9c9c", size = 12480242, upload-time = "2025-09-19T00:11:07.955Z" }, + { url = "https://files.pythonhosted.org/packages/5b/11/040983fad5132d85914c874a2836252bbc57832065548885b5bb5b0d4359/mypy-1.18.2-cp314-cp314-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:d924eef3795cc89fecf6bedc6ed32b33ac13e8321344f6ddbf8ee89f706c05cb", size = 13326683, upload-time = "2025-09-19T00:09:55.572Z" }, + { url = "https://files.pythonhosted.org/packages/e9/ba/89b2901dd77414dd7a8c8729985832a5735053be15b744c18e4586e506ef/mypy-1.18.2-cp314-cp314-musllinux_1_2_x86_64.whl", hash = "sha256:20c02215a080e3a2be3aa50506c67242df1c151eaba0dcbc1e4e557922a26075", size = 13514749, upload-time = "2025-09-19T00:10:44.827Z" }, + { url = "https://files.pythonhosted.org/packages/25/bc/cc98767cffd6b2928ba680f3e5bc969c4152bf7c2d83f92f5a504b92b0eb/mypy-1.18.2-cp314-cp314-win_amd64.whl", hash = "sha256:749b5f83198f1ca64345603118a6f01a4e99ad4bf9d103ddc5a3200cc4614adf", size = 9982959, upload-time = "2025-09-19T00:10:37.344Z" }, + { url = "https://files.pythonhosted.org/packages/87/e3/be76d87158ebafa0309946c4a73831974d4d6ab4f4ef40c3b53a385a66fd/mypy-1.18.2-py3-none-any.whl", hash = "sha256:22a1748707dd62b58d2ae53562ffc4d7f8bcc727e8ac7cbc69c053ddc874d47e", size = 2352367, upload-time = "2025-09-19T00:10:15.489Z" }, ] [[package]] name = "mypy-extensions" version = "1.1.0" source = { registry = "https://pypi.org/simple" } -sdist = { url = "https://files.pythonhosted.org/packages/a2/6e/371856a3fb9d31ca8dac321cda606860fa4548858c0cc45d9d1d4ca2628b/mypy_extensions-1.1.0.tar.gz", hash = "sha256:52e68efc3284861e772bbcd66823fde5ae21fd2fdb51c62a211403730b916558", size = 6343 } +sdist = { url = "https://files.pythonhosted.org/packages/a2/6e/371856a3fb9d31ca8dac321cda606860fa4548858c0cc45d9d1d4ca2628b/mypy_extensions-1.1.0.tar.gz", hash = "sha256:52e68efc3284861e772bbcd66823fde5ae21fd2fdb51c62a211403730b916558", size = 6343, upload-time = "2025-04-22T14:54:24.164Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/79/7b/2c79738432f5c924bef5071f933bcc9efd0473bac3b4aa584a6f7c1c8df8/mypy_extensions-1.1.0-py3-none-any.whl", hash = "sha256:1be4cccdb0f2482337c4743e60421de3a356cd97508abadd57d47403e94f5505", size = 4963 }, + { url = "https://files.pythonhosted.org/packages/79/7b/2c79738432f5c924bef5071f933bcc9efd0473bac3b4aa584a6f7c1c8df8/mypy_extensions-1.1.0-py3-none-any.whl", hash = "sha256:1be4cccdb0f2482337c4743e60421de3a356cd97508abadd57d47403e94f5505", size = 4963, upload-time = "2025-04-22T14:54:22.983Z" }, ] [[package]] name = "nest-asyncio" version = "1.6.0" source = { registry = "https://pypi.org/simple" } -sdist = { url = "https://files.pythonhosted.org/packages/83/f8/51569ac65d696c8ecbee95938f89d4abf00f47d58d48f6fbabfe8f0baefe/nest_asyncio-1.6.0.tar.gz", hash = "sha256:6f172d5449aca15afd6c646851f4e31e02c598d553a667e38cafa997cfec55fe", size = 7418 } +sdist = { url = "https://files.pythonhosted.org/packages/83/f8/51569ac65d696c8ecbee95938f89d4abf00f47d58d48f6fbabfe8f0baefe/nest_asyncio-1.6.0.tar.gz", hash = "sha256:6f172d5449aca15afd6c646851f4e31e02c598d553a667e38cafa997cfec55fe", size = 7418, upload-time = "2024-01-21T14:25:19.227Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/a0/c4/c2971a3ba4c6103a3d10c4b0f24f461ddc027f0f09763220cf35ca1401b3/nest_asyncio-1.6.0-py3-none-any.whl", hash = "sha256:87af6efd6b5e897c81050477ef65c62e2b2f35d51703cae01aff2905b1852e1c", size = 5195 }, + { url = "https://files.pythonhosted.org/packages/a0/c4/c2971a3ba4c6103a3d10c4b0f24f461ddc027f0f09763220cf35ca1401b3/nest_asyncio-1.6.0-py3-none-any.whl", hash = "sha256:87af6efd6b5e897c81050477ef65c62e2b2f35d51703cae01aff2905b1852e1c", size = 5195, upload-time = "2024-01-21T14:25:17.223Z" }, ] [[package]] name = "nodeenv" version = "1.9.1" source = { registry = "https://pypi.org/simple" } -sdist = { url = "https://files.pythonhosted.org/packages/43/16/fc88b08840de0e0a72a2f9d8c6bae36be573e475a6326ae854bcc549fc45/nodeenv-1.9.1.tar.gz", hash = "sha256:6ec12890a2dab7946721edbfbcd91f3319c6ccc9aec47be7c7e6b7011ee6645f", size = 47437 } +sdist = { url = "https://files.pythonhosted.org/packages/43/16/fc88b08840de0e0a72a2f9d8c6bae36be573e475a6326ae854bcc549fc45/nodeenv-1.9.1.tar.gz", hash = "sha256:6ec12890a2dab7946721edbfbcd91f3319c6ccc9aec47be7c7e6b7011ee6645f", size = 47437, upload-time = "2024-06-04T18:44:11.171Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/d2/1d/1b658dbd2b9fa9c4c9f32accbfc0205d532c8c6194dc0f2a4c0428e7128a/nodeenv-1.9.1-py2.py3-none-any.whl", hash = "sha256:ba11c9782d29c27c70ffbdda2d7415098754709be8a7056d79a737cd901155c9", size = 22314 }, + { url = "https://files.pythonhosted.org/packages/d2/1d/1b658dbd2b9fa9c4c9f32accbfc0205d532c8c6194dc0f2a4c0428e7128a/nodeenv-1.9.1-py2.py3-none-any.whl", hash = "sha256:ba11c9782d29c27c70ffbdda2d7415098754709be8a7056d79a737cd901155c9", size = 22314, upload-time = "2024-06-04T18:44:08.352Z" }, ] [[package]] @@ -906,225 +1083,253 @@ source = { registry = "https://pypi.org/simple" } resolution-markers = [ "python_full_version < '3.11'", ] -sdist = { url = "https://files.pythonhosted.org/packages/76/21/7d2a95e4bba9dc13d043ee156a356c0a8f0c6309dff6b21b4d71a073b8a8/numpy-2.2.6.tar.gz", hash = "sha256:e29554e2bef54a90aa5cc07da6ce955accb83f21ab5de01a62c8478897b264fd", size = 20276440 } -wheels = [ - { url = "https://files.pythonhosted.org/packages/9a/3e/ed6db5be21ce87955c0cbd3009f2803f59fa08df21b5df06862e2d8e2bdd/numpy-2.2.6-cp310-cp310-macosx_10_9_x86_64.whl", hash = "sha256:b412caa66f72040e6d268491a59f2c43bf03eb6c96dd8f0307829feb7fa2b6fb", size = 21165245 }, - { url = "https://files.pythonhosted.org/packages/22/c2/4b9221495b2a132cc9d2eb862e21d42a009f5a60e45fc44b00118c174bff/numpy-2.2.6-cp310-cp310-macosx_11_0_arm64.whl", hash = "sha256:8e41fd67c52b86603a91c1a505ebaef50b3314de0213461c7a6e99c9a3beff90", size = 14360048 }, - { url = "https://files.pythonhosted.org/packages/fd/77/dc2fcfc66943c6410e2bf598062f5959372735ffda175b39906d54f02349/numpy-2.2.6-cp310-cp310-macosx_14_0_arm64.whl", hash = "sha256:37e990a01ae6ec7fe7fa1c26c55ecb672dd98b19c3d0e1d1f326fa13cb38d163", size = 5340542 }, - { url = "https://files.pythonhosted.org/packages/7a/4f/1cb5fdc353a5f5cc7feb692db9b8ec2c3d6405453f982435efc52561df58/numpy-2.2.6-cp310-cp310-macosx_14_0_x86_64.whl", hash = "sha256:5a6429d4be8ca66d889b7cf70f536a397dc45ba6faeb5f8c5427935d9592e9cf", size = 6878301 }, - { url = "https://files.pythonhosted.org/packages/eb/17/96a3acd228cec142fcb8723bd3cc39c2a474f7dcf0a5d16731980bcafa95/numpy-2.2.6-cp310-cp310-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:efd28d4e9cd7d7a8d39074a4d44c63eda73401580c5c76acda2ce969e0a38e83", size = 14297320 }, - { url = "https://files.pythonhosted.org/packages/b4/63/3de6a34ad7ad6646ac7d2f55ebc6ad439dbbf9c4370017c50cf403fb19b5/numpy-2.2.6-cp310-cp310-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:fc7b73d02efb0e18c000e9ad8b83480dfcd5dfd11065997ed4c6747470ae8915", size = 16801050 }, - { url = "https://files.pythonhosted.org/packages/07/b6/89d837eddef52b3d0cec5c6ba0456c1bf1b9ef6a6672fc2b7873c3ec4e2e/numpy-2.2.6-cp310-cp310-musllinux_1_2_aarch64.whl", hash = "sha256:74d4531beb257d2c3f4b261bfb0fc09e0f9ebb8842d82a7b4209415896adc680", size = 15807034 }, - { url = "https://files.pythonhosted.org/packages/01/c8/dc6ae86e3c61cfec1f178e5c9f7858584049b6093f843bca541f94120920/numpy-2.2.6-cp310-cp310-musllinux_1_2_x86_64.whl", hash = "sha256:8fc377d995680230e83241d8a96def29f204b5782f371c532579b4f20607a289", size = 18614185 }, - { url = "https://files.pythonhosted.org/packages/5b/c5/0064b1b7e7c89137b471ccec1fd2282fceaae0ab3a9550f2568782d80357/numpy-2.2.6-cp310-cp310-win32.whl", hash = "sha256:b093dd74e50a8cba3e873868d9e93a85b78e0daf2e98c6797566ad8044e8363d", size = 6527149 }, - { url = "https://files.pythonhosted.org/packages/a3/dd/4b822569d6b96c39d1215dbae0582fd99954dcbcf0c1a13c61783feaca3f/numpy-2.2.6-cp310-cp310-win_amd64.whl", hash = "sha256:f0fd6321b839904e15c46e0d257fdd101dd7f530fe03fd6359c1ea63738703f3", size = 12904620 }, - { url = "https://files.pythonhosted.org/packages/da/a8/4f83e2aa666a9fbf56d6118faaaf5f1974d456b1823fda0a176eff722839/numpy-2.2.6-cp311-cp311-macosx_10_9_x86_64.whl", hash = "sha256:f9f1adb22318e121c5c69a09142811a201ef17ab257a1e66ca3025065b7f53ae", size = 21176963 }, - { url = "https://files.pythonhosted.org/packages/b3/2b/64e1affc7972decb74c9e29e5649fac940514910960ba25cd9af4488b66c/numpy-2.2.6-cp311-cp311-macosx_11_0_arm64.whl", hash = "sha256:c820a93b0255bc360f53eca31a0e676fd1101f673dda8da93454a12e23fc5f7a", size = 14406743 }, - { url = "https://files.pythonhosted.org/packages/4a/9f/0121e375000b5e50ffdd8b25bf78d8e1a5aa4cca3f185d41265198c7b834/numpy-2.2.6-cp311-cp311-macosx_14_0_arm64.whl", hash = "sha256:3d70692235e759f260c3d837193090014aebdf026dfd167834bcba43e30c2a42", size = 5352616 }, - { url = "https://files.pythonhosted.org/packages/31/0d/b48c405c91693635fbe2dcd7bc84a33a602add5f63286e024d3b6741411c/numpy-2.2.6-cp311-cp311-macosx_14_0_x86_64.whl", hash = "sha256:481b49095335f8eed42e39e8041327c05b0f6f4780488f61286ed3c01368d491", size = 6889579 }, - { url = "https://files.pythonhosted.org/packages/52/b8/7f0554d49b565d0171eab6e99001846882000883998e7b7d9f0d98b1f934/numpy-2.2.6-cp311-cp311-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:b64d8d4d17135e00c8e346e0a738deb17e754230d7e0810ac5012750bbd85a5a", size = 14312005 }, - { url = "https://files.pythonhosted.org/packages/b3/dd/2238b898e51bd6d389b7389ffb20d7f4c10066d80351187ec8e303a5a475/numpy-2.2.6-cp311-cp311-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:ba10f8411898fc418a521833e014a77d3ca01c15b0c6cdcce6a0d2897e6dbbdf", size = 16821570 }, - { url = "https://files.pythonhosted.org/packages/83/6c/44d0325722cf644f191042bf47eedad61c1e6df2432ed65cbe28509d404e/numpy-2.2.6-cp311-cp311-musllinux_1_2_aarch64.whl", hash = "sha256:bd48227a919f1bafbdda0583705e547892342c26fb127219d60a5c36882609d1", size = 15818548 }, - { url = "https://files.pythonhosted.org/packages/ae/9d/81e8216030ce66be25279098789b665d49ff19eef08bfa8cb96d4957f422/numpy-2.2.6-cp311-cp311-musllinux_1_2_x86_64.whl", hash = "sha256:9551a499bf125c1d4f9e250377c1ee2eddd02e01eac6644c080162c0c51778ab", size = 18620521 }, - { url = "https://files.pythonhosted.org/packages/6a/fd/e19617b9530b031db51b0926eed5345ce8ddc669bb3bc0044b23e275ebe8/numpy-2.2.6-cp311-cp311-win32.whl", hash = "sha256:0678000bb9ac1475cd454c6b8c799206af8107e310843532b04d49649c717a47", size = 6525866 }, - { url = "https://files.pythonhosted.org/packages/31/0a/f354fb7176b81747d870f7991dc763e157a934c717b67b58456bc63da3df/numpy-2.2.6-cp311-cp311-win_amd64.whl", hash = "sha256:e8213002e427c69c45a52bbd94163084025f533a55a59d6f9c5b820774ef3303", size = 12907455 }, - { url = "https://files.pythonhosted.org/packages/82/5d/c00588b6cf18e1da539b45d3598d3557084990dcc4331960c15ee776ee41/numpy-2.2.6-cp312-cp312-macosx_10_13_x86_64.whl", hash = "sha256:41c5a21f4a04fa86436124d388f6ed60a9343a6f767fced1a8a71c3fbca038ff", size = 20875348 }, - { url = "https://files.pythonhosted.org/packages/66/ee/560deadcdde6c2f90200450d5938f63a34b37e27ebff162810f716f6a230/numpy-2.2.6-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:de749064336d37e340f640b05f24e9e3dd678c57318c7289d222a8a2f543e90c", size = 14119362 }, - { url = "https://files.pythonhosted.org/packages/3c/65/4baa99f1c53b30adf0acd9a5519078871ddde8d2339dc5a7fde80d9d87da/numpy-2.2.6-cp312-cp312-macosx_14_0_arm64.whl", hash = "sha256:894b3a42502226a1cac872f840030665f33326fc3dac8e57c607905773cdcde3", size = 5084103 }, - { url = "https://files.pythonhosted.org/packages/cc/89/e5a34c071a0570cc40c9a54eb472d113eea6d002e9ae12bb3a8407fb912e/numpy-2.2.6-cp312-cp312-macosx_14_0_x86_64.whl", hash = "sha256:71594f7c51a18e728451bb50cc60a3ce4e6538822731b2933209a1f3614e9282", size = 6625382 }, - { url = "https://files.pythonhosted.org/packages/f8/35/8c80729f1ff76b3921d5c9487c7ac3de9b2a103b1cd05e905b3090513510/numpy-2.2.6-cp312-cp312-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:f2618db89be1b4e05f7a1a847a9c1c0abd63e63a1607d892dd54668dd92faf87", size = 14018462 }, - { url = "https://files.pythonhosted.org/packages/8c/3d/1e1db36cfd41f895d266b103df00ca5b3cbe965184df824dec5c08c6b803/numpy-2.2.6-cp312-cp312-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:fd83c01228a688733f1ded5201c678f0c53ecc1006ffbc404db9f7a899ac6249", size = 16527618 }, - { url = "https://files.pythonhosted.org/packages/61/c6/03ed30992602c85aa3cd95b9070a514f8b3c33e31124694438d88809ae36/numpy-2.2.6-cp312-cp312-musllinux_1_2_aarch64.whl", hash = "sha256:37c0ca431f82cd5fa716eca9506aefcabc247fb27ba69c5062a6d3ade8cf8f49", size = 15505511 }, - { url = "https://files.pythonhosted.org/packages/b7/25/5761d832a81df431e260719ec45de696414266613c9ee268394dd5ad8236/numpy-2.2.6-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:fe27749d33bb772c80dcd84ae7e8df2adc920ae8297400dabec45f0dedb3f6de", size = 18313783 }, - { url = "https://files.pythonhosted.org/packages/57/0a/72d5a3527c5ebffcd47bde9162c39fae1f90138c961e5296491ce778e682/numpy-2.2.6-cp312-cp312-win32.whl", hash = "sha256:4eeaae00d789f66c7a25ac5f34b71a7035bb474e679f410e5e1a94deb24cf2d4", size = 6246506 }, - { url = "https://files.pythonhosted.org/packages/36/fa/8c9210162ca1b88529ab76b41ba02d433fd54fecaf6feb70ef9f124683f1/numpy-2.2.6-cp312-cp312-win_amd64.whl", hash = "sha256:c1f9540be57940698ed329904db803cf7a402f3fc200bfe599334c9bd84a40b2", size = 12614190 }, - { url = "https://files.pythonhosted.org/packages/f9/5c/6657823f4f594f72b5471f1db1ab12e26e890bb2e41897522d134d2a3e81/numpy-2.2.6-cp313-cp313-macosx_10_13_x86_64.whl", hash = "sha256:0811bb762109d9708cca4d0b13c4f67146e3c3b7cf8d34018c722adb2d957c84", size = 20867828 }, - { url = "https://files.pythonhosted.org/packages/dc/9e/14520dc3dadf3c803473bd07e9b2bd1b69bc583cb2497b47000fed2fa92f/numpy-2.2.6-cp313-cp313-macosx_11_0_arm64.whl", hash = "sha256:287cc3162b6f01463ccd86be154f284d0893d2b3ed7292439ea97eafa8170e0b", size = 14143006 }, - { url = "https://files.pythonhosted.org/packages/4f/06/7e96c57d90bebdce9918412087fc22ca9851cceaf5567a45c1f404480e9e/numpy-2.2.6-cp313-cp313-macosx_14_0_arm64.whl", hash = "sha256:f1372f041402e37e5e633e586f62aa53de2eac8d98cbfb822806ce4bbefcb74d", size = 5076765 }, - { url = "https://files.pythonhosted.org/packages/73/ed/63d920c23b4289fdac96ddbdd6132e9427790977d5457cd132f18e76eae0/numpy-2.2.6-cp313-cp313-macosx_14_0_x86_64.whl", hash = "sha256:55a4d33fa519660d69614a9fad433be87e5252f4b03850642f88993f7b2ca566", size = 6617736 }, - { url = "https://files.pythonhosted.org/packages/85/c5/e19c8f99d83fd377ec8c7e0cf627a8049746da54afc24ef0a0cb73d5dfb5/numpy-2.2.6-cp313-cp313-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:f92729c95468a2f4f15e9bb94c432a9229d0d50de67304399627a943201baa2f", size = 14010719 }, - { url = "https://files.pythonhosted.org/packages/19/49/4df9123aafa7b539317bf6d342cb6d227e49f7a35b99c287a6109b13dd93/numpy-2.2.6-cp313-cp313-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:1bc23a79bfabc5d056d106f9befb8d50c31ced2fbc70eedb8155aec74a45798f", size = 16526072 }, - { url = "https://files.pythonhosted.org/packages/b2/6c/04b5f47f4f32f7c2b0e7260442a8cbcf8168b0e1a41ff1495da42f42a14f/numpy-2.2.6-cp313-cp313-musllinux_1_2_aarch64.whl", hash = "sha256:e3143e4451880bed956e706a3220b4e5cf6172ef05fcc397f6f36a550b1dd868", size = 15503213 }, - { url = "https://files.pythonhosted.org/packages/17/0a/5cd92e352c1307640d5b6fec1b2ffb06cd0dabe7d7b8227f97933d378422/numpy-2.2.6-cp313-cp313-musllinux_1_2_x86_64.whl", hash = "sha256:b4f13750ce79751586ae2eb824ba7e1e8dba64784086c98cdbbcc6a42112ce0d", size = 18316632 }, - { url = "https://files.pythonhosted.org/packages/f0/3b/5cba2b1d88760ef86596ad0f3d484b1cbff7c115ae2429678465057c5155/numpy-2.2.6-cp313-cp313-win32.whl", hash = "sha256:5beb72339d9d4fa36522fc63802f469b13cdbe4fdab4a288f0c441b74272ebfd", size = 6244532 }, - { url = "https://files.pythonhosted.org/packages/cb/3b/d58c12eafcb298d4e6d0d40216866ab15f59e55d148a5658bb3132311fcf/numpy-2.2.6-cp313-cp313-win_amd64.whl", hash = "sha256:b0544343a702fa80c95ad5d3d608ea3599dd54d4632df855e4c8d24eb6ecfa1c", size = 12610885 }, - { url = "https://files.pythonhosted.org/packages/6b/9e/4bf918b818e516322db999ac25d00c75788ddfd2d2ade4fa66f1f38097e1/numpy-2.2.6-cp313-cp313t-macosx_10_13_x86_64.whl", hash = "sha256:0bca768cd85ae743b2affdc762d617eddf3bcf8724435498a1e80132d04879e6", size = 20963467 }, - { url = "https://files.pythonhosted.org/packages/61/66/d2de6b291507517ff2e438e13ff7b1e2cdbdb7cb40b3ed475377aece69f9/numpy-2.2.6-cp313-cp313t-macosx_11_0_arm64.whl", hash = "sha256:fc0c5673685c508a142ca65209b4e79ed6740a4ed6b2267dbba90f34b0b3cfda", size = 14225144 }, - { url = "https://files.pythonhosted.org/packages/e4/25/480387655407ead912e28ba3a820bc69af9adf13bcbe40b299d454ec011f/numpy-2.2.6-cp313-cp313t-macosx_14_0_arm64.whl", hash = "sha256:5bd4fc3ac8926b3819797a7c0e2631eb889b4118a9898c84f585a54d475b7e40", size = 5200217 }, - { url = "https://files.pythonhosted.org/packages/aa/4a/6e313b5108f53dcbf3aca0c0f3e9c92f4c10ce57a0a721851f9785872895/numpy-2.2.6-cp313-cp313t-macosx_14_0_x86_64.whl", hash = "sha256:fee4236c876c4e8369388054d02d0e9bb84821feb1a64dd59e137e6511a551f8", size = 6712014 }, - { url = "https://files.pythonhosted.org/packages/b7/30/172c2d5c4be71fdf476e9de553443cf8e25feddbe185e0bd88b096915bcc/numpy-2.2.6-cp313-cp313t-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:e1dda9c7e08dc141e0247a5b8f49cf05984955246a327d4c48bda16821947b2f", size = 14077935 }, - { url = "https://files.pythonhosted.org/packages/12/fb/9e743f8d4e4d3c710902cf87af3512082ae3d43b945d5d16563f26ec251d/numpy-2.2.6-cp313-cp313t-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:f447e6acb680fd307f40d3da4852208af94afdfab89cf850986c3ca00562f4fa", size = 16600122 }, - { url = "https://files.pythonhosted.org/packages/12/75/ee20da0e58d3a66f204f38916757e01e33a9737d0b22373b3eb5a27358f9/numpy-2.2.6-cp313-cp313t-musllinux_1_2_aarch64.whl", hash = "sha256:389d771b1623ec92636b0786bc4ae56abafad4a4c513d36a55dce14bd9ce8571", size = 15586143 }, - { url = "https://files.pythonhosted.org/packages/76/95/bef5b37f29fc5e739947e9ce5179ad402875633308504a52d188302319c8/numpy-2.2.6-cp313-cp313t-musllinux_1_2_x86_64.whl", hash = "sha256:8e9ace4a37db23421249ed236fdcdd457d671e25146786dfc96835cd951aa7c1", size = 18385260 }, - { url = "https://files.pythonhosted.org/packages/09/04/f2f83279d287407cf36a7a8053a5abe7be3622a4363337338f2585e4afda/numpy-2.2.6-cp313-cp313t-win32.whl", hash = "sha256:038613e9fb8c72b0a41f025a7e4c3f0b7a1b5d768ece4796b674c8f3fe13efff", size = 6377225 }, - { url = "https://files.pythonhosted.org/packages/67/0e/35082d13c09c02c011cf21570543d202ad929d961c02a147493cb0c2bdf5/numpy-2.2.6-cp313-cp313t-win_amd64.whl", hash = "sha256:6031dd6dfecc0cf9f668681a37648373bddd6421fff6c66ec1624eed0180ee06", size = 12771374 }, - { url = "https://files.pythonhosted.org/packages/9e/3b/d94a75f4dbf1ef5d321523ecac21ef23a3cd2ac8b78ae2aac40873590229/numpy-2.2.6-pp310-pypy310_pp73-macosx_10_15_x86_64.whl", hash = "sha256:0b605b275d7bd0c640cad4e5d30fa701a8d59302e127e5f79138ad62762c3e3d", size = 21040391 }, - { url = "https://files.pythonhosted.org/packages/17/f4/09b2fa1b58f0fb4f7c7963a1649c64c4d315752240377ed74d9cd878f7b5/numpy-2.2.6-pp310-pypy310_pp73-macosx_14_0_x86_64.whl", hash = "sha256:7befc596a7dc9da8a337f79802ee8adb30a552a94f792b9c9d18c840055907db", size = 6786754 }, - { url = "https://files.pythonhosted.org/packages/af/30/feba75f143bdc868a1cc3f44ccfa6c4b9ec522b36458e738cd00f67b573f/numpy-2.2.6-pp310-pypy310_pp73-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:ce47521a4754c8f4593837384bd3424880629f718d87c5d44f8ed763edd63543", size = 16643476 }, - { url = "https://files.pythonhosted.org/packages/37/48/ac2a9584402fb6c0cd5b5d1a91dcf176b15760130dd386bbafdbfe3640bf/numpy-2.2.6-pp310-pypy310_pp73-win_amd64.whl", hash = "sha256:d042d24c90c41b54fd506da306759e06e568864df8ec17ccc17e9e884634fd00", size = 12812666 }, +sdist = { url = "https://files.pythonhosted.org/packages/76/21/7d2a95e4bba9dc13d043ee156a356c0a8f0c6309dff6b21b4d71a073b8a8/numpy-2.2.6.tar.gz", hash = "sha256:e29554e2bef54a90aa5cc07da6ce955accb83f21ab5de01a62c8478897b264fd", size = 20276440, upload-time = "2025-05-17T22:38:04.611Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/9a/3e/ed6db5be21ce87955c0cbd3009f2803f59fa08df21b5df06862e2d8e2bdd/numpy-2.2.6-cp310-cp310-macosx_10_9_x86_64.whl", hash = "sha256:b412caa66f72040e6d268491a59f2c43bf03eb6c96dd8f0307829feb7fa2b6fb", size = 21165245, upload-time = "2025-05-17T21:27:58.555Z" }, + { url = "https://files.pythonhosted.org/packages/22/c2/4b9221495b2a132cc9d2eb862e21d42a009f5a60e45fc44b00118c174bff/numpy-2.2.6-cp310-cp310-macosx_11_0_arm64.whl", hash = "sha256:8e41fd67c52b86603a91c1a505ebaef50b3314de0213461c7a6e99c9a3beff90", size = 14360048, upload-time = "2025-05-17T21:28:21.406Z" }, + { url = "https://files.pythonhosted.org/packages/fd/77/dc2fcfc66943c6410e2bf598062f5959372735ffda175b39906d54f02349/numpy-2.2.6-cp310-cp310-macosx_14_0_arm64.whl", hash = "sha256:37e990a01ae6ec7fe7fa1c26c55ecb672dd98b19c3d0e1d1f326fa13cb38d163", size = 5340542, upload-time = "2025-05-17T21:28:30.931Z" }, + { url = "https://files.pythonhosted.org/packages/7a/4f/1cb5fdc353a5f5cc7feb692db9b8ec2c3d6405453f982435efc52561df58/numpy-2.2.6-cp310-cp310-macosx_14_0_x86_64.whl", hash = "sha256:5a6429d4be8ca66d889b7cf70f536a397dc45ba6faeb5f8c5427935d9592e9cf", size = 6878301, upload-time = "2025-05-17T21:28:41.613Z" }, + { url = "https://files.pythonhosted.org/packages/eb/17/96a3acd228cec142fcb8723bd3cc39c2a474f7dcf0a5d16731980bcafa95/numpy-2.2.6-cp310-cp310-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:efd28d4e9cd7d7a8d39074a4d44c63eda73401580c5c76acda2ce969e0a38e83", size = 14297320, upload-time = "2025-05-17T21:29:02.78Z" }, + { url = "https://files.pythonhosted.org/packages/b4/63/3de6a34ad7ad6646ac7d2f55ebc6ad439dbbf9c4370017c50cf403fb19b5/numpy-2.2.6-cp310-cp310-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:fc7b73d02efb0e18c000e9ad8b83480dfcd5dfd11065997ed4c6747470ae8915", size = 16801050, upload-time = "2025-05-17T21:29:27.675Z" }, + { url = "https://files.pythonhosted.org/packages/07/b6/89d837eddef52b3d0cec5c6ba0456c1bf1b9ef6a6672fc2b7873c3ec4e2e/numpy-2.2.6-cp310-cp310-musllinux_1_2_aarch64.whl", hash = "sha256:74d4531beb257d2c3f4b261bfb0fc09e0f9ebb8842d82a7b4209415896adc680", size = 15807034, upload-time = "2025-05-17T21:29:51.102Z" }, + { url = "https://files.pythonhosted.org/packages/01/c8/dc6ae86e3c61cfec1f178e5c9f7858584049b6093f843bca541f94120920/numpy-2.2.6-cp310-cp310-musllinux_1_2_x86_64.whl", hash = "sha256:8fc377d995680230e83241d8a96def29f204b5782f371c532579b4f20607a289", size = 18614185, upload-time = "2025-05-17T21:30:18.703Z" }, + { url = "https://files.pythonhosted.org/packages/5b/c5/0064b1b7e7c89137b471ccec1fd2282fceaae0ab3a9550f2568782d80357/numpy-2.2.6-cp310-cp310-win32.whl", hash = "sha256:b093dd74e50a8cba3e873868d9e93a85b78e0daf2e98c6797566ad8044e8363d", size = 6527149, upload-time = "2025-05-17T21:30:29.788Z" }, + { url = "https://files.pythonhosted.org/packages/a3/dd/4b822569d6b96c39d1215dbae0582fd99954dcbcf0c1a13c61783feaca3f/numpy-2.2.6-cp310-cp310-win_amd64.whl", hash = "sha256:f0fd6321b839904e15c46e0d257fdd101dd7f530fe03fd6359c1ea63738703f3", size = 12904620, upload-time = "2025-05-17T21:30:48.994Z" }, + { url = "https://files.pythonhosted.org/packages/da/a8/4f83e2aa666a9fbf56d6118faaaf5f1974d456b1823fda0a176eff722839/numpy-2.2.6-cp311-cp311-macosx_10_9_x86_64.whl", hash = "sha256:f9f1adb22318e121c5c69a09142811a201ef17ab257a1e66ca3025065b7f53ae", size = 21176963, upload-time = "2025-05-17T21:31:19.36Z" }, + { url = "https://files.pythonhosted.org/packages/b3/2b/64e1affc7972decb74c9e29e5649fac940514910960ba25cd9af4488b66c/numpy-2.2.6-cp311-cp311-macosx_11_0_arm64.whl", hash = "sha256:c820a93b0255bc360f53eca31a0e676fd1101f673dda8da93454a12e23fc5f7a", size = 14406743, upload-time = "2025-05-17T21:31:41.087Z" }, + { url = "https://files.pythonhosted.org/packages/4a/9f/0121e375000b5e50ffdd8b25bf78d8e1a5aa4cca3f185d41265198c7b834/numpy-2.2.6-cp311-cp311-macosx_14_0_arm64.whl", hash = "sha256:3d70692235e759f260c3d837193090014aebdf026dfd167834bcba43e30c2a42", size = 5352616, upload-time = "2025-05-17T21:31:50.072Z" }, + { url = "https://files.pythonhosted.org/packages/31/0d/b48c405c91693635fbe2dcd7bc84a33a602add5f63286e024d3b6741411c/numpy-2.2.6-cp311-cp311-macosx_14_0_x86_64.whl", hash = "sha256:481b49095335f8eed42e39e8041327c05b0f6f4780488f61286ed3c01368d491", size = 6889579, upload-time = "2025-05-17T21:32:01.712Z" }, + { url = "https://files.pythonhosted.org/packages/52/b8/7f0554d49b565d0171eab6e99001846882000883998e7b7d9f0d98b1f934/numpy-2.2.6-cp311-cp311-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:b64d8d4d17135e00c8e346e0a738deb17e754230d7e0810ac5012750bbd85a5a", size = 14312005, upload-time = "2025-05-17T21:32:23.332Z" }, + { url = "https://files.pythonhosted.org/packages/b3/dd/2238b898e51bd6d389b7389ffb20d7f4c10066d80351187ec8e303a5a475/numpy-2.2.6-cp311-cp311-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:ba10f8411898fc418a521833e014a77d3ca01c15b0c6cdcce6a0d2897e6dbbdf", size = 16821570, upload-time = "2025-05-17T21:32:47.991Z" }, + { url = "https://files.pythonhosted.org/packages/83/6c/44d0325722cf644f191042bf47eedad61c1e6df2432ed65cbe28509d404e/numpy-2.2.6-cp311-cp311-musllinux_1_2_aarch64.whl", hash = "sha256:bd48227a919f1bafbdda0583705e547892342c26fb127219d60a5c36882609d1", size = 15818548, upload-time = "2025-05-17T21:33:11.728Z" }, + { url = "https://files.pythonhosted.org/packages/ae/9d/81e8216030ce66be25279098789b665d49ff19eef08bfa8cb96d4957f422/numpy-2.2.6-cp311-cp311-musllinux_1_2_x86_64.whl", hash = "sha256:9551a499bf125c1d4f9e250377c1ee2eddd02e01eac6644c080162c0c51778ab", size = 18620521, upload-time = "2025-05-17T21:33:39.139Z" }, + { url = "https://files.pythonhosted.org/packages/6a/fd/e19617b9530b031db51b0926eed5345ce8ddc669bb3bc0044b23e275ebe8/numpy-2.2.6-cp311-cp311-win32.whl", hash = "sha256:0678000bb9ac1475cd454c6b8c799206af8107e310843532b04d49649c717a47", size = 6525866, upload-time = "2025-05-17T21:33:50.273Z" }, + { url = "https://files.pythonhosted.org/packages/31/0a/f354fb7176b81747d870f7991dc763e157a934c717b67b58456bc63da3df/numpy-2.2.6-cp311-cp311-win_amd64.whl", hash = "sha256:e8213002e427c69c45a52bbd94163084025f533a55a59d6f9c5b820774ef3303", size = 12907455, upload-time = "2025-05-17T21:34:09.135Z" }, + { url = "https://files.pythonhosted.org/packages/82/5d/c00588b6cf18e1da539b45d3598d3557084990dcc4331960c15ee776ee41/numpy-2.2.6-cp312-cp312-macosx_10_13_x86_64.whl", hash = "sha256:41c5a21f4a04fa86436124d388f6ed60a9343a6f767fced1a8a71c3fbca038ff", size = 20875348, upload-time = "2025-05-17T21:34:39.648Z" }, + { url = "https://files.pythonhosted.org/packages/66/ee/560deadcdde6c2f90200450d5938f63a34b37e27ebff162810f716f6a230/numpy-2.2.6-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:de749064336d37e340f640b05f24e9e3dd678c57318c7289d222a8a2f543e90c", size = 14119362, upload-time = "2025-05-17T21:35:01.241Z" }, + { url = "https://files.pythonhosted.org/packages/3c/65/4baa99f1c53b30adf0acd9a5519078871ddde8d2339dc5a7fde80d9d87da/numpy-2.2.6-cp312-cp312-macosx_14_0_arm64.whl", hash = "sha256:894b3a42502226a1cac872f840030665f33326fc3dac8e57c607905773cdcde3", size = 5084103, upload-time = "2025-05-17T21:35:10.622Z" }, + { url = "https://files.pythonhosted.org/packages/cc/89/e5a34c071a0570cc40c9a54eb472d113eea6d002e9ae12bb3a8407fb912e/numpy-2.2.6-cp312-cp312-macosx_14_0_x86_64.whl", hash = "sha256:71594f7c51a18e728451bb50cc60a3ce4e6538822731b2933209a1f3614e9282", size = 6625382, upload-time = "2025-05-17T21:35:21.414Z" }, + { url = "https://files.pythonhosted.org/packages/f8/35/8c80729f1ff76b3921d5c9487c7ac3de9b2a103b1cd05e905b3090513510/numpy-2.2.6-cp312-cp312-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:f2618db89be1b4e05f7a1a847a9c1c0abd63e63a1607d892dd54668dd92faf87", size = 14018462, upload-time = "2025-05-17T21:35:42.174Z" }, + { url = "https://files.pythonhosted.org/packages/8c/3d/1e1db36cfd41f895d266b103df00ca5b3cbe965184df824dec5c08c6b803/numpy-2.2.6-cp312-cp312-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:fd83c01228a688733f1ded5201c678f0c53ecc1006ffbc404db9f7a899ac6249", size = 16527618, upload-time = "2025-05-17T21:36:06.711Z" }, + { url = "https://files.pythonhosted.org/packages/61/c6/03ed30992602c85aa3cd95b9070a514f8b3c33e31124694438d88809ae36/numpy-2.2.6-cp312-cp312-musllinux_1_2_aarch64.whl", hash = "sha256:37c0ca431f82cd5fa716eca9506aefcabc247fb27ba69c5062a6d3ade8cf8f49", size = 15505511, upload-time = "2025-05-17T21:36:29.965Z" }, + { url = "https://files.pythonhosted.org/packages/b7/25/5761d832a81df431e260719ec45de696414266613c9ee268394dd5ad8236/numpy-2.2.6-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:fe27749d33bb772c80dcd84ae7e8df2adc920ae8297400dabec45f0dedb3f6de", size = 18313783, upload-time = "2025-05-17T21:36:56.883Z" }, + { url = "https://files.pythonhosted.org/packages/57/0a/72d5a3527c5ebffcd47bde9162c39fae1f90138c961e5296491ce778e682/numpy-2.2.6-cp312-cp312-win32.whl", hash = "sha256:4eeaae00d789f66c7a25ac5f34b71a7035bb474e679f410e5e1a94deb24cf2d4", size = 6246506, upload-time = "2025-05-17T21:37:07.368Z" }, + { url = "https://files.pythonhosted.org/packages/36/fa/8c9210162ca1b88529ab76b41ba02d433fd54fecaf6feb70ef9f124683f1/numpy-2.2.6-cp312-cp312-win_amd64.whl", hash = "sha256:c1f9540be57940698ed329904db803cf7a402f3fc200bfe599334c9bd84a40b2", size = 12614190, upload-time = "2025-05-17T21:37:26.213Z" }, + { url = "https://files.pythonhosted.org/packages/f9/5c/6657823f4f594f72b5471f1db1ab12e26e890bb2e41897522d134d2a3e81/numpy-2.2.6-cp313-cp313-macosx_10_13_x86_64.whl", hash = "sha256:0811bb762109d9708cca4d0b13c4f67146e3c3b7cf8d34018c722adb2d957c84", size = 20867828, upload-time = "2025-05-17T21:37:56.699Z" }, + { url = "https://files.pythonhosted.org/packages/dc/9e/14520dc3dadf3c803473bd07e9b2bd1b69bc583cb2497b47000fed2fa92f/numpy-2.2.6-cp313-cp313-macosx_11_0_arm64.whl", hash = "sha256:287cc3162b6f01463ccd86be154f284d0893d2b3ed7292439ea97eafa8170e0b", size = 14143006, upload-time = "2025-05-17T21:38:18.291Z" }, + { url = "https://files.pythonhosted.org/packages/4f/06/7e96c57d90bebdce9918412087fc22ca9851cceaf5567a45c1f404480e9e/numpy-2.2.6-cp313-cp313-macosx_14_0_arm64.whl", hash = "sha256:f1372f041402e37e5e633e586f62aa53de2eac8d98cbfb822806ce4bbefcb74d", size = 5076765, upload-time = "2025-05-17T21:38:27.319Z" }, + { url = "https://files.pythonhosted.org/packages/73/ed/63d920c23b4289fdac96ddbdd6132e9427790977d5457cd132f18e76eae0/numpy-2.2.6-cp313-cp313-macosx_14_0_x86_64.whl", hash = "sha256:55a4d33fa519660d69614a9fad433be87e5252f4b03850642f88993f7b2ca566", size = 6617736, upload-time = "2025-05-17T21:38:38.141Z" }, + { url = "https://files.pythonhosted.org/packages/85/c5/e19c8f99d83fd377ec8c7e0cf627a8049746da54afc24ef0a0cb73d5dfb5/numpy-2.2.6-cp313-cp313-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:f92729c95468a2f4f15e9bb94c432a9229d0d50de67304399627a943201baa2f", size = 14010719, upload-time = "2025-05-17T21:38:58.433Z" }, + { url = "https://files.pythonhosted.org/packages/19/49/4df9123aafa7b539317bf6d342cb6d227e49f7a35b99c287a6109b13dd93/numpy-2.2.6-cp313-cp313-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:1bc23a79bfabc5d056d106f9befb8d50c31ced2fbc70eedb8155aec74a45798f", size = 16526072, upload-time = "2025-05-17T21:39:22.638Z" }, + { url = "https://files.pythonhosted.org/packages/b2/6c/04b5f47f4f32f7c2b0e7260442a8cbcf8168b0e1a41ff1495da42f42a14f/numpy-2.2.6-cp313-cp313-musllinux_1_2_aarch64.whl", hash = "sha256:e3143e4451880bed956e706a3220b4e5cf6172ef05fcc397f6f36a550b1dd868", size = 15503213, upload-time = "2025-05-17T21:39:45.865Z" }, + { url = "https://files.pythonhosted.org/packages/17/0a/5cd92e352c1307640d5b6fec1b2ffb06cd0dabe7d7b8227f97933d378422/numpy-2.2.6-cp313-cp313-musllinux_1_2_x86_64.whl", hash = "sha256:b4f13750ce79751586ae2eb824ba7e1e8dba64784086c98cdbbcc6a42112ce0d", size = 18316632, upload-time = "2025-05-17T21:40:13.331Z" }, + { url = "https://files.pythonhosted.org/packages/f0/3b/5cba2b1d88760ef86596ad0f3d484b1cbff7c115ae2429678465057c5155/numpy-2.2.6-cp313-cp313-win32.whl", hash = "sha256:5beb72339d9d4fa36522fc63802f469b13cdbe4fdab4a288f0c441b74272ebfd", size = 6244532, upload-time = "2025-05-17T21:43:46.099Z" }, + { url = "https://files.pythonhosted.org/packages/cb/3b/d58c12eafcb298d4e6d0d40216866ab15f59e55d148a5658bb3132311fcf/numpy-2.2.6-cp313-cp313-win_amd64.whl", hash = "sha256:b0544343a702fa80c95ad5d3d608ea3599dd54d4632df855e4c8d24eb6ecfa1c", size = 12610885, upload-time = "2025-05-17T21:44:05.145Z" }, + { url = "https://files.pythonhosted.org/packages/6b/9e/4bf918b818e516322db999ac25d00c75788ddfd2d2ade4fa66f1f38097e1/numpy-2.2.6-cp313-cp313t-macosx_10_13_x86_64.whl", hash = "sha256:0bca768cd85ae743b2affdc762d617eddf3bcf8724435498a1e80132d04879e6", size = 20963467, upload-time = "2025-05-17T21:40:44Z" }, + { url = "https://files.pythonhosted.org/packages/61/66/d2de6b291507517ff2e438e13ff7b1e2cdbdb7cb40b3ed475377aece69f9/numpy-2.2.6-cp313-cp313t-macosx_11_0_arm64.whl", hash = "sha256:fc0c5673685c508a142ca65209b4e79ed6740a4ed6b2267dbba90f34b0b3cfda", size = 14225144, upload-time = "2025-05-17T21:41:05.695Z" }, + { url = "https://files.pythonhosted.org/packages/e4/25/480387655407ead912e28ba3a820bc69af9adf13bcbe40b299d454ec011f/numpy-2.2.6-cp313-cp313t-macosx_14_0_arm64.whl", hash = "sha256:5bd4fc3ac8926b3819797a7c0e2631eb889b4118a9898c84f585a54d475b7e40", size = 5200217, upload-time = "2025-05-17T21:41:15.903Z" }, + { url = "https://files.pythonhosted.org/packages/aa/4a/6e313b5108f53dcbf3aca0c0f3e9c92f4c10ce57a0a721851f9785872895/numpy-2.2.6-cp313-cp313t-macosx_14_0_x86_64.whl", hash = "sha256:fee4236c876c4e8369388054d02d0e9bb84821feb1a64dd59e137e6511a551f8", size = 6712014, upload-time = "2025-05-17T21:41:27.321Z" }, + { url = "https://files.pythonhosted.org/packages/b7/30/172c2d5c4be71fdf476e9de553443cf8e25feddbe185e0bd88b096915bcc/numpy-2.2.6-cp313-cp313t-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:e1dda9c7e08dc141e0247a5b8f49cf05984955246a327d4c48bda16821947b2f", size = 14077935, upload-time = "2025-05-17T21:41:49.738Z" }, + { url = "https://files.pythonhosted.org/packages/12/fb/9e743f8d4e4d3c710902cf87af3512082ae3d43b945d5d16563f26ec251d/numpy-2.2.6-cp313-cp313t-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:f447e6acb680fd307f40d3da4852208af94afdfab89cf850986c3ca00562f4fa", size = 16600122, upload-time = "2025-05-17T21:42:14.046Z" }, + { url = "https://files.pythonhosted.org/packages/12/75/ee20da0e58d3a66f204f38916757e01e33a9737d0b22373b3eb5a27358f9/numpy-2.2.6-cp313-cp313t-musllinux_1_2_aarch64.whl", hash = "sha256:389d771b1623ec92636b0786bc4ae56abafad4a4c513d36a55dce14bd9ce8571", size = 15586143, upload-time = "2025-05-17T21:42:37.464Z" }, + { url = "https://files.pythonhosted.org/packages/76/95/bef5b37f29fc5e739947e9ce5179ad402875633308504a52d188302319c8/numpy-2.2.6-cp313-cp313t-musllinux_1_2_x86_64.whl", hash = "sha256:8e9ace4a37db23421249ed236fdcdd457d671e25146786dfc96835cd951aa7c1", size = 18385260, upload-time = "2025-05-17T21:43:05.189Z" }, + { url = "https://files.pythonhosted.org/packages/09/04/f2f83279d287407cf36a7a8053a5abe7be3622a4363337338f2585e4afda/numpy-2.2.6-cp313-cp313t-win32.whl", hash = "sha256:038613e9fb8c72b0a41f025a7e4c3f0b7a1b5d768ece4796b674c8f3fe13efff", size = 6377225, upload-time = "2025-05-17T21:43:16.254Z" }, + { url = "https://files.pythonhosted.org/packages/67/0e/35082d13c09c02c011cf21570543d202ad929d961c02a147493cb0c2bdf5/numpy-2.2.6-cp313-cp313t-win_amd64.whl", hash = "sha256:6031dd6dfecc0cf9f668681a37648373bddd6421fff6c66ec1624eed0180ee06", size = 12771374, upload-time = "2025-05-17T21:43:35.479Z" }, + { url = "https://files.pythonhosted.org/packages/9e/3b/d94a75f4dbf1ef5d321523ecac21ef23a3cd2ac8b78ae2aac40873590229/numpy-2.2.6-pp310-pypy310_pp73-macosx_10_15_x86_64.whl", hash = "sha256:0b605b275d7bd0c640cad4e5d30fa701a8d59302e127e5f79138ad62762c3e3d", size = 21040391, upload-time = "2025-05-17T21:44:35.948Z" }, + { url = "https://files.pythonhosted.org/packages/17/f4/09b2fa1b58f0fb4f7c7963a1649c64c4d315752240377ed74d9cd878f7b5/numpy-2.2.6-pp310-pypy310_pp73-macosx_14_0_x86_64.whl", hash = "sha256:7befc596a7dc9da8a337f79802ee8adb30a552a94f792b9c9d18c840055907db", size = 6786754, upload-time = "2025-05-17T21:44:47.446Z" }, + { url = "https://files.pythonhosted.org/packages/af/30/feba75f143bdc868a1cc3f44ccfa6c4b9ec522b36458e738cd00f67b573f/numpy-2.2.6-pp310-pypy310_pp73-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:ce47521a4754c8f4593837384bd3424880629f718d87c5d44f8ed763edd63543", size = 16643476, upload-time = "2025-05-17T21:45:11.871Z" }, + { url = "https://files.pythonhosted.org/packages/37/48/ac2a9584402fb6c0cd5b5d1a91dcf176b15760130dd386bbafdbfe3640bf/numpy-2.2.6-pp310-pypy310_pp73-win_amd64.whl", hash = "sha256:d042d24c90c41b54fd506da306759e06e568864df8ec17ccc17e9e884634fd00", size = 12812666, upload-time = "2025-05-17T21:45:31.426Z" }, ] [[package]] name = "numpy" -version = "2.3.1" +version = "2.3.3" source = { registry = "https://pypi.org/simple" } resolution-markers = [ "python_full_version >= '3.13'", "python_full_version == '3.12.*'", "python_full_version == '3.11.*'", ] -sdist = { url = "https://files.pythonhosted.org/packages/2e/19/d7c972dfe90a353dbd3efbbe1d14a5951de80c99c9dc1b93cd998d51dc0f/numpy-2.3.1.tar.gz", hash = "sha256:1ec9ae20a4226da374362cca3c62cd753faf2f951440b0e3b98e93c235441d2b", size = 20390372 } -wheels = [ - { url = "https://files.pythonhosted.org/packages/b0/c7/87c64d7ab426156530676000c94784ef55676df2f13b2796f97722464124/numpy-2.3.1-cp311-cp311-macosx_10_9_x86_64.whl", hash = "sha256:6ea9e48336a402551f52cd8f593343699003d2353daa4b72ce8d34f66b722070", size = 21199346 }, - { url = "https://files.pythonhosted.org/packages/58/0e/0966c2f44beeac12af8d836e5b5f826a407cf34c45cb73ddcdfce9f5960b/numpy-2.3.1-cp311-cp311-macosx_11_0_arm64.whl", hash = "sha256:5ccb7336eaf0e77c1635b232c141846493a588ec9ea777a7c24d7166bb8533ae", size = 14361143 }, - { url = "https://files.pythonhosted.org/packages/7d/31/6e35a247acb1bfc19226791dfc7d4c30002cd4e620e11e58b0ddf836fe52/numpy-2.3.1-cp311-cp311-macosx_14_0_arm64.whl", hash = "sha256:0bb3a4a61e1d327e035275d2a993c96fa786e4913aa089843e6a2d9dd205c66a", size = 5378989 }, - { url = "https://files.pythonhosted.org/packages/b0/25/93b621219bb6f5a2d4e713a824522c69ab1f06a57cd571cda70e2e31af44/numpy-2.3.1-cp311-cp311-macosx_14_0_x86_64.whl", hash = "sha256:e344eb79dab01f1e838ebb67aab09965fb271d6da6b00adda26328ac27d4a66e", size = 6912890 }, - { url = "https://files.pythonhosted.org/packages/ef/60/6b06ed98d11fb32e27fb59468b42383f3877146d3ee639f733776b6ac596/numpy-2.3.1-cp311-cp311-manylinux_2_28_aarch64.whl", hash = "sha256:467db865b392168ceb1ef1ffa6f5a86e62468c43e0cfb4ab6da667ede10e58db", size = 14569032 }, - { url = "https://files.pythonhosted.org/packages/75/c9/9bec03675192077467a9c7c2bdd1f2e922bd01d3a69b15c3a0fdcd8548f6/numpy-2.3.1-cp311-cp311-manylinux_2_28_x86_64.whl", hash = "sha256:afed2ce4a84f6b0fc6c1ce734ff368cbf5a5e24e8954a338f3bdffa0718adffb", size = 16930354 }, - { url = "https://files.pythonhosted.org/packages/6a/e2/5756a00cabcf50a3f527a0c968b2b4881c62b1379223931853114fa04cda/numpy-2.3.1-cp311-cp311-musllinux_1_2_aarch64.whl", hash = "sha256:0025048b3c1557a20bc80d06fdeb8cc7fc193721484cca82b2cfa072fec71a93", size = 15879605 }, - { url = "https://files.pythonhosted.org/packages/ff/86/a471f65f0a86f1ca62dcc90b9fa46174dd48f50214e5446bc16a775646c5/numpy-2.3.1-cp311-cp311-musllinux_1_2_x86_64.whl", hash = "sha256:a5ee121b60aa509679b682819c602579e1df14a5b07fe95671c8849aad8f2115", size = 18666994 }, - { url = "https://files.pythonhosted.org/packages/43/a6/482a53e469b32be6500aaf61cfafd1de7a0b0d484babf679209c3298852e/numpy-2.3.1-cp311-cp311-win32.whl", hash = "sha256:a8b740f5579ae4585831b3cf0e3b0425c667274f82a484866d2adf9570539369", size = 6603672 }, - { url = "https://files.pythonhosted.org/packages/6b/fb/bb613f4122c310a13ec67585c70e14b03bfc7ebabd24f4d5138b97371d7c/numpy-2.3.1-cp311-cp311-win_amd64.whl", hash = "sha256:d4580adadc53311b163444f877e0789f1c8861e2698f6b2a4ca852fda154f3ff", size = 13024015 }, - { url = "https://files.pythonhosted.org/packages/51/58/2d842825af9a0c041aca246dc92eb725e1bc5e1c9ac89712625db0c4e11c/numpy-2.3.1-cp311-cp311-win_arm64.whl", hash = "sha256:ec0bdafa906f95adc9a0c6f26a4871fa753f25caaa0e032578a30457bff0af6a", size = 10456989 }, - { url = "https://files.pythonhosted.org/packages/c6/56/71ad5022e2f63cfe0ca93559403d0edef14aea70a841d640bd13cdba578e/numpy-2.3.1-cp312-cp312-macosx_10_13_x86_64.whl", hash = "sha256:2959d8f268f3d8ee402b04a9ec4bb7604555aeacf78b360dc4ec27f1d508177d", size = 20896664 }, - { url = "https://files.pythonhosted.org/packages/25/65/2db52ba049813670f7f987cc5db6dac9be7cd95e923cc6832b3d32d87cef/numpy-2.3.1-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:762e0c0c6b56bdedfef9a8e1d4538556438288c4276901ea008ae44091954e29", size = 14131078 }, - { url = "https://files.pythonhosted.org/packages/57/dd/28fa3c17b0e751047ac928c1e1b6990238faad76e9b147e585b573d9d1bd/numpy-2.3.1-cp312-cp312-macosx_14_0_arm64.whl", hash = "sha256:867ef172a0976aaa1f1d1b63cf2090de8b636a7674607d514505fb7276ab08fc", size = 5112554 }, - { url = "https://files.pythonhosted.org/packages/c9/fc/84ea0cba8e760c4644b708b6819d91784c290288c27aca916115e3311d17/numpy-2.3.1-cp312-cp312-macosx_14_0_x86_64.whl", hash = "sha256:4e602e1b8682c2b833af89ba641ad4176053aaa50f5cacda1a27004352dde943", size = 6646560 }, - { url = "https://files.pythonhosted.org/packages/61/b2/512b0c2ddec985ad1e496b0bd853eeb572315c0f07cd6997473ced8f15e2/numpy-2.3.1-cp312-cp312-manylinux_2_28_aarch64.whl", hash = "sha256:8e333040d069eba1652fb08962ec5b76af7f2c7bce1df7e1418c8055cf776f25", size = 14260638 }, - { url = "https://files.pythonhosted.org/packages/6e/45/c51cb248e679a6c6ab14b7a8e3ead3f4a3fe7425fc7a6f98b3f147bec532/numpy-2.3.1-cp312-cp312-manylinux_2_28_x86_64.whl", hash = "sha256:e7cbf5a5eafd8d230a3ce356d892512185230e4781a361229bd902ff403bc660", size = 16632729 }, - { url = "https://files.pythonhosted.org/packages/e4/ff/feb4be2e5c09a3da161b412019caf47183099cbea1132fd98061808c2df2/numpy-2.3.1-cp312-cp312-musllinux_1_2_aarch64.whl", hash = "sha256:5f1b8f26d1086835f442286c1d9b64bb3974b0b1e41bb105358fd07d20872952", size = 15565330 }, - { url = "https://files.pythonhosted.org/packages/bc/6d/ceafe87587101e9ab0d370e4f6e5f3f3a85b9a697f2318738e5e7e176ce3/numpy-2.3.1-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:ee8340cb48c9b7a5899d1149eece41ca535513a9698098edbade2a8e7a84da77", size = 18361734 }, - { url = "https://files.pythonhosted.org/packages/2b/19/0fb49a3ea088be691f040c9bf1817e4669a339d6e98579f91859b902c636/numpy-2.3.1-cp312-cp312-win32.whl", hash = "sha256:e772dda20a6002ef7061713dc1e2585bc1b534e7909b2030b5a46dae8ff077ab", size = 6320411 }, - { url = "https://files.pythonhosted.org/packages/b1/3e/e28f4c1dd9e042eb57a3eb652f200225e311b608632bc727ae378623d4f8/numpy-2.3.1-cp312-cp312-win_amd64.whl", hash = "sha256:cfecc7822543abdea6de08758091da655ea2210b8ffa1faf116b940693d3df76", size = 12734973 }, - { url = "https://files.pythonhosted.org/packages/04/a8/8a5e9079dc722acf53522b8f8842e79541ea81835e9b5483388701421073/numpy-2.3.1-cp312-cp312-win_arm64.whl", hash = "sha256:7be91b2239af2658653c5bb6f1b8bccafaf08226a258caf78ce44710a0160d30", size = 10191491 }, - { url = "https://files.pythonhosted.org/packages/d4/bd/35ad97006d8abff8631293f8ea6adf07b0108ce6fec68da3c3fcca1197f2/numpy-2.3.1-cp313-cp313-macosx_10_13_x86_64.whl", hash = "sha256:25a1992b0a3fdcdaec9f552ef10d8103186f5397ab45e2d25f8ac51b1a6b97e8", size = 20889381 }, - { url = "https://files.pythonhosted.org/packages/f1/4f/df5923874d8095b6062495b39729178eef4a922119cee32a12ee1bd4664c/numpy-2.3.1-cp313-cp313-macosx_11_0_arm64.whl", hash = "sha256:7dea630156d39b02a63c18f508f85010230409db5b2927ba59c8ba4ab3e8272e", size = 14152726 }, - { url = "https://files.pythonhosted.org/packages/8c/0f/a1f269b125806212a876f7efb049b06c6f8772cf0121139f97774cd95626/numpy-2.3.1-cp313-cp313-macosx_14_0_arm64.whl", hash = "sha256:bada6058dd886061f10ea15f230ccf7dfff40572e99fef440a4a857c8728c9c0", size = 5105145 }, - { url = "https://files.pythonhosted.org/packages/6d/63/a7f7fd5f375b0361682f6ffbf686787e82b7bbd561268e4f30afad2bb3c0/numpy-2.3.1-cp313-cp313-macosx_14_0_x86_64.whl", hash = "sha256:a894f3816eb17b29e4783e5873f92faf55b710c2519e5c351767c51f79d8526d", size = 6639409 }, - { url = "https://files.pythonhosted.org/packages/bf/0d/1854a4121af895aab383f4aa233748f1df4671ef331d898e32426756a8a6/numpy-2.3.1-cp313-cp313-manylinux_2_28_aarch64.whl", hash = "sha256:18703df6c4a4fee55fd3d6e5a253d01c5d33a295409b03fda0c86b3ca2ff41a1", size = 14257630 }, - { url = "https://files.pythonhosted.org/packages/50/30/af1b277b443f2fb08acf1c55ce9d68ee540043f158630d62cef012750f9f/numpy-2.3.1-cp313-cp313-manylinux_2_28_x86_64.whl", hash = "sha256:5902660491bd7a48b2ec16c23ccb9124b8abfd9583c5fdfa123fe6b421e03de1", size = 16627546 }, - { url = "https://files.pythonhosted.org/packages/6e/ec/3b68220c277e463095342d254c61be8144c31208db18d3fd8ef02712bcd6/numpy-2.3.1-cp313-cp313-musllinux_1_2_aarch64.whl", hash = "sha256:36890eb9e9d2081137bd78d29050ba63b8dab95dff7912eadf1185e80074b2a0", size = 15562538 }, - { url = "https://files.pythonhosted.org/packages/77/2b/4014f2bcc4404484021c74d4c5ee8eb3de7e3f7ac75f06672f8dcf85140a/numpy-2.3.1-cp313-cp313-musllinux_1_2_x86_64.whl", hash = "sha256:a780033466159c2270531e2b8ac063704592a0bc62ec4a1b991c7c40705eb0e8", size = 18360327 }, - { url = "https://files.pythonhosted.org/packages/40/8d/2ddd6c9b30fcf920837b8672f6c65590c7d92e43084c25fc65edc22e93ca/numpy-2.3.1-cp313-cp313-win32.whl", hash = "sha256:39bff12c076812595c3a306f22bfe49919c5513aa1e0e70fac756a0be7c2a2b8", size = 6312330 }, - { url = "https://files.pythonhosted.org/packages/dd/c8/beaba449925988d415efccb45bf977ff8327a02f655090627318f6398c7b/numpy-2.3.1-cp313-cp313-win_amd64.whl", hash = "sha256:8d5ee6eec45f08ce507a6570e06f2f879b374a552087a4179ea7838edbcbfa42", size = 12731565 }, - { url = "https://files.pythonhosted.org/packages/0b/c3/5c0c575d7ec78c1126998071f58facfc124006635da75b090805e642c62e/numpy-2.3.1-cp313-cp313-win_arm64.whl", hash = "sha256:0c4d9e0a8368db90f93bd192bfa771ace63137c3488d198ee21dfb8e7771916e", size = 10190262 }, - { url = "https://files.pythonhosted.org/packages/ea/19/a029cd335cf72f79d2644dcfc22d90f09caa86265cbbde3b5702ccef6890/numpy-2.3.1-cp313-cp313t-macosx_10_13_x86_64.whl", hash = "sha256:b0b5397374f32ec0649dd98c652a1798192042e715df918c20672c62fb52d4b8", size = 20987593 }, - { url = "https://files.pythonhosted.org/packages/25/91/8ea8894406209107d9ce19b66314194675d31761fe2cb3c84fe2eeae2f37/numpy-2.3.1-cp313-cp313t-macosx_11_0_arm64.whl", hash = "sha256:c5bdf2015ccfcee8253fb8be695516ac4457c743473a43290fd36eba6a1777eb", size = 14300523 }, - { url = "https://files.pythonhosted.org/packages/a6/7f/06187b0066eefc9e7ce77d5f2ddb4e314a55220ad62dd0bfc9f2c44bac14/numpy-2.3.1-cp313-cp313t-macosx_14_0_arm64.whl", hash = "sha256:d70f20df7f08b90a2062c1f07737dd340adccf2068d0f1b9b3d56e2038979fee", size = 5227993 }, - { url = "https://files.pythonhosted.org/packages/e8/ec/a926c293c605fa75e9cfb09f1e4840098ed46d2edaa6e2152ee35dc01ed3/numpy-2.3.1-cp313-cp313t-macosx_14_0_x86_64.whl", hash = "sha256:2fb86b7e58f9ac50e1e9dd1290154107e47d1eef23a0ae9145ded06ea606f992", size = 6736652 }, - { url = "https://files.pythonhosted.org/packages/e3/62/d68e52fb6fde5586650d4c0ce0b05ff3a48ad4df4ffd1b8866479d1d671d/numpy-2.3.1-cp313-cp313t-manylinux_2_28_aarch64.whl", hash = "sha256:23ab05b2d241f76cb883ce8b9a93a680752fbfcbd51c50eff0b88b979e471d8c", size = 14331561 }, - { url = "https://files.pythonhosted.org/packages/fc/ec/b74d3f2430960044bdad6900d9f5edc2dc0fb8bf5a0be0f65287bf2cbe27/numpy-2.3.1-cp313-cp313t-manylinux_2_28_x86_64.whl", hash = "sha256:ce2ce9e5de4703a673e705183f64fd5da5bf36e7beddcb63a25ee2286e71ca48", size = 16693349 }, - { url = "https://files.pythonhosted.org/packages/0d/15/def96774b9d7eb198ddadfcbd20281b20ebb510580419197e225f5c55c3e/numpy-2.3.1-cp313-cp313t-musllinux_1_2_aarch64.whl", hash = "sha256:c4913079974eeb5c16ccfd2b1f09354b8fed7e0d6f2cab933104a09a6419b1ee", size = 15642053 }, - { url = "https://files.pythonhosted.org/packages/2b/57/c3203974762a759540c6ae71d0ea2341c1fa41d84e4971a8e76d7141678a/numpy-2.3.1-cp313-cp313t-musllinux_1_2_x86_64.whl", hash = "sha256:010ce9b4f00d5c036053ca684c77441f2f2c934fd23bee058b4d6f196efd8280", size = 18434184 }, - { url = "https://files.pythonhosted.org/packages/22/8a/ccdf201457ed8ac6245187850aff4ca56a79edbea4829f4e9f14d46fa9a5/numpy-2.3.1-cp313-cp313t-win32.whl", hash = "sha256:6269b9edfe32912584ec496d91b00b6d34282ca1d07eb10e82dfc780907d6c2e", size = 6440678 }, - { url = "https://files.pythonhosted.org/packages/f1/7e/7f431d8bd8eb7e03d79294aed238b1b0b174b3148570d03a8a8a8f6a0da9/numpy-2.3.1-cp313-cp313t-win_amd64.whl", hash = "sha256:2a809637460e88a113e186e87f228d74ae2852a2e0c44de275263376f17b5bdc", size = 12870697 }, - { url = "https://files.pythonhosted.org/packages/d4/ca/af82bf0fad4c3e573c6930ed743b5308492ff19917c7caaf2f9b6f9e2e98/numpy-2.3.1-cp313-cp313t-win_arm64.whl", hash = "sha256:eccb9a159db9aed60800187bc47a6d3451553f0e1b08b068d8b277ddfbb9b244", size = 10260376 }, - { url = "https://files.pythonhosted.org/packages/e8/34/facc13b9b42ddca30498fc51f7f73c3d0f2be179943a4b4da8686e259740/numpy-2.3.1-pp311-pypy311_pp73-macosx_10_15_x86_64.whl", hash = "sha256:ad506d4b09e684394c42c966ec1527f6ebc25da7f4da4b1b056606ffe446b8a3", size = 21070637 }, - { url = "https://files.pythonhosted.org/packages/65/b6/41b705d9dbae04649b529fc9bd3387664c3281c7cd78b404a4efe73dcc45/numpy-2.3.1-pp311-pypy311_pp73-macosx_14_0_arm64.whl", hash = "sha256:ebb8603d45bc86bbd5edb0d63e52c5fd9e7945d3a503b77e486bd88dde67a19b", size = 5304087 }, - { url = "https://files.pythonhosted.org/packages/7a/b4/fe3ac1902bff7a4934a22d49e1c9d71a623204d654d4cc43c6e8fe337fcb/numpy-2.3.1-pp311-pypy311_pp73-macosx_14_0_x86_64.whl", hash = "sha256:15aa4c392ac396e2ad3d0a2680c0f0dee420f9fed14eef09bdb9450ee6dcb7b7", size = 6817588 }, - { url = "https://files.pythonhosted.org/packages/ae/ee/89bedf69c36ace1ac8f59e97811c1f5031e179a37e4821c3a230bf750142/numpy-2.3.1-pp311-pypy311_pp73-manylinux_2_28_aarch64.whl", hash = "sha256:c6e0bf9d1a2f50d2b65a7cf56db37c095af17b59f6c132396f7c6d5dd76484df", size = 14399010 }, - { url = "https://files.pythonhosted.org/packages/15/08/e00e7070ede29b2b176165eba18d6f9784d5349be3c0c1218338e79c27fd/numpy-2.3.1-pp311-pypy311_pp73-manylinux_2_28_x86_64.whl", hash = "sha256:eabd7e8740d494ce2b4ea0ff05afa1b7b291e978c0ae075487c51e8bd93c0c68", size = 16752042 }, - { url = "https://files.pythonhosted.org/packages/48/6b/1c6b515a83d5564b1698a61efa245727c8feecf308f4091f565988519d20/numpy-2.3.1-pp311-pypy311_pp73-win_amd64.whl", hash = "sha256:e610832418a2bc09d974cc9fecebfa51e9532d6190223bc5ef6a7402ebf3b5cb", size = 12927246 }, +sdist = { url = "https://files.pythonhosted.org/packages/d0/19/95b3d357407220ed24c139018d2518fab0a61a948e68286a25f1a4d049ff/numpy-2.3.3.tar.gz", hash = "sha256:ddc7c39727ba62b80dfdbedf400d1c10ddfa8eefbd7ec8dcb118be8b56d31029", size = 20576648, upload-time = "2025-09-09T16:54:12.543Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/7a/45/e80d203ef6b267aa29b22714fb558930b27960a0c5ce3c19c999232bb3eb/numpy-2.3.3-cp311-cp311-macosx_10_9_x86_64.whl", hash = "sha256:0ffc4f5caba7dfcbe944ed674b7eef683c7e94874046454bb79ed7ee0236f59d", size = 21259253, upload-time = "2025-09-09T15:56:02.094Z" }, + { url = "https://files.pythonhosted.org/packages/52/18/cf2c648fccf339e59302e00e5f2bc87725a3ce1992f30f3f78c9044d7c43/numpy-2.3.3-cp311-cp311-macosx_11_0_arm64.whl", hash = "sha256:e7e946c7170858a0295f79a60214424caac2ffdb0063d4d79cb681f9aa0aa569", size = 14450980, upload-time = "2025-09-09T15:56:05.926Z" }, + { url = "https://files.pythonhosted.org/packages/93/fb/9af1082bec870188c42a1c239839915b74a5099c392389ff04215dcee812/numpy-2.3.3-cp311-cp311-macosx_14_0_arm64.whl", hash = "sha256:cd4260f64bc794c3390a63bf0728220dd1a68170c169088a1e0dfa2fde1be12f", size = 5379709, upload-time = "2025-09-09T15:56:07.95Z" }, + { url = "https://files.pythonhosted.org/packages/75/0f/bfd7abca52bcbf9a4a65abc83fe18ef01ccdeb37bfb28bbd6ad613447c79/numpy-2.3.3-cp311-cp311-macosx_14_0_x86_64.whl", hash = "sha256:f0ddb4b96a87b6728df9362135e764eac3cfa674499943ebc44ce96c478ab125", size = 6913923, upload-time = "2025-09-09T15:56:09.443Z" }, + { url = "https://files.pythonhosted.org/packages/79/55/d69adad255e87ab7afda1caf93ca997859092afeb697703e2f010f7c2e55/numpy-2.3.3-cp311-cp311-manylinux_2_27_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:afd07d377f478344ec6ca2b8d4ca08ae8bd44706763d1efb56397de606393f48", size = 14589591, upload-time = "2025-09-09T15:56:11.234Z" }, + { url = "https://files.pythonhosted.org/packages/10/a2/010b0e27ddeacab7839957d7a8f00e91206e0c2c47abbb5f35a2630e5387/numpy-2.3.3-cp311-cp311-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:bc92a5dedcc53857249ca51ef29f5e5f2f8c513e22cfb90faeb20343b8c6f7a6", size = 16938714, upload-time = "2025-09-09T15:56:14.637Z" }, + { url = "https://files.pythonhosted.org/packages/1c/6b/12ce8ede632c7126eb2762b9e15e18e204b81725b81f35176eac14dc5b82/numpy-2.3.3-cp311-cp311-musllinux_1_2_aarch64.whl", hash = "sha256:7af05ed4dc19f308e1d9fc759f36f21921eb7bbfc82843eeec6b2a2863a0aefa", size = 16370592, upload-time = "2025-09-09T15:56:17.285Z" }, + { url = "https://files.pythonhosted.org/packages/b4/35/aba8568b2593067bb6a8fe4c52babb23b4c3b9c80e1b49dff03a09925e4a/numpy-2.3.3-cp311-cp311-musllinux_1_2_x86_64.whl", hash = "sha256:433bf137e338677cebdd5beac0199ac84712ad9d630b74eceeb759eaa45ddf30", size = 18884474, upload-time = "2025-09-09T15:56:20.943Z" }, + { url = "https://files.pythonhosted.org/packages/45/fa/7f43ba10c77575e8be7b0138d107e4f44ca4a1ef322cd16980ea3e8b8222/numpy-2.3.3-cp311-cp311-win32.whl", hash = "sha256:eb63d443d7b4ffd1e873f8155260d7f58e7e4b095961b01c91062935c2491e57", size = 6599794, upload-time = "2025-09-09T15:56:23.258Z" }, + { url = "https://files.pythonhosted.org/packages/0a/a2/a4f78cb2241fe5664a22a10332f2be886dcdea8784c9f6a01c272da9b426/numpy-2.3.3-cp311-cp311-win_amd64.whl", hash = "sha256:ec9d249840f6a565f58d8f913bccac2444235025bbb13e9a4681783572ee3caa", size = 13088104, upload-time = "2025-09-09T15:56:25.476Z" }, + { url = "https://files.pythonhosted.org/packages/79/64/e424e975adbd38282ebcd4891661965b78783de893b381cbc4832fb9beb2/numpy-2.3.3-cp311-cp311-win_arm64.whl", hash = "sha256:74c2a948d02f88c11a3c075d9733f1ae67d97c6bdb97f2bb542f980458b257e7", size = 10460772, upload-time = "2025-09-09T15:56:27.679Z" }, + { url = "https://files.pythonhosted.org/packages/51/5d/bb7fc075b762c96329147799e1bcc9176ab07ca6375ea976c475482ad5b3/numpy-2.3.3-cp312-cp312-macosx_10_13_x86_64.whl", hash = "sha256:cfdd09f9c84a1a934cde1eec2267f0a43a7cd44b2cca4ff95b7c0d14d144b0bf", size = 20957014, upload-time = "2025-09-09T15:56:29.966Z" }, + { url = "https://files.pythonhosted.org/packages/6b/0e/c6211bb92af26517acd52125a237a92afe9c3124c6a68d3b9f81b62a0568/numpy-2.3.3-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:cb32e3cf0f762aee47ad1ddc6672988f7f27045b0783c887190545baba73aa25", size = 14185220, upload-time = "2025-09-09T15:56:32.175Z" }, + { url = "https://files.pythonhosted.org/packages/22/f2/07bb754eb2ede9073f4054f7c0286b0d9d2e23982e090a80d478b26d35ca/numpy-2.3.3-cp312-cp312-macosx_14_0_arm64.whl", hash = "sha256:396b254daeb0a57b1fe0ecb5e3cff6fa79a380fa97c8f7781a6d08cd429418fe", size = 5113918, upload-time = "2025-09-09T15:56:34.175Z" }, + { url = "https://files.pythonhosted.org/packages/81/0a/afa51697e9fb74642f231ea36aca80fa17c8fb89f7a82abd5174023c3960/numpy-2.3.3-cp312-cp312-macosx_14_0_x86_64.whl", hash = "sha256:067e3d7159a5d8f8a0b46ee11148fc35ca9b21f61e3c49fbd0a027450e65a33b", size = 6647922, upload-time = "2025-09-09T15:56:36.149Z" }, + { url = "https://files.pythonhosted.org/packages/5d/f5/122d9cdb3f51c520d150fef6e87df9279e33d19a9611a87c0d2cf78a89f4/numpy-2.3.3-cp312-cp312-manylinux_2_27_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:1c02d0629d25d426585fb2e45a66154081b9fa677bc92a881ff1d216bc9919a8", size = 14281991, upload-time = "2025-09-09T15:56:40.548Z" }, + { url = "https://files.pythonhosted.org/packages/51/64/7de3c91e821a2debf77c92962ea3fe6ac2bc45d0778c1cbe15d4fce2fd94/numpy-2.3.3-cp312-cp312-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:d9192da52b9745f7f0766531dcfa978b7763916f158bb63bdb8a1eca0068ab20", size = 16641643, upload-time = "2025-09-09T15:56:43.343Z" }, + { url = "https://files.pythonhosted.org/packages/30/e4/961a5fa681502cd0d68907818b69f67542695b74e3ceaa513918103b7e80/numpy-2.3.3-cp312-cp312-musllinux_1_2_aarch64.whl", hash = "sha256:cd7de500a5b66319db419dc3c345244404a164beae0d0937283b907d8152e6ea", size = 16056787, upload-time = "2025-09-09T15:56:46.141Z" }, + { url = "https://files.pythonhosted.org/packages/99/26/92c912b966e47fbbdf2ad556cb17e3a3088e2e1292b9833be1dfa5361a1a/numpy-2.3.3-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:93d4962d8f82af58f0b2eb85daaf1b3ca23fe0a85d0be8f1f2b7bb46034e56d7", size = 18579598, upload-time = "2025-09-09T15:56:49.844Z" }, + { url = "https://files.pythonhosted.org/packages/17/b6/fc8f82cb3520768718834f310c37d96380d9dc61bfdaf05fe5c0b7653e01/numpy-2.3.3-cp312-cp312-win32.whl", hash = "sha256:5534ed6b92f9b7dca6c0a19d6df12d41c68b991cef051d108f6dbff3babc4ebf", size = 6320800, upload-time = "2025-09-09T15:56:52.499Z" }, + { url = "https://files.pythonhosted.org/packages/32/ee/de999f2625b80d043d6d2d628c07d0d5555a677a3cf78fdf868d409b8766/numpy-2.3.3-cp312-cp312-win_amd64.whl", hash = "sha256:497d7cad08e7092dba36e3d296fe4c97708c93daf26643a1ae4b03f6294d30eb", size = 12786615, upload-time = "2025-09-09T15:56:54.422Z" }, + { url = "https://files.pythonhosted.org/packages/49/6e/b479032f8a43559c383acb20816644f5f91c88f633d9271ee84f3b3a996c/numpy-2.3.3-cp312-cp312-win_arm64.whl", hash = "sha256:ca0309a18d4dfea6fc6262a66d06c26cfe4640c3926ceec90e57791a82b6eee5", size = 10195936, upload-time = "2025-09-09T15:56:56.541Z" }, + { url = "https://files.pythonhosted.org/packages/7d/b9/984c2b1ee61a8b803bf63582b4ac4242cf76e2dbd663efeafcb620cc0ccb/numpy-2.3.3-cp313-cp313-macosx_10_13_x86_64.whl", hash = "sha256:f5415fb78995644253370985342cd03572ef8620b934da27d77377a2285955bf", size = 20949588, upload-time = "2025-09-09T15:56:59.087Z" }, + { url = "https://files.pythonhosted.org/packages/a6/e4/07970e3bed0b1384d22af1e9912527ecbeb47d3b26e9b6a3bced068b3bea/numpy-2.3.3-cp313-cp313-macosx_11_0_arm64.whl", hash = "sha256:d00de139a3324e26ed5b95870ce63be7ec7352171bc69a4cf1f157a48e3eb6b7", size = 14177802, upload-time = "2025-09-09T15:57:01.73Z" }, + { url = "https://files.pythonhosted.org/packages/35/c7/477a83887f9de61f1203bad89cf208b7c19cc9fef0cebef65d5a1a0619f2/numpy-2.3.3-cp313-cp313-macosx_14_0_arm64.whl", hash = "sha256:9dc13c6a5829610cc07422bc74d3ac083bd8323f14e2827d992f9e52e22cd6a6", size = 5106537, upload-time = "2025-09-09T15:57:03.765Z" }, + { url = "https://files.pythonhosted.org/packages/52/47/93b953bd5866a6f6986344d045a207d3f1cfbad99db29f534ea9cee5108c/numpy-2.3.3-cp313-cp313-macosx_14_0_x86_64.whl", hash = "sha256:d79715d95f1894771eb4e60fb23f065663b2298f7d22945d66877aadf33d00c7", size = 6640743, upload-time = "2025-09-09T15:57:07.921Z" }, + { url = "https://files.pythonhosted.org/packages/23/83/377f84aaeb800b64c0ef4de58b08769e782edcefa4fea712910b6f0afd3c/numpy-2.3.3-cp313-cp313-manylinux_2_27_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:952cfd0748514ea7c3afc729a0fc639e61655ce4c55ab9acfab14bda4f402b4c", size = 14278881, upload-time = "2025-09-09T15:57:11.349Z" }, + { url = "https://files.pythonhosted.org/packages/9a/a5/bf3db6e66c4b160d6ea10b534c381a1955dfab34cb1017ea93aa33c70ed3/numpy-2.3.3-cp313-cp313-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:5b83648633d46f77039c29078751f80da65aa64d5622a3cd62aaef9d835b6c93", size = 16636301, upload-time = "2025-09-09T15:57:14.245Z" }, + { url = "https://files.pythonhosted.org/packages/a2/59/1287924242eb4fa3f9b3a2c30400f2e17eb2707020d1c5e3086fe7330717/numpy-2.3.3-cp313-cp313-musllinux_1_2_aarch64.whl", hash = "sha256:b001bae8cea1c7dfdb2ae2b017ed0a6f2102d7a70059df1e338e307a4c78a8ae", size = 16053645, upload-time = "2025-09-09T15:57:16.534Z" }, + { url = "https://files.pythonhosted.org/packages/e6/93/b3d47ed882027c35e94ac2320c37e452a549f582a5e801f2d34b56973c97/numpy-2.3.3-cp313-cp313-musllinux_1_2_x86_64.whl", hash = "sha256:8e9aced64054739037d42fb84c54dd38b81ee238816c948c8f3ed134665dcd86", size = 18578179, upload-time = "2025-09-09T15:57:18.883Z" }, + { url = "https://files.pythonhosted.org/packages/20/d9/487a2bccbf7cc9d4bfc5f0f197761a5ef27ba870f1e3bbb9afc4bbe3fcc2/numpy-2.3.3-cp313-cp313-win32.whl", hash = "sha256:9591e1221db3f37751e6442850429b3aabf7026d3b05542d102944ca7f00c8a8", size = 6312250, upload-time = "2025-09-09T15:57:21.296Z" }, + { url = "https://files.pythonhosted.org/packages/1b/b5/263ebbbbcede85028f30047eab3d58028d7ebe389d6493fc95ae66c636ab/numpy-2.3.3-cp313-cp313-win_amd64.whl", hash = "sha256:f0dadeb302887f07431910f67a14d57209ed91130be0adea2f9793f1a4f817cf", size = 12783269, upload-time = "2025-09-09T15:57:23.034Z" }, + { url = "https://files.pythonhosted.org/packages/fa/75/67b8ca554bbeaaeb3fac2e8bce46967a5a06544c9108ec0cf5cece559b6c/numpy-2.3.3-cp313-cp313-win_arm64.whl", hash = "sha256:3c7cf302ac6e0b76a64c4aecf1a09e51abd9b01fc7feee80f6c43e3ab1b1dbc5", size = 10195314, upload-time = "2025-09-09T15:57:25.045Z" }, + { url = "https://files.pythonhosted.org/packages/11/d0/0d1ddec56b162042ddfafeeb293bac672de9b0cfd688383590090963720a/numpy-2.3.3-cp313-cp313t-macosx_10_13_x86_64.whl", hash = "sha256:eda59e44957d272846bb407aad19f89dc6f58fecf3504bd144f4c5cf81a7eacc", size = 21048025, upload-time = "2025-09-09T15:57:27.257Z" }, + { url = "https://files.pythonhosted.org/packages/36/9e/1996ca6b6d00415b6acbdd3c42f7f03ea256e2c3f158f80bd7436a8a19f3/numpy-2.3.3-cp313-cp313t-macosx_11_0_arm64.whl", hash = "sha256:823d04112bc85ef5c4fda73ba24e6096c8f869931405a80aa8b0e604510a26bc", size = 14301053, upload-time = "2025-09-09T15:57:30.077Z" }, + { url = "https://files.pythonhosted.org/packages/05/24/43da09aa764c68694b76e84b3d3f0c44cb7c18cdc1ba80e48b0ac1d2cd39/numpy-2.3.3-cp313-cp313t-macosx_14_0_arm64.whl", hash = "sha256:40051003e03db4041aa325da2a0971ba41cf65714e65d296397cc0e32de6018b", size = 5229444, upload-time = "2025-09-09T15:57:32.733Z" }, + { url = "https://files.pythonhosted.org/packages/bc/14/50ffb0f22f7218ef8af28dd089f79f68289a7a05a208db9a2c5dcbe123c1/numpy-2.3.3-cp313-cp313t-macosx_14_0_x86_64.whl", hash = "sha256:6ee9086235dd6ab7ae75aba5662f582a81ced49f0f1c6de4260a78d8f2d91a19", size = 6738039, upload-time = "2025-09-09T15:57:34.328Z" }, + { url = "https://files.pythonhosted.org/packages/55/52/af46ac0795e09657d45a7f4db961917314377edecf66db0e39fa7ab5c3d3/numpy-2.3.3-cp313-cp313t-manylinux_2_27_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:94fcaa68757c3e2e668ddadeaa86ab05499a70725811e582b6a9858dd472fb30", size = 14352314, upload-time = "2025-09-09T15:57:36.255Z" }, + { url = "https://files.pythonhosted.org/packages/a7/b1/dc226b4c90eb9f07a3fff95c2f0db3268e2e54e5cce97c4ac91518aee71b/numpy-2.3.3-cp313-cp313t-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:da1a74b90e7483d6ce5244053399a614b1d6b7bc30a60d2f570e5071f8959d3e", size = 16701722, upload-time = "2025-09-09T15:57:38.622Z" }, + { url = "https://files.pythonhosted.org/packages/9d/9d/9d8d358f2eb5eced14dba99f110d83b5cd9a4460895230f3b396ad19a323/numpy-2.3.3-cp313-cp313t-musllinux_1_2_aarch64.whl", hash = "sha256:2990adf06d1ecee3b3dcbb4977dfab6e9f09807598d647f04d385d29e7a3c3d3", size = 16132755, upload-time = "2025-09-09T15:57:41.16Z" }, + { url = "https://files.pythonhosted.org/packages/b6/27/b3922660c45513f9377b3fb42240bec63f203c71416093476ec9aa0719dc/numpy-2.3.3-cp313-cp313t-musllinux_1_2_x86_64.whl", hash = "sha256:ed635ff692483b8e3f0fcaa8e7eb8a75ee71aa6d975388224f70821421800cea", size = 18651560, upload-time = "2025-09-09T15:57:43.459Z" }, + { url = "https://files.pythonhosted.org/packages/5b/8e/3ab61a730bdbbc201bb245a71102aa609f0008b9ed15255500a99cd7f780/numpy-2.3.3-cp313-cp313t-win32.whl", hash = "sha256:a333b4ed33d8dc2b373cc955ca57babc00cd6f9009991d9edc5ddbc1bac36bcd", size = 6442776, upload-time = "2025-09-09T15:57:45.793Z" }, + { url = "https://files.pythonhosted.org/packages/1c/3a/e22b766b11f6030dc2decdeff5c2fb1610768055603f9f3be88b6d192fb2/numpy-2.3.3-cp313-cp313t-win_amd64.whl", hash = "sha256:4384a169c4d8f97195980815d6fcad04933a7e1ab3b530921c3fef7a1c63426d", size = 12927281, upload-time = "2025-09-09T15:57:47.492Z" }, + { url = "https://files.pythonhosted.org/packages/7b/42/c2e2bc48c5e9b2a83423f99733950fbefd86f165b468a3d85d52b30bf782/numpy-2.3.3-cp313-cp313t-win_arm64.whl", hash = "sha256:75370986cc0bc66f4ce5110ad35aae6d182cc4ce6433c40ad151f53690130bf1", size = 10265275, upload-time = "2025-09-09T15:57:49.647Z" }, + { url = "https://files.pythonhosted.org/packages/6b/01/342ad585ad82419b99bcf7cebe99e61da6bedb89e213c5fd71acc467faee/numpy-2.3.3-cp314-cp314-macosx_10_13_x86_64.whl", hash = "sha256:cd052f1fa6a78dee696b58a914b7229ecfa41f0a6d96dc663c1220a55e137593", size = 20951527, upload-time = "2025-09-09T15:57:52.006Z" }, + { url = "https://files.pythonhosted.org/packages/ef/d8/204e0d73fc1b7a9ee80ab1fe1983dd33a4d64a4e30a05364b0208e9a241a/numpy-2.3.3-cp314-cp314-macosx_11_0_arm64.whl", hash = "sha256:414a97499480067d305fcac9716c29cf4d0d76db6ebf0bf3cbce666677f12652", size = 14186159, upload-time = "2025-09-09T15:57:54.407Z" }, + { url = "https://files.pythonhosted.org/packages/22/af/f11c916d08f3a18fb8ba81ab72b5b74a6e42ead4c2846d270eb19845bf74/numpy-2.3.3-cp314-cp314-macosx_14_0_arm64.whl", hash = "sha256:50a5fe69f135f88a2be9b6ca0481a68a136f6febe1916e4920e12f1a34e708a7", size = 5114624, upload-time = "2025-09-09T15:57:56.5Z" }, + { url = "https://files.pythonhosted.org/packages/fb/11/0ed919c8381ac9d2ffacd63fd1f0c34d27e99cab650f0eb6f110e6ae4858/numpy-2.3.3-cp314-cp314-macosx_14_0_x86_64.whl", hash = "sha256:b912f2ed2b67a129e6a601e9d93d4fa37bef67e54cac442a2f588a54afe5c67a", size = 6642627, upload-time = "2025-09-09T15:57:58.206Z" }, + { url = "https://files.pythonhosted.org/packages/ee/83/deb5f77cb0f7ba6cb52b91ed388b47f8f3c2e9930d4665c600408d9b90b9/numpy-2.3.3-cp314-cp314-manylinux_2_27_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:9e318ee0596d76d4cb3d78535dc005fa60e5ea348cd131a51e99d0bdbe0b54fe", size = 14296926, upload-time = "2025-09-09T15:58:00.035Z" }, + { url = "https://files.pythonhosted.org/packages/77/cc/70e59dcb84f2b005d4f306310ff0a892518cc0c8000a33d0e6faf7ca8d80/numpy-2.3.3-cp314-cp314-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:ce020080e4a52426202bdb6f7691c65bb55e49f261f31a8f506c9f6bc7450421", size = 16638958, upload-time = "2025-09-09T15:58:02.738Z" }, + { url = "https://files.pythonhosted.org/packages/b6/5a/b2ab6c18b4257e099587d5b7f903317bd7115333ad8d4ec4874278eafa61/numpy-2.3.3-cp314-cp314-musllinux_1_2_aarch64.whl", hash = "sha256:e6687dc183aa55dae4a705b35f9c0f8cb178bcaa2f029b241ac5356221d5c021", size = 16071920, upload-time = "2025-09-09T15:58:05.029Z" }, + { url = "https://files.pythonhosted.org/packages/b8/f1/8b3fdc44324a259298520dd82147ff648979bed085feeacc1250ef1656c0/numpy-2.3.3-cp314-cp314-musllinux_1_2_x86_64.whl", hash = "sha256:d8f3b1080782469fdc1718c4ed1d22549b5fb12af0d57d35e992158a772a37cf", size = 18577076, upload-time = "2025-09-09T15:58:07.745Z" }, + { url = "https://files.pythonhosted.org/packages/f0/a1/b87a284fb15a42e9274e7fcea0dad259d12ddbf07c1595b26883151ca3b4/numpy-2.3.3-cp314-cp314-win32.whl", hash = "sha256:cb248499b0bc3be66ebd6578b83e5acacf1d6cb2a77f2248ce0e40fbec5a76d0", size = 6366952, upload-time = "2025-09-09T15:58:10.096Z" }, + { url = "https://files.pythonhosted.org/packages/70/5f/1816f4d08f3b8f66576d8433a66f8fa35a5acfb3bbd0bf6c31183b003f3d/numpy-2.3.3-cp314-cp314-win_amd64.whl", hash = "sha256:691808c2b26b0f002a032c73255d0bd89751425f379f7bcd22d140db593a96e8", size = 12919322, upload-time = "2025-09-09T15:58:12.138Z" }, + { url = "https://files.pythonhosted.org/packages/8c/de/072420342e46a8ea41c324a555fa90fcc11637583fb8df722936aed1736d/numpy-2.3.3-cp314-cp314-win_arm64.whl", hash = "sha256:9ad12e976ca7b10f1774b03615a2a4bab8addce37ecc77394d8e986927dc0dfe", size = 10478630, upload-time = "2025-09-09T15:58:14.64Z" }, + { url = "https://files.pythonhosted.org/packages/d5/df/ee2f1c0a9de7347f14da5dd3cd3c3b034d1b8607ccb6883d7dd5c035d631/numpy-2.3.3-cp314-cp314t-macosx_10_13_x86_64.whl", hash = "sha256:9cc48e09feb11e1db00b320e9d30a4151f7369afb96bd0e48d942d09da3a0d00", size = 21047987, upload-time = "2025-09-09T15:58:16.889Z" }, + { url = "https://files.pythonhosted.org/packages/d6/92/9453bdc5a4e9e69cf4358463f25e8260e2ffc126d52e10038b9077815989/numpy-2.3.3-cp314-cp314t-macosx_11_0_arm64.whl", hash = "sha256:901bf6123879b7f251d3631967fd574690734236075082078e0571977c6a8e6a", size = 14301076, upload-time = "2025-09-09T15:58:20.343Z" }, + { url = "https://files.pythonhosted.org/packages/13/77/1447b9eb500f028bb44253105bd67534af60499588a5149a94f18f2ca917/numpy-2.3.3-cp314-cp314t-macosx_14_0_arm64.whl", hash = "sha256:7f025652034199c301049296b59fa7d52c7e625017cae4c75d8662e377bf487d", size = 5229491, upload-time = "2025-09-09T15:58:22.481Z" }, + { url = "https://files.pythonhosted.org/packages/3d/f9/d72221b6ca205f9736cb4b2ce3b002f6e45cd67cd6a6d1c8af11a2f0b649/numpy-2.3.3-cp314-cp314t-macosx_14_0_x86_64.whl", hash = "sha256:533ca5f6d325c80b6007d4d7fb1984c303553534191024ec6a524a4c92a5935a", size = 6737913, upload-time = "2025-09-09T15:58:24.569Z" }, + { url = "https://files.pythonhosted.org/packages/3c/5f/d12834711962ad9c46af72f79bb31e73e416ee49d17f4c797f72c96b6ca5/numpy-2.3.3-cp314-cp314t-manylinux_2_27_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:0edd58682a399824633b66885d699d7de982800053acf20be1eaa46d92009c54", size = 14352811, upload-time = "2025-09-09T15:58:26.416Z" }, + { url = "https://files.pythonhosted.org/packages/a1/0d/fdbec6629d97fd1bebed56cd742884e4eead593611bbe1abc3eb40d304b2/numpy-2.3.3-cp314-cp314t-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:367ad5d8fbec5d9296d18478804a530f1191e24ab4d75ab408346ae88045d25e", size = 16702689, upload-time = "2025-09-09T15:58:28.831Z" }, + { url = "https://files.pythonhosted.org/packages/9b/09/0a35196dc5575adde1eb97ddfbc3e1687a814f905377621d18ca9bc2b7dd/numpy-2.3.3-cp314-cp314t-musllinux_1_2_aarch64.whl", hash = "sha256:8f6ac61a217437946a1fa48d24c47c91a0c4f725237871117dea264982128097", size = 16133855, upload-time = "2025-09-09T15:58:31.349Z" }, + { url = "https://files.pythonhosted.org/packages/7a/ca/c9de3ea397d576f1b6753eaa906d4cdef1bf97589a6d9825a349b4729cc2/numpy-2.3.3-cp314-cp314t-musllinux_1_2_x86_64.whl", hash = "sha256:179a42101b845a816d464b6fe9a845dfaf308fdfc7925387195570789bb2c970", size = 18652520, upload-time = "2025-09-09T15:58:33.762Z" }, + { url = "https://files.pythonhosted.org/packages/fd/c2/e5ed830e08cd0196351db55db82f65bc0ab05da6ef2b72a836dcf1936d2f/numpy-2.3.3-cp314-cp314t-win32.whl", hash = "sha256:1250c5d3d2562ec4174bce2e3a1523041595f9b651065e4a4473f5f48a6bc8a5", size = 6515371, upload-time = "2025-09-09T15:58:36.04Z" }, + { url = "https://files.pythonhosted.org/packages/47/c7/b0f6b5b67f6788a0725f744496badbb604d226bf233ba716683ebb47b570/numpy-2.3.3-cp314-cp314t-win_amd64.whl", hash = "sha256:b37a0b2e5935409daebe82c1e42274d30d9dd355852529eab91dab8dcca7419f", size = 13112576, upload-time = "2025-09-09T15:58:37.927Z" }, + { url = "https://files.pythonhosted.org/packages/06/b9/33bba5ff6fb679aa0b1f8a07e853f002a6b04b9394db3069a1270a7784ca/numpy-2.3.3-cp314-cp314t-win_arm64.whl", hash = "sha256:78c9f6560dc7e6b3990e32df7ea1a50bbd0e2a111e05209963f5ddcab7073b0b", size = 10545953, upload-time = "2025-09-09T15:58:40.576Z" }, + { url = "https://files.pythonhosted.org/packages/b8/f2/7e0a37cfced2644c9563c529f29fa28acbd0960dde32ece683aafa6f4949/numpy-2.3.3-pp311-pypy311_pp73-macosx_10_15_x86_64.whl", hash = "sha256:1e02c7159791cd481e1e6d5ddd766b62a4d5acf8df4d4d1afe35ee9c5c33a41e", size = 21131019, upload-time = "2025-09-09T15:58:42.838Z" }, + { url = "https://files.pythonhosted.org/packages/1a/7e/3291f505297ed63831135a6cc0f474da0c868a1f31b0dd9a9f03a7a0d2ed/numpy-2.3.3-pp311-pypy311_pp73-macosx_11_0_arm64.whl", hash = "sha256:dca2d0fc80b3893ae72197b39f69d55a3cd8b17ea1b50aa4c62de82419936150", size = 14376288, upload-time = "2025-09-09T15:58:45.425Z" }, + { url = "https://files.pythonhosted.org/packages/bf/4b/ae02e985bdeee73d7b5abdefeb98aef1207e96d4c0621ee0cf228ddfac3c/numpy-2.3.3-pp311-pypy311_pp73-macosx_14_0_arm64.whl", hash = "sha256:99683cbe0658f8271b333a1b1b4bb3173750ad59c0c61f5bbdc5b318918fffe3", size = 5305425, upload-time = "2025-09-09T15:58:48.6Z" }, + { url = "https://files.pythonhosted.org/packages/8b/eb/9df215d6d7250db32007941500dc51c48190be25f2401d5b2b564e467247/numpy-2.3.3-pp311-pypy311_pp73-macosx_14_0_x86_64.whl", hash = "sha256:d9d537a39cc9de668e5cd0e25affb17aec17b577c6b3ae8a3d866b479fbe88d0", size = 6819053, upload-time = "2025-09-09T15:58:50.401Z" }, + { url = "https://files.pythonhosted.org/packages/57/62/208293d7d6b2a8998a4a1f23ac758648c3c32182d4ce4346062018362e29/numpy-2.3.3-pp311-pypy311_pp73-manylinux_2_27_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:8596ba2f8af5f93b01d97563832686d20206d303024777f6dfc2e7c7c3f1850e", size = 14420354, upload-time = "2025-09-09T15:58:52.704Z" }, + { url = "https://files.pythonhosted.org/packages/ed/0c/8e86e0ff7072e14a71b4c6af63175e40d1e7e933ce9b9e9f765a95b4e0c3/numpy-2.3.3-pp311-pypy311_pp73-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:e1ec5615b05369925bd1125f27df33f3b6c8bc10d788d5999ecd8769a1fa04db", size = 16760413, upload-time = "2025-09-09T15:58:55.027Z" }, + { url = "https://files.pythonhosted.org/packages/af/11/0cc63f9f321ccf63886ac203336777140011fb669e739da36d8db3c53b98/numpy-2.3.3-pp311-pypy311_pp73-win_amd64.whl", hash = "sha256:2e267c7da5bf7309670523896df97f93f6e469fb931161f483cd6882b3b1a5dc", size = 12971844, upload-time = "2025-09-09T15:58:57.359Z" }, ] [[package]] name = "opt-einsum" version = "3.4.0" source = { registry = "https://pypi.org/simple" } -sdist = { url = "https://files.pythonhosted.org/packages/8c/b9/2ac072041e899a52f20cf9510850ff58295003aa75525e58343591b0cbfb/opt_einsum-3.4.0.tar.gz", hash = "sha256:96ca72f1b886d148241348783498194c577fa30a8faac108586b14f1ba4473ac", size = 63004 } +sdist = { url = "https://files.pythonhosted.org/packages/8c/b9/2ac072041e899a52f20cf9510850ff58295003aa75525e58343591b0cbfb/opt_einsum-3.4.0.tar.gz", hash = "sha256:96ca72f1b886d148241348783498194c577fa30a8faac108586b14f1ba4473ac", size = 63004, upload-time = "2024-09-26T14:33:24.483Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/23/cd/066e86230ae37ed0be70aae89aabf03ca8d9f39c8aea0dec8029455b5540/opt_einsum-3.4.0-py3-none-any.whl", hash = "sha256:69bb92469f86a1565195ece4ac0323943e83477171b91d24c35afe028a90d7cd", size = 71932 }, + { url = "https://files.pythonhosted.org/packages/23/cd/066e86230ae37ed0be70aae89aabf03ca8d9f39c8aea0dec8029455b5540/opt_einsum-3.4.0-py3-none-any.whl", hash = "sha256:69bb92469f86a1565195ece4ac0323943e83477171b91d24c35afe028a90d7cd", size = 71932, upload-time = "2024-09-26T14:33:23.039Z" }, ] [[package]] name = "optax" -version = "0.2.5" +version = "0.2.6" source = { registry = "https://pypi.org/simple" } dependencies = [ { name = "absl-py" }, - { name = "chex" }, - { name = "jax" }, - { name = "jaxlib" }, + { name = "chex", version = "0.1.90", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version < '3.11'" }, + { name = "chex", version = "0.1.91", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version >= '3.11'" }, + { name = "jax", version = "0.6.2", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version < '3.11'" }, + { name = "jax", version = "0.7.2", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version >= '3.11'" }, + { name = "jaxlib", version = "0.6.2", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version < '3.11'" }, + { name = "jaxlib", version = "0.7.2", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version >= '3.11'" }, { name = "numpy", version = "2.2.6", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version < '3.11'" }, - { name = "numpy", version = "2.3.1", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version >= '3.11'" }, + { name = "numpy", version = "2.3.3", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version >= '3.11'" }, ] -sdist = { url = "https://files.pythonhosted.org/packages/c0/75/1e011953c48be502d4d84fa8458e91be7c6f983002511669bddd7b1a065f/optax-0.2.5.tar.gz", hash = "sha256:b2e38c7aea376186deae758ba7a258e6ef760c6f6131e9e11bc561c65386d594", size = 258548 } +sdist = { url = "https://files.pythonhosted.org/packages/6d/3b/90c11f740a3538200b61cd2b7d9346959cb9e31e0bdea3d2f886b7262203/optax-0.2.6.tar.gz", hash = "sha256:ba8d1e12678eba2657484d6feeca4fb281b8066bdfd5efbfc0f41b87663109c0", size = 269660, upload-time = "2025-09-15T22:41:24.76Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/b9/33/f86091c706db1a5459f501830241afff2ecab3532725c188ea57be6e54de/optax-0.2.5-py3-none-any.whl", hash = "sha256:966deae936207f268ac8f564d8ed228d645ac1aaddefbbf194096d2299b24ba8", size = 354324 }, + { url = "https://files.pythonhosted.org/packages/b8/ec/19c6cc6064c7fc8f0cd6d5b37c4747849e66040c6ca98f86565efc2c227c/optax-0.2.6-py3-none-any.whl", hash = "sha256:f875251a5ab20f179d4be57478354e8e21963373b10f9c3b762b94dcb8c36d91", size = 367782, upload-time = "2025-09-15T22:41:22.825Z" }, ] [[package]] name = "orbax-checkpoint" -version = "0.11.18" +version = "0.11.25" source = { registry = "https://pypi.org/simple" } dependencies = [ { name = "absl-py" }, + { name = "aiofiles" }, { name = "etils", extra = ["epath", "epy"] }, { name = "humanize" }, - { name = "jax" }, + { name = "jax", version = "0.6.2", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version < '3.11'" }, + { name = "jax", version = "0.7.2", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version >= '3.11'" }, { name = "msgpack" }, { name = "nest-asyncio" }, { name = "numpy", version = "2.2.6", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version < '3.11'" }, - { name = "numpy", version = "2.3.1", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version >= '3.11'" }, + { name = "numpy", version = "2.3.3", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version >= '3.11'" }, { name = "protobuf" }, { name = "pyyaml" }, { name = "simplejson" }, { name = "tensorstore" }, { name = "typing-extensions" }, ] -sdist = { url = "https://files.pythonhosted.org/packages/55/02/3a2d2d862931a96c4208756bfe8de1f9b65723588be757e5074beab33c53/orbax_checkpoint-0.11.18.tar.gz", hash = "sha256:de7c3826550fc5fed1eb362be30e4b83125cb32bb86de951652bb3c4f9337415", size = 340670 } +sdist = { url = "https://files.pythonhosted.org/packages/00/44/63d4a064fddc9f75cf622427f01333ed109096b6af8db039c00c12b2a85b/orbax_checkpoint-0.11.25.tar.gz", hash = "sha256:15d35e4ee165aad8edccc25bc462a71c921bdaecc79ce0a2a5a0f784fce091be", size = 389724, upload-time = "2025-09-11T17:40:50.771Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/cd/2d/2fc1b216df08d775b860c20683dd8e8d2c8c2930bf8d2dfbe52ebc2fdf46/orbax_checkpoint-0.11.18-py3-none-any.whl", hash = "sha256:9f2f1ebc0305d75593e5720aeb8a82ee42c68f436ef98840411b2804136f7034", size = 479958 }, + { url = "https://files.pythonhosted.org/packages/1b/96/510dff16d2b75d9debb77fcfc4e6a4749059024a290953032f3ac793f74a/orbax_checkpoint-0.11.25-py3-none-any.whl", hash = "sha256:af8f5d16f1185c54ead7859309c57de28bf3cc9b4928ebd5a526e3ba549256c4", size = 563103, upload-time = "2025-09-11T17:40:49.368Z" }, ] [[package]] name = "packaging" version = "25.0" source = { registry = "https://pypi.org/simple" } -sdist = { url = "https://files.pythonhosted.org/packages/a1/d4/1fc4078c65507b51b96ca8f8c3ba19e6a61c8253c72794544580a7b6c24d/packaging-25.0.tar.gz", hash = "sha256:d443872c98d677bf60f6a1f2f8c1cb748e8fe762d2bf9d3148b5599295b0fc4f", size = 165727 } +sdist = { url = "https://files.pythonhosted.org/packages/a1/d4/1fc4078c65507b51b96ca8f8c3ba19e6a61c8253c72794544580a7b6c24d/packaging-25.0.tar.gz", hash = "sha256:d443872c98d677bf60f6a1f2f8c1cb748e8fe762d2bf9d3148b5599295b0fc4f", size = 165727, upload-time = "2025-04-19T11:48:59.673Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/20/12/38679034af332785aac8774540895e234f4d07f7545804097de4b666afd8/packaging-25.0-py3-none-any.whl", hash = "sha256:29572ef2b1f17581046b3a2227d5c611fb25ec70ca1ba8554b24b0e69331a484", size = 66469 }, + { url = "https://files.pythonhosted.org/packages/20/12/38679034af332785aac8774540895e234f4d07f7545804097de4b666afd8/packaging-25.0-py3-none-any.whl", hash = "sha256:29572ef2b1f17581046b3a2227d5c611fb25ec70ca1ba8554b24b0e69331a484", size = 66469, upload-time = "2025-04-19T11:48:57.875Z" }, ] [[package]] name = "paginate" version = "0.5.7" source = { registry = "https://pypi.org/simple" } -sdist = { url = "https://files.pythonhosted.org/packages/ec/46/68dde5b6bc00c1296ec6466ab27dddede6aec9af1b99090e1107091b3b84/paginate-0.5.7.tar.gz", hash = "sha256:22bd083ab41e1a8b4f3690544afb2c60c25e5c9a63a30fa2f483f6c60c8e5945", size = 19252 } +sdist = { url = "https://files.pythonhosted.org/packages/ec/46/68dde5b6bc00c1296ec6466ab27dddede6aec9af1b99090e1107091b3b84/paginate-0.5.7.tar.gz", hash = "sha256:22bd083ab41e1a8b4f3690544afb2c60c25e5c9a63a30fa2f483f6c60c8e5945", size = 19252, upload-time = "2024-08-25T14:17:24.139Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/90/96/04b8e52da071d28f5e21a805b19cb9390aa17a47462ac87f5e2696b9566d/paginate-0.5.7-py2.py3-none-any.whl", hash = "sha256:b885e2af73abcf01d9559fd5216b57ef722f8c42affbb63942377668e35c7591", size = 13746 }, + { url = "https://files.pythonhosted.org/packages/90/96/04b8e52da071d28f5e21a805b19cb9390aa17a47462ac87f5e2696b9566d/paginate-0.5.7-py2.py3-none-any.whl", hash = "sha256:b885e2af73abcf01d9559fd5216b57ef722f8c42affbb63942377668e35c7591", size = 13746, upload-time = "2024-08-25T14:17:22.55Z" }, ] [[package]] name = "pathspec" version = "0.12.1" source = { registry = "https://pypi.org/simple" } -sdist = { url = "https://files.pythonhosted.org/packages/ca/bc/f35b8446f4531a7cb215605d100cd88b7ac6f44ab3fc94870c120ab3adbf/pathspec-0.12.1.tar.gz", hash = "sha256:a482d51503a1ab33b1c67a6c3813a26953dbdc71c31dacaef9a838c4e29f5712", size = 51043 } +sdist = { url = "https://files.pythonhosted.org/packages/ca/bc/f35b8446f4531a7cb215605d100cd88b7ac6f44ab3fc94870c120ab3adbf/pathspec-0.12.1.tar.gz", hash = "sha256:a482d51503a1ab33b1c67a6c3813a26953dbdc71c31dacaef9a838c4e29f5712", size = 51043, upload-time = "2023-12-10T22:30:45Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/cc/20/ff623b09d963f88bfde16306a54e12ee5ea43e9b597108672ff3a408aad6/pathspec-0.12.1-py3-none-any.whl", hash = "sha256:a0d503e138a4c123b27490a4f7beda6a01c6f288df0e4a8b79c7eb0dc7b4cc08", size = 31191 }, + { url = "https://files.pythonhosted.org/packages/cc/20/ff623b09d963f88bfde16306a54e12ee5ea43e9b597108672ff3a408aad6/pathspec-0.12.1-py3-none-any.whl", hash = "sha256:a0d503e138a4c123b27490a4f7beda6a01c6f288df0e4a8b79c7eb0dc7b4cc08", size = 31191, upload-time = "2023-12-10T22:30:43.14Z" }, ] [[package]] name = "platformdirs" -version = "4.3.8" +version = "4.4.0" source = { registry = "https://pypi.org/simple" } -sdist = { url = "https://files.pythonhosted.org/packages/fe/8b/3c73abc9c759ecd3f1f7ceff6685840859e8070c4d947c93fae71f6a0bf2/platformdirs-4.3.8.tar.gz", hash = "sha256:3d512d96e16bcb959a814c9f348431070822a6496326a4be0911c40b5a74c2bc", size = 21362 } +sdist = { url = "https://files.pythonhosted.org/packages/23/e8/21db9c9987b0e728855bd57bff6984f67952bea55d6f75e055c46b5383e8/platformdirs-4.4.0.tar.gz", hash = "sha256:ca753cf4d81dc309bc67b0ea38fd15dc97bc30ce419a7f58d13eb3bf14c4febf", size = 21634, upload-time = "2025-08-26T14:32:04.268Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/fe/39/979e8e21520d4e47a0bbe349e2713c0aac6f3d853d0e5b34d76206c439aa/platformdirs-4.3.8-py3-none-any.whl", hash = "sha256:ff7059bb7eb1179e2685604f4aaf157cfd9535242bd23742eadc3c13542139b4", size = 18567 }, + { url = "https://files.pythonhosted.org/packages/40/4b/2028861e724d3bd36227adfa20d3fd24c3fc6d52032f4a93c133be5d17ce/platformdirs-4.4.0-py3-none-any.whl", hash = "sha256:abd01743f24e5287cd7a5db3752faf1a2d65353f38ec26d98e25a6db65958c85", size = 18654, upload-time = "2025-08-26T14:32:02.735Z" }, ] [[package]] name = "pluggy" version = "1.6.0" source = { registry = "https://pypi.org/simple" } -sdist = { url = "https://files.pythonhosted.org/packages/f9/e2/3e91f31a7d2b083fe6ef3fa267035b518369d9511ffab804f839851d2779/pluggy-1.6.0.tar.gz", hash = "sha256:7dcc130b76258d33b90f61b658791dede3486c3e6bfb003ee5c9bfb396dd22f3", size = 69412 } +sdist = { url = "https://files.pythonhosted.org/packages/f9/e2/3e91f31a7d2b083fe6ef3fa267035b518369d9511ffab804f839851d2779/pluggy-1.6.0.tar.gz", hash = "sha256:7dcc130b76258d33b90f61b658791dede3486c3e6bfb003ee5c9bfb396dd22f3", size = 69412, upload-time = "2025-05-15T12:30:07.975Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/54/20/4d324d65cc6d9205fabedc306948156824eb9f0ee1633355a8f7ec5c66bf/pluggy-1.6.0-py3-none-any.whl", hash = "sha256:e920276dd6813095e9377c0bc5566d94c932c33b27a3e3945d8389c374dd4746", size = 20538 }, + { url = "https://files.pythonhosted.org/packages/54/20/4d324d65cc6d9205fabedc306948156824eb9f0ee1633355a8f7ec5c66bf/pluggy-1.6.0-py3-none-any.whl", hash = "sha256:e920276dd6813095e9377c0bc5566d94c932c33b27a3e3945d8389c374dd4746", size = 20538, upload-time = "2025-05-15T12:30:06.134Z" }, ] [[package]] name = "pre-commit" -version = "4.2.0" +version = "4.3.0" source = { registry = "https://pypi.org/simple" } dependencies = [ { name = "cfgv" }, @@ -1133,50 +1338,50 @@ dependencies = [ { name = "pyyaml" }, { name = "virtualenv" }, ] -sdist = { url = "https://files.pythonhosted.org/packages/08/39/679ca9b26c7bb2999ff122d50faa301e49af82ca9c066ec061cfbc0c6784/pre_commit-4.2.0.tar.gz", hash = "sha256:601283b9757afd87d40c4c4a9b2b5de9637a8ea02eaff7adc2d0fb4e04841146", size = 193424 } +sdist = { url = "https://files.pythonhosted.org/packages/ff/29/7cf5bbc236333876e4b41f56e06857a87937ce4bf91e117a6991a2dbb02a/pre_commit-4.3.0.tar.gz", hash = "sha256:499fe450cc9d42e9d58e606262795ecb64dd05438943c62b66f6a8673da30b16", size = 193792, upload-time = "2025-08-09T18:56:14.651Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/88/74/a88bf1b1efeae488a0c0b7bdf71429c313722d1fc0f377537fbe554e6180/pre_commit-4.2.0-py2.py3-none-any.whl", hash = "sha256:a009ca7205f1eb497d10b845e52c838a98b6cdd2102a6c8e4540e94ee75c58bd", size = 220707 }, + { url = "https://files.pythonhosted.org/packages/5b/a5/987a405322d78a73b66e39e4a90e4ef156fd7141bf71df987e50717c321b/pre_commit-4.3.0-py2.py3-none-any.whl", hash = "sha256:2b0747ad7e6e967169136edffee14c16e148a778a54e4f967921aa1ebf2308d8", size = 220965, upload-time = "2025-08-09T18:56:13.192Z" }, ] [[package]] name = "protobuf" -version = "6.31.1" +version = "6.32.1" source = { registry = "https://pypi.org/simple" } -sdist = { url = "https://files.pythonhosted.org/packages/52/f3/b9655a711b32c19720253f6f06326faf90580834e2e83f840472d752bc8b/protobuf-6.31.1.tar.gz", hash = "sha256:d8cac4c982f0b957a4dc73a80e2ea24fab08e679c0de9deb835f4a12d69aca9a", size = 441797 } +sdist = { url = "https://files.pythonhosted.org/packages/fa/a4/cc17347aa2897568beece2e674674359f911d6fe21b0b8d6268cd42727ac/protobuf-6.32.1.tar.gz", hash = "sha256:ee2469e4a021474ab9baafea6cd070e5bf27c7d29433504ddea1a4ee5850f68d", size = 440635, upload-time = "2025-09-11T21:38:42.935Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/f3/6f/6ab8e4bf962fd5570d3deaa2d5c38f0a363f57b4501047b5ebeb83ab1125/protobuf-6.31.1-cp310-abi3-win32.whl", hash = "sha256:7fa17d5a29c2e04b7d90e5e32388b8bfd0e7107cd8e616feef7ed3fa6bdab5c9", size = 423603 }, - { url = "https://files.pythonhosted.org/packages/44/3a/b15c4347dd4bf3a1b0ee882f384623e2063bb5cf9fa9d57990a4f7df2fb6/protobuf-6.31.1-cp310-abi3-win_amd64.whl", hash = "sha256:426f59d2964864a1a366254fa703b8632dcec0790d8862d30034d8245e1cd447", size = 435283 }, - { url = "https://files.pythonhosted.org/packages/6a/c9/b9689a2a250264a84e66c46d8862ba788ee7a641cdca39bccf64f59284b7/protobuf-6.31.1-cp39-abi3-macosx_10_9_universal2.whl", hash = "sha256:6f1227473dc43d44ed644425268eb7c2e488ae245d51c6866d19fe158e207402", size = 425604 }, - { url = "https://files.pythonhosted.org/packages/76/a1/7a5a94032c83375e4fe7e7f56e3976ea6ac90c5e85fac8576409e25c39c3/protobuf-6.31.1-cp39-abi3-manylinux2014_aarch64.whl", hash = "sha256:a40fc12b84c154884d7d4c4ebd675d5b3b5283e155f324049ae396b95ddebc39", size = 322115 }, - { url = "https://files.pythonhosted.org/packages/fa/b1/b59d405d64d31999244643d88c45c8241c58f17cc887e73bcb90602327f8/protobuf-6.31.1-cp39-abi3-manylinux2014_x86_64.whl", hash = "sha256:4ee898bf66f7a8b0bd21bce523814e6fbd8c6add948045ce958b73af7e8878c6", size = 321070 }, - { url = "https://files.pythonhosted.org/packages/f7/af/ab3c51ab7507a7325e98ffe691d9495ee3d3aa5f589afad65ec920d39821/protobuf-6.31.1-py3-none-any.whl", hash = "sha256:720a6c7e6b77288b85063569baae8536671b39f15cc22037ec7045658d80489e", size = 168724 }, + { url = "https://files.pythonhosted.org/packages/c0/98/645183ea03ab3995d29086b8bf4f7562ebd3d10c9a4b14ee3f20d47cfe50/protobuf-6.32.1-cp310-abi3-win32.whl", hash = "sha256:a8a32a84bc9f2aad712041b8b366190f71dde248926da517bde9e832e4412085", size = 424411, upload-time = "2025-09-11T21:38:27.427Z" }, + { url = "https://files.pythonhosted.org/packages/8c/f3/6f58f841f6ebafe076cebeae33fc336e900619d34b1c93e4b5c97a81fdfa/protobuf-6.32.1-cp310-abi3-win_amd64.whl", hash = "sha256:b00a7d8c25fa471f16bc8153d0e53d6c9e827f0953f3c09aaa4331c718cae5e1", size = 435738, upload-time = "2025-09-11T21:38:30.959Z" }, + { url = "https://files.pythonhosted.org/packages/10/56/a8a3f4e7190837139e68c7002ec749190a163af3e330f65d90309145a210/protobuf-6.32.1-cp39-abi3-macosx_10_9_universal2.whl", hash = "sha256:d8c7e6eb619ffdf105ee4ab76af5a68b60a9d0f66da3ea12d1640e6d8dab7281", size = 426454, upload-time = "2025-09-11T21:38:34.076Z" }, + { url = "https://files.pythonhosted.org/packages/3f/be/8dd0a927c559b37d7a6c8ab79034fd167dcc1f851595f2e641ad62be8643/protobuf-6.32.1-cp39-abi3-manylinux2014_aarch64.whl", hash = "sha256:2f5b80a49e1eb7b86d85fcd23fe92df154b9730a725c3b38c4e43b9d77018bf4", size = 322874, upload-time = "2025-09-11T21:38:35.509Z" }, + { url = "https://files.pythonhosted.org/packages/5c/f6/88d77011b605ef979aace37b7703e4eefad066f7e84d935e5a696515c2dd/protobuf-6.32.1-cp39-abi3-manylinux2014_x86_64.whl", hash = "sha256:b1864818300c297265c83a4982fd3169f97122c299f56a56e2445c3698d34710", size = 322013, upload-time = "2025-09-11T21:38:37.017Z" }, + { url = "https://files.pythonhosted.org/packages/97/b7/15cc7d93443d6c6a84626ae3258a91f4c6ac8c0edd5df35ea7658f71b79c/protobuf-6.32.1-py3-none-any.whl", hash = "sha256:2601b779fc7d32a866c6b4404f9d42a3f67c5b9f3f15b4db3cccabe06b95c346", size = 169289, upload-time = "2025-09-11T21:38:41.234Z" }, ] [[package]] name = "pygments" version = "2.19.2" source = { registry = "https://pypi.org/simple" } -sdist = { url = "https://files.pythonhosted.org/packages/b0/77/a5b8c569bf593b0140bde72ea885a803b82086995367bf2037de0159d924/pygments-2.19.2.tar.gz", hash = "sha256:636cb2477cec7f8952536970bc533bc43743542f70392ae026374600add5b887", size = 4968631 } +sdist = { url = "https://files.pythonhosted.org/packages/b0/77/a5b8c569bf593b0140bde72ea885a803b82086995367bf2037de0159d924/pygments-2.19.2.tar.gz", hash = "sha256:636cb2477cec7f8952536970bc533bc43743542f70392ae026374600add5b887", size = 4968631, upload-time = "2025-06-21T13:39:12.283Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/c7/21/705964c7812476f378728bdf590ca4b771ec72385c533964653c68e86bdc/pygments-2.19.2-py3-none-any.whl", hash = "sha256:86540386c03d588bb81d44bc3928634ff26449851e99741617ecb9037ee5ec0b", size = 1225217 }, + { url = "https://files.pythonhosted.org/packages/c7/21/705964c7812476f378728bdf590ca4b771ec72385c533964653c68e86bdc/pygments-2.19.2-py3-none-any.whl", hash = "sha256:86540386c03d588bb81d44bc3928634ff26449851e99741617ecb9037ee5ec0b", size = 1225217, upload-time = "2025-06-21T13:39:07.939Z" }, ] [[package]] name = "pymdown-extensions" -version = "10.16" +version = "10.16.1" source = { registry = "https://pypi.org/simple" } dependencies = [ { name = "markdown" }, { name = "pyyaml" }, ] -sdist = { url = "https://files.pythonhosted.org/packages/1a/0a/c06b542ac108bfc73200677309cd9188a3a01b127a63f20cadc18d873d88/pymdown_extensions-10.16.tar.gz", hash = "sha256:71dac4fca63fabeffd3eb9038b756161a33ec6e8d230853d3cecf562155ab3de", size = 853197 } +sdist = { url = "https://files.pythonhosted.org/packages/55/b3/6d2b3f149bc5413b0a29761c2c5832d8ce904a1d7f621e86616d96f505cc/pymdown_extensions-10.16.1.tar.gz", hash = "sha256:aace82bcccba3efc03e25d584e6a22d27a8e17caa3f4dd9f207e49b787aa9a91", size = 853277, upload-time = "2025-07-28T16:19:34.167Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/98/d4/10bb14004d3c792811e05e21b5e5dcae805aacb739bd12a0540967b99592/pymdown_extensions-10.16-py3-none-any.whl", hash = "sha256:f5dd064a4db588cb2d95229fc4ee63a1b16cc8b4d0e6145c0899ed8723da1df2", size = 266143 }, + { url = "https://files.pythonhosted.org/packages/e4/06/43084e6cbd4b3bc0e80f6be743b2e79fbc6eed8de9ad8c629939fa55d972/pymdown_extensions-10.16.1-py3-none-any.whl", hash = "sha256:d6ba157a6c03146a7fb122b2b9a121300056384eafeec9c9f9e584adfdb2a32d", size = 266178, upload-time = "2025-07-28T16:19:31.401Z" }, ] [[package]] name = "pytest" -version = "8.4.1" +version = "8.4.2" source = { registry = "https://pypi.org/simple" } dependencies = [ { name = "colorama", marker = "sys_platform == 'win32'" }, @@ -1187,9 +1392,9 @@ dependencies = [ { name = "pygments" }, { name = "tomli", marker = "python_full_version < '3.11'" }, ] -sdist = { url = "https://files.pythonhosted.org/packages/08/ba/45911d754e8eba3d5a841a5ce61a65a685ff1798421ac054f85aa8747dfb/pytest-8.4.1.tar.gz", hash = "sha256:7c67fd69174877359ed9371ec3af8a3d2b04741818c51e5e99cc1742251fa93c", size = 1517714 } +sdist = { url = "https://files.pythonhosted.org/packages/a3/5c/00a0e072241553e1a7496d638deababa67c5058571567b92a7eaa258397c/pytest-8.4.2.tar.gz", hash = "sha256:86c0d0b93306b961d58d62a4db4879f27fe25513d4b969df351abdddb3c30e01", size = 1519618, upload-time = "2025-09-04T14:34:22.711Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/29/16/c8a903f4c4dffe7a12843191437d7cd8e32751d5de349d45d3fe69544e87/pytest-8.4.1-py3-none-any.whl", hash = "sha256:539c70ba6fcead8e78eebbf1115e8b589e7565830d7d006a8723f19ac8a0afb7", size = 365474 }, + { url = "https://files.pythonhosted.org/packages/a8/a4/20da314d277121d6534b3a980b29035dcd51e6744bd79075a6ce8fa4eb8d/pytest-8.4.2-py3-none-any.whl", hash = "sha256:872f880de3fc3a5bdc88a11b39c9710c3497a547cfa9320bc3c5e62fbf272e79", size = 365750, upload-time = "2025-09-04T14:34:20.226Z" }, ] [[package]] @@ -1199,53 +1404,73 @@ source = { registry = "https://pypi.org/simple" } dependencies = [ { name = "six" }, ] -sdist = { url = "https://files.pythonhosted.org/packages/66/c0/0c8b6ad9f17a802ee498c46e004a0eb49bc148f2fd230864601a86dcf6db/python-dateutil-2.9.0.post0.tar.gz", hash = "sha256:37dd54208da7e1cd875388217d5e00ebd4179249f90fb72437e91a35459a0ad3", size = 342432 } +sdist = { url = "https://files.pythonhosted.org/packages/66/c0/0c8b6ad9f17a802ee498c46e004a0eb49bc148f2fd230864601a86dcf6db/python-dateutil-2.9.0.post0.tar.gz", hash = "sha256:37dd54208da7e1cd875388217d5e00ebd4179249f90fb72437e91a35459a0ad3", size = 342432, upload-time = "2024-03-01T18:36:20.211Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/ec/57/56b9bcc3c9c6a792fcbaf139543cee77261f3651ca9da0c93f5c1221264b/python_dateutil-2.9.0.post0-py2.py3-none-any.whl", hash = "sha256:a8b2bc7bffae282281c8140a97d3aa9c14da0b136dfe83f850eea9a5f7470427", size = 229892 }, + { url = "https://files.pythonhosted.org/packages/ec/57/56b9bcc3c9c6a792fcbaf139543cee77261f3651ca9da0c93f5c1221264b/python_dateutil-2.9.0.post0-py2.py3-none-any.whl", hash = "sha256:a8b2bc7bffae282281c8140a97d3aa9c14da0b136dfe83f850eea9a5f7470427", size = 229892, upload-time = "2024-03-01T18:36:18.57Z" }, ] [[package]] name = "pyyaml" -version = "6.0.2" -source = { registry = "https://pypi.org/simple" } -sdist = { url = "https://files.pythonhosted.org/packages/54/ed/79a089b6be93607fa5cdaedf301d7dfb23af5f25c398d5ead2525b063e17/pyyaml-6.0.2.tar.gz", hash = "sha256:d584d9ec91ad65861cc08d42e834324ef890a082e591037abe114850ff7bbc3e", size = 130631 } -wheels = [ - { url = "https://files.pythonhosted.org/packages/9b/95/a3fac87cb7158e231b5a6012e438c647e1a87f09f8e0d123acec8ab8bf71/PyYAML-6.0.2-cp310-cp310-macosx_10_9_x86_64.whl", hash = "sha256:0a9a2848a5b7feac301353437eb7d5957887edbf81d56e903999a75a3d743086", size = 184199 }, - { url = "https://files.pythonhosted.org/packages/c7/7a/68bd47624dab8fd4afbfd3c48e3b79efe09098ae941de5b58abcbadff5cb/PyYAML-6.0.2-cp310-cp310-macosx_11_0_arm64.whl", hash = "sha256:29717114e51c84ddfba879543fb232a6ed60086602313ca38cce623c1d62cfbf", size = 171758 }, - { url = "https://files.pythonhosted.org/packages/49/ee/14c54df452143b9ee9f0f29074d7ca5516a36edb0b4cc40c3f280131656f/PyYAML-6.0.2-cp310-cp310-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:8824b5a04a04a047e72eea5cec3bc266db09e35de6bdfe34c9436ac5ee27d237", size = 718463 }, - { url = "https://files.pythonhosted.org/packages/4d/61/de363a97476e766574650d742205be468921a7b532aa2499fcd886b62530/PyYAML-6.0.2-cp310-cp310-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:7c36280e6fb8385e520936c3cb3b8042851904eba0e58d277dca80a5cfed590b", size = 719280 }, - { url = "https://files.pythonhosted.org/packages/6b/4e/1523cb902fd98355e2e9ea5e5eb237cbc5f3ad5f3075fa65087aa0ecb669/PyYAML-6.0.2-cp310-cp310-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:ec031d5d2feb36d1d1a24380e4db6d43695f3748343d99434e6f5f9156aaa2ed", size = 751239 }, - { url = "https://files.pythonhosted.org/packages/b7/33/5504b3a9a4464893c32f118a9cc045190a91637b119a9c881da1cf6b7a72/PyYAML-6.0.2-cp310-cp310-musllinux_1_1_aarch64.whl", hash = "sha256:936d68689298c36b53b29f23c6dbb74de12b4ac12ca6cfe0e047bedceea56180", size = 695802 }, - { url = "https://files.pythonhosted.org/packages/5c/20/8347dcabd41ef3a3cdc4f7b7a2aff3d06598c8779faa189cdbf878b626a4/PyYAML-6.0.2-cp310-cp310-musllinux_1_1_x86_64.whl", hash = "sha256:23502f431948090f597378482b4812b0caae32c22213aecf3b55325e049a6c68", size = 720527 }, - { url = "https://files.pythonhosted.org/packages/be/aa/5afe99233fb360d0ff37377145a949ae258aaab831bde4792b32650a4378/PyYAML-6.0.2-cp310-cp310-win32.whl", hash = "sha256:2e99c6826ffa974fe6e27cdb5ed0021786b03fc98e5ee3c5bfe1fd5015f42b99", size = 144052 }, - { url = "https://files.pythonhosted.org/packages/b5/84/0fa4b06f6d6c958d207620fc60005e241ecedceee58931bb20138e1e5776/PyYAML-6.0.2-cp310-cp310-win_amd64.whl", hash = "sha256:a4d3091415f010369ae4ed1fc6b79def9416358877534caf6a0fdd2146c87a3e", size = 161774 }, - { url = "https://files.pythonhosted.org/packages/f8/aa/7af4e81f7acba21a4c6be026da38fd2b872ca46226673c89a758ebdc4fd2/PyYAML-6.0.2-cp311-cp311-macosx_10_9_x86_64.whl", hash = "sha256:cc1c1159b3d456576af7a3e4d1ba7e6924cb39de8f67111c735f6fc832082774", size = 184612 }, - { url = "https://files.pythonhosted.org/packages/8b/62/b9faa998fd185f65c1371643678e4d58254add437edb764a08c5a98fb986/PyYAML-6.0.2-cp311-cp311-macosx_11_0_arm64.whl", hash = "sha256:1e2120ef853f59c7419231f3bf4e7021f1b936f6ebd222406c3b60212205d2ee", size = 172040 }, - { url = "https://files.pythonhosted.org/packages/ad/0c/c804f5f922a9a6563bab712d8dcc70251e8af811fce4524d57c2c0fd49a4/PyYAML-6.0.2-cp311-cp311-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:5d225db5a45f21e78dd9358e58a98702a0302f2659a3c6cd320564b75b86f47c", size = 736829 }, - { url = "https://files.pythonhosted.org/packages/51/16/6af8d6a6b210c8e54f1406a6b9481febf9c64a3109c541567e35a49aa2e7/PyYAML-6.0.2-cp311-cp311-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:5ac9328ec4831237bec75defaf839f7d4564be1e6b25ac710bd1a96321cc8317", size = 764167 }, - { url = "https://files.pythonhosted.org/packages/75/e4/2c27590dfc9992f73aabbeb9241ae20220bd9452df27483b6e56d3975cc5/PyYAML-6.0.2-cp311-cp311-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:3ad2a3decf9aaba3d29c8f537ac4b243e36bef957511b4766cb0057d32b0be85", size = 762952 }, - { url = "https://files.pythonhosted.org/packages/9b/97/ecc1abf4a823f5ac61941a9c00fe501b02ac3ab0e373c3857f7d4b83e2b6/PyYAML-6.0.2-cp311-cp311-musllinux_1_1_aarch64.whl", hash = "sha256:ff3824dc5261f50c9b0dfb3be22b4567a6f938ccce4587b38952d85fd9e9afe4", size = 735301 }, - { url = "https://files.pythonhosted.org/packages/45/73/0f49dacd6e82c9430e46f4a027baa4ca205e8b0a9dce1397f44edc23559d/PyYAML-6.0.2-cp311-cp311-musllinux_1_1_x86_64.whl", hash = "sha256:797b4f722ffa07cc8d62053e4cff1486fa6dc094105d13fea7b1de7d8bf71c9e", size = 756638 }, - { url = "https://files.pythonhosted.org/packages/22/5f/956f0f9fc65223a58fbc14459bf34b4cc48dec52e00535c79b8db361aabd/PyYAML-6.0.2-cp311-cp311-win32.whl", hash = "sha256:11d8f3dd2b9c1207dcaf2ee0bbbfd5991f571186ec9cc78427ba5bd32afae4b5", size = 143850 }, - { url = "https://files.pythonhosted.org/packages/ed/23/8da0bbe2ab9dcdd11f4f4557ccaf95c10b9811b13ecced089d43ce59c3c8/PyYAML-6.0.2-cp311-cp311-win_amd64.whl", hash = "sha256:e10ce637b18caea04431ce14fabcf5c64a1c61ec9c56b071a4b7ca131ca52d44", size = 161980 }, - { url = "https://files.pythonhosted.org/packages/86/0c/c581167fc46d6d6d7ddcfb8c843a4de25bdd27e4466938109ca68492292c/PyYAML-6.0.2-cp312-cp312-macosx_10_9_x86_64.whl", hash = "sha256:c70c95198c015b85feafc136515252a261a84561b7b1d51e3384e0655ddf25ab", size = 183873 }, - { url = "https://files.pythonhosted.org/packages/a8/0c/38374f5bb272c051e2a69281d71cba6fdb983413e6758b84482905e29a5d/PyYAML-6.0.2-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:ce826d6ef20b1bc864f0a68340c8b3287705cae2f8b4b1d932177dcc76721725", size = 173302 }, - { url = "https://files.pythonhosted.org/packages/c3/93/9916574aa8c00aa06bbac729972eb1071d002b8e158bd0e83a3b9a20a1f7/PyYAML-6.0.2-cp312-cp312-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:1f71ea527786de97d1a0cc0eacd1defc0985dcf6b3f17bb77dcfc8c34bec4dc5", size = 739154 }, - { url = "https://files.pythonhosted.org/packages/95/0f/b8938f1cbd09739c6da569d172531567dbcc9789e0029aa070856f123984/PyYAML-6.0.2-cp312-cp312-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:9b22676e8097e9e22e36d6b7bda33190d0d400f345f23d4065d48f4ca7ae0425", size = 766223 }, - { url = "https://files.pythonhosted.org/packages/b9/2b/614b4752f2e127db5cc206abc23a8c19678e92b23c3db30fc86ab731d3bd/PyYAML-6.0.2-cp312-cp312-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:80bab7bfc629882493af4aa31a4cfa43a4c57c83813253626916b8c7ada83476", size = 767542 }, - { url = "https://files.pythonhosted.org/packages/d4/00/dd137d5bcc7efea1836d6264f049359861cf548469d18da90cd8216cf05f/PyYAML-6.0.2-cp312-cp312-musllinux_1_1_aarch64.whl", hash = "sha256:0833f8694549e586547b576dcfaba4a6b55b9e96098b36cdc7ebefe667dfed48", size = 731164 }, - { url = "https://files.pythonhosted.org/packages/c9/1f/4f998c900485e5c0ef43838363ba4a9723ac0ad73a9dc42068b12aaba4e4/PyYAML-6.0.2-cp312-cp312-musllinux_1_1_x86_64.whl", hash = "sha256:8b9c7197f7cb2738065c481a0461e50ad02f18c78cd75775628afb4d7137fb3b", size = 756611 }, - { url = "https://files.pythonhosted.org/packages/df/d1/f5a275fdb252768b7a11ec63585bc38d0e87c9e05668a139fea92b80634c/PyYAML-6.0.2-cp312-cp312-win32.whl", hash = "sha256:ef6107725bd54b262d6dedcc2af448a266975032bc85ef0172c5f059da6325b4", size = 140591 }, - { url = "https://files.pythonhosted.org/packages/0c/e8/4f648c598b17c3d06e8753d7d13d57542b30d56e6c2dedf9c331ae56312e/PyYAML-6.0.2-cp312-cp312-win_amd64.whl", hash = "sha256:7e7401d0de89a9a855c839bc697c079a4af81cf878373abd7dc625847d25cbd8", size = 156338 }, - { url = "https://files.pythonhosted.org/packages/ef/e3/3af305b830494fa85d95f6d95ef7fa73f2ee1cc8ef5b495c7c3269fb835f/PyYAML-6.0.2-cp313-cp313-macosx_10_13_x86_64.whl", hash = "sha256:efdca5630322a10774e8e98e1af481aad470dd62c3170801852d752aa7a783ba", size = 181309 }, - { url = "https://files.pythonhosted.org/packages/45/9f/3b1c20a0b7a3200524eb0076cc027a970d320bd3a6592873c85c92a08731/PyYAML-6.0.2-cp313-cp313-macosx_11_0_arm64.whl", hash = "sha256:50187695423ffe49e2deacb8cd10510bc361faac997de9efef88badc3bb9e2d1", size = 171679 }, - { url = "https://files.pythonhosted.org/packages/7c/9a/337322f27005c33bcb656c655fa78325b730324c78620e8328ae28b64d0c/PyYAML-6.0.2-cp313-cp313-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:0ffe8360bab4910ef1b9e87fb812d8bc0a308b0d0eef8c8f44e0254ab3b07133", size = 733428 }, - { url = "https://files.pythonhosted.org/packages/a3/69/864fbe19e6c18ea3cc196cbe5d392175b4cf3d5d0ac1403ec3f2d237ebb5/PyYAML-6.0.2-cp313-cp313-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:17e311b6c678207928d649faa7cb0d7b4c26a0ba73d41e99c4fff6b6c3276484", size = 763361 }, - { url = "https://files.pythonhosted.org/packages/04/24/b7721e4845c2f162d26f50521b825fb061bc0a5afcf9a386840f23ea19fa/PyYAML-6.0.2-cp313-cp313-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:70b189594dbe54f75ab3a1acec5f1e3faa7e8cf2f1e08d9b561cb41b845f69d5", size = 759523 }, - { url = "https://files.pythonhosted.org/packages/2b/b2/e3234f59ba06559c6ff63c4e10baea10e5e7df868092bf9ab40e5b9c56b6/PyYAML-6.0.2-cp313-cp313-musllinux_1_1_aarch64.whl", hash = "sha256:41e4e3953a79407c794916fa277a82531dd93aad34e29c2a514c2c0c5fe971cc", size = 726660 }, - { url = "https://files.pythonhosted.org/packages/fe/0f/25911a9f080464c59fab9027482f822b86bf0608957a5fcc6eaac85aa515/PyYAML-6.0.2-cp313-cp313-musllinux_1_1_x86_64.whl", hash = "sha256:68ccc6023a3400877818152ad9a1033e3db8625d899c72eacb5a668902e4d652", size = 751597 }, - { url = "https://files.pythonhosted.org/packages/14/0d/e2c3b43bbce3cf6bd97c840b46088a3031085179e596d4929729d8d68270/PyYAML-6.0.2-cp313-cp313-win32.whl", hash = "sha256:bc2fa7c6b47d6bc618dd7fb02ef6fdedb1090ec036abab80d4681424b84c1183", size = 140527 }, - { url = "https://files.pythonhosted.org/packages/fa/de/02b54f42487e3d3c6efb3f89428677074ca7bf43aae402517bc7cca949f3/PyYAML-6.0.2-cp313-cp313-win_amd64.whl", hash = "sha256:8388ee1976c416731879ac16da0aff3f63b286ffdd57cdeb95f3f2e085687563", size = 156446 }, +version = "6.0.3" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/05/8e/961c0007c59b8dd7729d542c61a4d537767a59645b82a0b521206e1e25c2/pyyaml-6.0.3.tar.gz", hash = "sha256:d76623373421df22fb4cf8817020cbb7ef15c725b9d5e45f17e189bfc384190f", size = 130960, upload-time = "2025-09-25T21:33:16.546Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/f4/a0/39350dd17dd6d6c6507025c0e53aef67a9293a6d37d3511f23ea510d5800/pyyaml-6.0.3-cp310-cp310-macosx_10_13_x86_64.whl", hash = "sha256:214ed4befebe12df36bcc8bc2b64b396ca31be9304b8f59e25c11cf94a4c033b", size = 184227, upload-time = "2025-09-25T21:31:46.04Z" }, + { url = "https://files.pythonhosted.org/packages/05/14/52d505b5c59ce73244f59c7a50ecf47093ce4765f116cdb98286a71eeca2/pyyaml-6.0.3-cp310-cp310-macosx_11_0_arm64.whl", hash = "sha256:02ea2dfa234451bbb8772601d7b8e426c2bfa197136796224e50e35a78777956", size = 174019, upload-time = "2025-09-25T21:31:47.706Z" }, + { url = "https://files.pythonhosted.org/packages/43/f7/0e6a5ae5599c838c696adb4e6330a59f463265bfa1e116cfd1fbb0abaaae/pyyaml-6.0.3-cp310-cp310-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:b30236e45cf30d2b8e7b3e85881719e98507abed1011bf463a8fa23e9c3e98a8", size = 740646, upload-time = "2025-09-25T21:31:49.21Z" }, + { url = "https://files.pythonhosted.org/packages/2f/3a/61b9db1d28f00f8fd0ae760459a5c4bf1b941baf714e207b6eb0657d2578/pyyaml-6.0.3-cp310-cp310-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:66291b10affd76d76f54fad28e22e51719ef9ba22b29e1d7d03d6777a9174198", size = 840793, upload-time = "2025-09-25T21:31:50.735Z" }, + { url = "https://files.pythonhosted.org/packages/7a/1e/7acc4f0e74c4b3d9531e24739e0ab832a5edf40e64fbae1a9c01941cabd7/pyyaml-6.0.3-cp310-cp310-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:9c7708761fccb9397fe64bbc0395abcae8c4bf7b0eac081e12b809bf47700d0b", size = 770293, upload-time = "2025-09-25T21:31:51.828Z" }, + { url = "https://files.pythonhosted.org/packages/8b/ef/abd085f06853af0cd59fa5f913d61a8eab65d7639ff2a658d18a25d6a89d/pyyaml-6.0.3-cp310-cp310-musllinux_1_2_aarch64.whl", hash = "sha256:418cf3f2111bc80e0933b2cd8cd04f286338bb88bdc7bc8e6dd775ebde60b5e0", size = 732872, upload-time = "2025-09-25T21:31:53.282Z" }, + { url = "https://files.pythonhosted.org/packages/1f/15/2bc9c8faf6450a8b3c9fc5448ed869c599c0a74ba2669772b1f3a0040180/pyyaml-6.0.3-cp310-cp310-musllinux_1_2_x86_64.whl", hash = "sha256:5e0b74767e5f8c593e8c9b5912019159ed0533c70051e9cce3e8b6aa699fcd69", size = 758828, upload-time = "2025-09-25T21:31:54.807Z" }, + { url = "https://files.pythonhosted.org/packages/a3/00/531e92e88c00f4333ce359e50c19b8d1de9fe8d581b1534e35ccfbc5f393/pyyaml-6.0.3-cp310-cp310-win32.whl", hash = "sha256:28c8d926f98f432f88adc23edf2e6d4921ac26fb084b028c733d01868d19007e", size = 142415, upload-time = "2025-09-25T21:31:55.885Z" }, + { url = "https://files.pythonhosted.org/packages/2a/fa/926c003379b19fca39dd4634818b00dec6c62d87faf628d1394e137354d4/pyyaml-6.0.3-cp310-cp310-win_amd64.whl", hash = "sha256:bdb2c67c6c1390b63c6ff89f210c8fd09d9a1217a465701eac7316313c915e4c", size = 158561, upload-time = "2025-09-25T21:31:57.406Z" }, + { url = "https://files.pythonhosted.org/packages/6d/16/a95b6757765b7b031c9374925bb718d55e0a9ba8a1b6a12d25962ea44347/pyyaml-6.0.3-cp311-cp311-macosx_10_13_x86_64.whl", hash = "sha256:44edc647873928551a01e7a563d7452ccdebee747728c1080d881d68af7b997e", size = 185826, upload-time = "2025-09-25T21:31:58.655Z" }, + { url = "https://files.pythonhosted.org/packages/16/19/13de8e4377ed53079ee996e1ab0a9c33ec2faf808a4647b7b4c0d46dd239/pyyaml-6.0.3-cp311-cp311-macosx_11_0_arm64.whl", hash = "sha256:652cb6edd41e718550aad172851962662ff2681490a8a711af6a4d288dd96824", size = 175577, upload-time = "2025-09-25T21:32:00.088Z" }, + { url = "https://files.pythonhosted.org/packages/0c/62/d2eb46264d4b157dae1275b573017abec435397aa59cbcdab6fc978a8af4/pyyaml-6.0.3-cp311-cp311-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:10892704fc220243f5305762e276552a0395f7beb4dbf9b14ec8fd43b57f126c", size = 775556, upload-time = "2025-09-25T21:32:01.31Z" }, + { url = "https://files.pythonhosted.org/packages/10/cb/16c3f2cf3266edd25aaa00d6c4350381c8b012ed6f5276675b9eba8d9ff4/pyyaml-6.0.3-cp311-cp311-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:850774a7879607d3a6f50d36d04f00ee69e7fc816450e5f7e58d7f17f1ae5c00", size = 882114, upload-time = "2025-09-25T21:32:03.376Z" }, + { url = "https://files.pythonhosted.org/packages/71/60/917329f640924b18ff085ab889a11c763e0b573da888e8404ff486657602/pyyaml-6.0.3-cp311-cp311-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:b8bb0864c5a28024fac8a632c443c87c5aa6f215c0b126c449ae1a150412f31d", size = 806638, upload-time = "2025-09-25T21:32:04.553Z" }, + { url = "https://files.pythonhosted.org/packages/dd/6f/529b0f316a9fd167281a6c3826b5583e6192dba792dd55e3203d3f8e655a/pyyaml-6.0.3-cp311-cp311-musllinux_1_2_aarch64.whl", hash = "sha256:1d37d57ad971609cf3c53ba6a7e365e40660e3be0e5175fa9f2365a379d6095a", size = 767463, upload-time = "2025-09-25T21:32:06.152Z" }, + { url = "https://files.pythonhosted.org/packages/f2/6a/b627b4e0c1dd03718543519ffb2f1deea4a1e6d42fbab8021936a4d22589/pyyaml-6.0.3-cp311-cp311-musllinux_1_2_x86_64.whl", hash = "sha256:37503bfbfc9d2c40b344d06b2199cf0e96e97957ab1c1b546fd4f87e53e5d3e4", size = 794986, upload-time = "2025-09-25T21:32:07.367Z" }, + { url = "https://files.pythonhosted.org/packages/45/91/47a6e1c42d9ee337c4839208f30d9f09caa9f720ec7582917b264defc875/pyyaml-6.0.3-cp311-cp311-win32.whl", hash = "sha256:8098f252adfa6c80ab48096053f512f2321f0b998f98150cea9bd23d83e1467b", size = 142543, upload-time = "2025-09-25T21:32:08.95Z" }, + { url = "https://files.pythonhosted.org/packages/da/e3/ea007450a105ae919a72393cb06f122f288ef60bba2dc64b26e2646fa315/pyyaml-6.0.3-cp311-cp311-win_amd64.whl", hash = "sha256:9f3bfb4965eb874431221a3ff3fdcddc7e74e3b07799e0e84ca4a0f867d449bf", size = 158763, upload-time = "2025-09-25T21:32:09.96Z" }, + { url = "https://files.pythonhosted.org/packages/d1/33/422b98d2195232ca1826284a76852ad5a86fe23e31b009c9886b2d0fb8b2/pyyaml-6.0.3-cp312-cp312-macosx_10_13_x86_64.whl", hash = "sha256:7f047e29dcae44602496db43be01ad42fc6f1cc0d8cd6c83d342306c32270196", size = 182063, upload-time = "2025-09-25T21:32:11.445Z" }, + { url = "https://files.pythonhosted.org/packages/89/a0/6cf41a19a1f2f3feab0e9c0b74134aa2ce6849093d5517a0c550fe37a648/pyyaml-6.0.3-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:fc09d0aa354569bc501d4e787133afc08552722d3ab34836a80547331bb5d4a0", size = 173973, upload-time = "2025-09-25T21:32:12.492Z" }, + { url = "https://files.pythonhosted.org/packages/ed/23/7a778b6bd0b9a8039df8b1b1d80e2e2ad78aa04171592c8a5c43a56a6af4/pyyaml-6.0.3-cp312-cp312-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:9149cad251584d5fb4981be1ecde53a1ca46c891a79788c0df828d2f166bda28", size = 775116, upload-time = "2025-09-25T21:32:13.652Z" }, + { url = "https://files.pythonhosted.org/packages/65/30/d7353c338e12baef4ecc1b09e877c1970bd3382789c159b4f89d6a70dc09/pyyaml-6.0.3-cp312-cp312-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:5fdec68f91a0c6739b380c83b951e2c72ac0197ace422360e6d5a959d8d97b2c", size = 844011, upload-time = "2025-09-25T21:32:15.21Z" }, + { url = "https://files.pythonhosted.org/packages/8b/9d/b3589d3877982d4f2329302ef98a8026e7f4443c765c46cfecc8858c6b4b/pyyaml-6.0.3-cp312-cp312-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:ba1cc08a7ccde2d2ec775841541641e4548226580ab850948cbfda66a1befcdc", size = 807870, upload-time = "2025-09-25T21:32:16.431Z" }, + { url = "https://files.pythonhosted.org/packages/05/c0/b3be26a015601b822b97d9149ff8cb5ead58c66f981e04fedf4e762f4bd4/pyyaml-6.0.3-cp312-cp312-musllinux_1_2_aarch64.whl", hash = "sha256:8dc52c23056b9ddd46818a57b78404882310fb473d63f17b07d5c40421e47f8e", size = 761089, upload-time = "2025-09-25T21:32:17.56Z" }, + { url = "https://files.pythonhosted.org/packages/be/8e/98435a21d1d4b46590d5459a22d88128103f8da4c2d4cb8f14f2a96504e1/pyyaml-6.0.3-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:41715c910c881bc081f1e8872880d3c650acf13dfa8214bad49ed4cede7c34ea", size = 790181, upload-time = "2025-09-25T21:32:18.834Z" }, + { url = "https://files.pythonhosted.org/packages/74/93/7baea19427dcfbe1e5a372d81473250b379f04b1bd3c4c5ff825e2327202/pyyaml-6.0.3-cp312-cp312-win32.whl", hash = "sha256:96b533f0e99f6579b3d4d4995707cf36df9100d67e0c8303a0c55b27b5f99bc5", size = 137658, upload-time = "2025-09-25T21:32:20.209Z" }, + { url = "https://files.pythonhosted.org/packages/86/bf/899e81e4cce32febab4fb42bb97dcdf66bc135272882d1987881a4b519e9/pyyaml-6.0.3-cp312-cp312-win_amd64.whl", hash = "sha256:5fcd34e47f6e0b794d17de1b4ff496c00986e1c83f7ab2fb8fcfe9616ff7477b", size = 154003, upload-time = "2025-09-25T21:32:21.167Z" }, + { url = "https://files.pythonhosted.org/packages/1a/08/67bd04656199bbb51dbed1439b7f27601dfb576fb864099c7ef0c3e55531/pyyaml-6.0.3-cp312-cp312-win_arm64.whl", hash = "sha256:64386e5e707d03a7e172c0701abfb7e10f0fb753ee1d773128192742712a98fd", size = 140344, upload-time = "2025-09-25T21:32:22.617Z" }, + { url = "https://files.pythonhosted.org/packages/d1/11/0fd08f8192109f7169db964b5707a2f1e8b745d4e239b784a5a1dd80d1db/pyyaml-6.0.3-cp313-cp313-macosx_10_13_x86_64.whl", hash = "sha256:8da9669d359f02c0b91ccc01cac4a67f16afec0dac22c2ad09f46bee0697eba8", size = 181669, upload-time = "2025-09-25T21:32:23.673Z" }, + { url = "https://files.pythonhosted.org/packages/b1/16/95309993f1d3748cd644e02e38b75d50cbc0d9561d21f390a76242ce073f/pyyaml-6.0.3-cp313-cp313-macosx_11_0_arm64.whl", hash = "sha256:2283a07e2c21a2aa78d9c4442724ec1eb15f5e42a723b99cb3d822d48f5f7ad1", size = 173252, upload-time = "2025-09-25T21:32:25.149Z" }, + { url = "https://files.pythonhosted.org/packages/50/31/b20f376d3f810b9b2371e72ef5adb33879b25edb7a6d072cb7ca0c486398/pyyaml-6.0.3-cp313-cp313-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:ee2922902c45ae8ccada2c5b501ab86c36525b883eff4255313a253a3160861c", size = 767081, upload-time = "2025-09-25T21:32:26.575Z" }, + { url = "https://files.pythonhosted.org/packages/49/1e/a55ca81e949270d5d4432fbbd19dfea5321eda7c41a849d443dc92fd1ff7/pyyaml-6.0.3-cp313-cp313-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:a33284e20b78bd4a18c8c2282d549d10bc8408a2a7ff57653c0cf0b9be0afce5", size = 841159, upload-time = "2025-09-25T21:32:27.727Z" }, + { url = "https://files.pythonhosted.org/packages/74/27/e5b8f34d02d9995b80abcef563ea1f8b56d20134d8f4e5e81733b1feceb2/pyyaml-6.0.3-cp313-cp313-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:0f29edc409a6392443abf94b9cf89ce99889a1dd5376d94316ae5145dfedd5d6", size = 801626, upload-time = "2025-09-25T21:32:28.878Z" }, + { url = "https://files.pythonhosted.org/packages/f9/11/ba845c23988798f40e52ba45f34849aa8a1f2d4af4b798588010792ebad6/pyyaml-6.0.3-cp313-cp313-musllinux_1_2_aarch64.whl", hash = "sha256:f7057c9a337546edc7973c0d3ba84ddcdf0daa14533c2065749c9075001090e6", size = 753613, upload-time = "2025-09-25T21:32:30.178Z" }, + { url = "https://files.pythonhosted.org/packages/3d/e0/7966e1a7bfc0a45bf0a7fb6b98ea03fc9b8d84fa7f2229e9659680b69ee3/pyyaml-6.0.3-cp313-cp313-musllinux_1_2_x86_64.whl", hash = "sha256:eda16858a3cab07b80edaf74336ece1f986ba330fdb8ee0d6c0d68fe82bc96be", size = 794115, upload-time = "2025-09-25T21:32:31.353Z" }, + { url = "https://files.pythonhosted.org/packages/de/94/980b50a6531b3019e45ddeada0626d45fa85cbe22300844a7983285bed3b/pyyaml-6.0.3-cp313-cp313-win32.whl", hash = "sha256:d0eae10f8159e8fdad514efdc92d74fd8d682c933a6dd088030f3834bc8e6b26", size = 137427, upload-time = "2025-09-25T21:32:32.58Z" }, + { url = "https://files.pythonhosted.org/packages/97/c9/39d5b874e8b28845e4ec2202b5da735d0199dbe5b8fb85f91398814a9a46/pyyaml-6.0.3-cp313-cp313-win_amd64.whl", hash = "sha256:79005a0d97d5ddabfeeea4cf676af11e647e41d81c9a7722a193022accdb6b7c", size = 154090, upload-time = "2025-09-25T21:32:33.659Z" }, + { url = "https://files.pythonhosted.org/packages/73/e8/2bdf3ca2090f68bb3d75b44da7bbc71843b19c9f2b9cb9b0f4ab7a5a4329/pyyaml-6.0.3-cp313-cp313-win_arm64.whl", hash = "sha256:5498cd1645aa724a7c71c8f378eb29ebe23da2fc0d7a08071d89469bf1d2defb", size = 140246, upload-time = "2025-09-25T21:32:34.663Z" }, + { url = "https://files.pythonhosted.org/packages/9d/8c/f4bd7f6465179953d3ac9bc44ac1a8a3e6122cf8ada906b4f96c60172d43/pyyaml-6.0.3-cp314-cp314-macosx_10_13_x86_64.whl", hash = "sha256:8d1fab6bb153a416f9aeb4b8763bc0f22a5586065f86f7664fc23339fc1c1fac", size = 181814, upload-time = "2025-09-25T21:32:35.712Z" }, + { url = "https://files.pythonhosted.org/packages/bd/9c/4d95bb87eb2063d20db7b60faa3840c1b18025517ae857371c4dd55a6b3a/pyyaml-6.0.3-cp314-cp314-macosx_11_0_arm64.whl", hash = "sha256:34d5fcd24b8445fadc33f9cf348c1047101756fd760b4dacb5c3e99755703310", size = 173809, upload-time = "2025-09-25T21:32:36.789Z" }, + { url = "https://files.pythonhosted.org/packages/92/b5/47e807c2623074914e29dabd16cbbdd4bf5e9b2db9f8090fa64411fc5382/pyyaml-6.0.3-cp314-cp314-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:501a031947e3a9025ed4405a168e6ef5ae3126c59f90ce0cd6f2bfc477be31b7", size = 766454, upload-time = "2025-09-25T21:32:37.966Z" }, + { url = "https://files.pythonhosted.org/packages/02/9e/e5e9b168be58564121efb3de6859c452fccde0ab093d8438905899a3a483/pyyaml-6.0.3-cp314-cp314-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:b3bc83488de33889877a0f2543ade9f70c67d66d9ebb4ac959502e12de895788", size = 836355, upload-time = "2025-09-25T21:32:39.178Z" }, + { url = "https://files.pythonhosted.org/packages/88/f9/16491d7ed2a919954993e48aa941b200f38040928474c9e85ea9e64222c3/pyyaml-6.0.3-cp314-cp314-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:c458b6d084f9b935061bc36216e8a69a7e293a2f1e68bf956dcd9e6cbcd143f5", size = 794175, upload-time = "2025-09-25T21:32:40.865Z" }, + { url = "https://files.pythonhosted.org/packages/dd/3f/5989debef34dc6397317802b527dbbafb2b4760878a53d4166579111411e/pyyaml-6.0.3-cp314-cp314-musllinux_1_2_aarch64.whl", hash = "sha256:7c6610def4f163542a622a73fb39f534f8c101d690126992300bf3207eab9764", size = 755228, upload-time = "2025-09-25T21:32:42.084Z" }, + { url = "https://files.pythonhosted.org/packages/d7/ce/af88a49043cd2e265be63d083fc75b27b6ed062f5f9fd6cdc223ad62f03e/pyyaml-6.0.3-cp314-cp314-musllinux_1_2_x86_64.whl", hash = "sha256:5190d403f121660ce8d1d2c1bb2ef1bd05b5f68533fc5c2ea899bd15f4399b35", size = 789194, upload-time = "2025-09-25T21:32:43.362Z" }, + { url = "https://files.pythonhosted.org/packages/23/20/bb6982b26a40bb43951265ba29d4c246ef0ff59c9fdcdf0ed04e0687de4d/pyyaml-6.0.3-cp314-cp314-win_amd64.whl", hash = "sha256:4a2e8cebe2ff6ab7d1050ecd59c25d4c8bd7e6f400f5f82b96557ac0abafd0ac", size = 156429, upload-time = "2025-09-25T21:32:57.844Z" }, + { url = "https://files.pythonhosted.org/packages/f4/f4/a4541072bb9422c8a883ab55255f918fa378ecf083f5b85e87fc2b4eda1b/pyyaml-6.0.3-cp314-cp314-win_arm64.whl", hash = "sha256:93dda82c9c22deb0a405ea4dc5f2d0cda384168e466364dec6255b293923b2f3", size = 143912, upload-time = "2025-09-25T21:32:59.247Z" }, + { url = "https://files.pythonhosted.org/packages/7c/f9/07dd09ae774e4616edf6cda684ee78f97777bdd15847253637a6f052a62f/pyyaml-6.0.3-cp314-cp314t-macosx_10_13_x86_64.whl", hash = "sha256:02893d100e99e03eda1c8fd5c441d8c60103fd175728e23e431db1b589cf5ab3", size = 189108, upload-time = "2025-09-25T21:32:44.377Z" }, + { url = "https://files.pythonhosted.org/packages/4e/78/8d08c9fb7ce09ad8c38ad533c1191cf27f7ae1effe5bb9400a46d9437fcf/pyyaml-6.0.3-cp314-cp314t-macosx_11_0_arm64.whl", hash = "sha256:c1ff362665ae507275af2853520967820d9124984e0f7466736aea23d8611fba", size = 183641, upload-time = "2025-09-25T21:32:45.407Z" }, + { url = "https://files.pythonhosted.org/packages/7b/5b/3babb19104a46945cf816d047db2788bcaf8c94527a805610b0289a01c6b/pyyaml-6.0.3-cp314-cp314t-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:6adc77889b628398debc7b65c073bcb99c4a0237b248cacaf3fe8a557563ef6c", size = 831901, upload-time = "2025-09-25T21:32:48.83Z" }, + { url = "https://files.pythonhosted.org/packages/8b/cc/dff0684d8dc44da4d22a13f35f073d558c268780ce3c6ba1b87055bb0b87/pyyaml-6.0.3-cp314-cp314t-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:a80cb027f6b349846a3bf6d73b5e95e782175e52f22108cfa17876aaeff93702", size = 861132, upload-time = "2025-09-25T21:32:50.149Z" }, + { url = "https://files.pythonhosted.org/packages/b1/5e/f77dc6b9036943e285ba76b49e118d9ea929885becb0a29ba8a7c75e29fe/pyyaml-6.0.3-cp314-cp314t-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:00c4bdeba853cc34e7dd471f16b4114f4162dc03e6b7afcc2128711f0eca823c", size = 839261, upload-time = "2025-09-25T21:32:51.808Z" }, + { url = "https://files.pythonhosted.org/packages/ce/88/a9db1376aa2a228197c58b37302f284b5617f56a5d959fd1763fb1675ce6/pyyaml-6.0.3-cp314-cp314t-musllinux_1_2_aarch64.whl", hash = "sha256:66e1674c3ef6f541c35191caae2d429b967b99e02040f5ba928632d9a7f0f065", size = 805272, upload-time = "2025-09-25T21:32:52.941Z" }, + { url = "https://files.pythonhosted.org/packages/da/92/1446574745d74df0c92e6aa4a7b0b3130706a4142b2d1a5869f2eaa423c6/pyyaml-6.0.3-cp314-cp314t-musllinux_1_2_x86_64.whl", hash = "sha256:16249ee61e95f858e83976573de0f5b2893b3677ba71c9dd36b9cf8be9ac6d65", size = 829923, upload-time = "2025-09-25T21:32:54.537Z" }, + { url = "https://files.pythonhosted.org/packages/f0/7a/1c7270340330e575b92f397352af856a8c06f230aa3e76f86b39d01b416a/pyyaml-6.0.3-cp314-cp314t-win_amd64.whl", hash = "sha256:4ad1906908f2f5ae4e5a8ddfce73c320c2a1429ec52eafd27138b7f1cbe341c9", size = 174062, upload-time = "2025-09-25T21:32:55.767Z" }, + { url = "https://files.pythonhosted.org/packages/f1/12/de94a39c2ef588c7e6455cfbe7343d3b2dc9d6b6b2f40c4c6565744c873d/pyyaml-6.0.3-cp314-cp314t-win_arm64.whl", hash = "sha256:ebc55a14a21cb14062aa4162f906cd962b28e2e9ea38f9b4391244cd8de4ae0b", size = 149341, upload-time = "2025-09-25T21:32:56.828Z" }, ] [[package]] @@ -1255,14 +1480,14 @@ source = { registry = "https://pypi.org/simple" } dependencies = [ { name = "pyyaml" }, ] -sdist = { url = "https://files.pythonhosted.org/packages/eb/2e/79c822141bfd05a853236b504869ebc6b70159afc570e1d5a20641782eaa/pyyaml_env_tag-1.1.tar.gz", hash = "sha256:2eb38b75a2d21ee0475d6d97ec19c63287a7e140231e4214969d0eac923cd7ff", size = 5737 } +sdist = { url = "https://files.pythonhosted.org/packages/eb/2e/79c822141bfd05a853236b504869ebc6b70159afc570e1d5a20641782eaa/pyyaml_env_tag-1.1.tar.gz", hash = "sha256:2eb38b75a2d21ee0475d6d97ec19c63287a7e140231e4214969d0eac923cd7ff", size = 5737, upload-time = "2025-05-13T15:24:01.64Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/04/11/432f32f8097b03e3cd5fe57e88efb685d964e2e5178a48ed61e841f7fdce/pyyaml_env_tag-1.1-py3-none-any.whl", hash = "sha256:17109e1a528561e32f026364712fee1264bc2ea6715120891174ed1b980d2e04", size = 4722 }, + { url = "https://files.pythonhosted.org/packages/04/11/432f32f8097b03e3cd5fe57e88efb685d964e2e5178a48ed61e841f7fdce/pyyaml_env_tag-1.1-py3-none-any.whl", hash = "sha256:17109e1a528561e32f026364712fee1264bc2ea6715120891174ed1b980d2e04", size = 4722, upload-time = "2025-05-13T15:23:59.629Z" }, ] [[package]] name = "requests" -version = "2.32.4" +version = "2.32.5" source = { registry = "https://pypi.org/simple" } dependencies = [ { name = "certifi" }, @@ -1270,45 +1495,44 @@ dependencies = [ { name = "idna" }, { name = "urllib3" }, ] -sdist = { url = "https://files.pythonhosted.org/packages/e1/0a/929373653770d8a0d7ea76c37de6e41f11eb07559b103b1c02cafb3f7cf8/requests-2.32.4.tar.gz", hash = "sha256:27d0316682c8a29834d3264820024b62a36942083d52caf2f14c0591336d3422", size = 135258 } +sdist = { url = "https://files.pythonhosted.org/packages/c9/74/b3ff8e6c8446842c3f5c837e9c3dfcfe2018ea6ecef224c710c85ef728f4/requests-2.32.5.tar.gz", hash = "sha256:dbba0bac56e100853db0ea71b82b4dfd5fe2bf6d3754a8893c3af500cec7d7cf", size = 134517, upload-time = "2025-08-18T20:46:02.573Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/7c/e4/56027c4a6b4ae70ca9de302488c5ca95ad4a39e190093d6c1a8ace08341b/requests-2.32.4-py3-none-any.whl", hash = "sha256:27babd3cda2a6d50b30443204ee89830707d396671944c998b5975b031ac2b2c", size = 64847 }, + { url = "https://files.pythonhosted.org/packages/1e/db/4254e3eabe8020b458f1a747140d32277ec7a271daf1d235b70dc0b4e6e3/requests-2.32.5-py3-none-any.whl", hash = "sha256:2462f94637a34fd532264295e186976db0f5d453d1cdd31473c85a6a161affb6", size = 64738, upload-time = "2025-08-18T20:46:00.542Z" }, ] [[package]] name = "rich" -version = "14.0.0" +version = "14.1.0" source = { registry = "https://pypi.org/simple" } dependencies = [ { name = "markdown-it-py" }, { name = "pygments" }, - { name = "typing-extensions", marker = "python_full_version < '3.11'" }, ] -sdist = { url = "https://files.pythonhosted.org/packages/a1/53/830aa4c3066a8ab0ae9a9955976fb770fe9c6102117c8ec4ab3ea62d89e8/rich-14.0.0.tar.gz", hash = "sha256:82f1bc23a6a21ebca4ae0c45af9bdbc492ed20231dcb63f297d6d1021a9d5725", size = 224078 } +sdist = { url = "https://files.pythonhosted.org/packages/fe/75/af448d8e52bf1d8fa6a9d089ca6c07ff4453d86c65c145d0a300bb073b9b/rich-14.1.0.tar.gz", hash = "sha256:e497a48b844b0320d45007cdebfeaeed8db2a4f4bcf49f15e455cfc4af11eaa8", size = 224441, upload-time = "2025-07-25T07:32:58.125Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/0d/9b/63f4c7ebc259242c89b3acafdb37b41d1185c07ff0011164674e9076b491/rich-14.0.0-py3-none-any.whl", hash = "sha256:1c9491e1951aac09caffd42f448ee3d04e58923ffe14993f6e83068dc395d7e0", size = 243229 }, + { url = "https://files.pythonhosted.org/packages/e3/30/3c4d035596d3cf444529e0b2953ad0466f6049528a879d27534700580395/rich-14.1.0-py3-none-any.whl", hash = "sha256:536f5f1785986d6dbdea3c75205c473f970777b4a0d6c6dd1b696aa05a3fa04f", size = 243368, upload-time = "2025-07-25T07:32:56.73Z" }, ] [[package]] name = "safetensors" -version = "0.5.3" +version = "0.6.2" source = { registry = "https://pypi.org/simple" } -sdist = { url = "https://files.pythonhosted.org/packages/71/7e/2d5d6ee7b40c0682315367ec7475693d110f512922d582fef1bd4a63adc3/safetensors-0.5.3.tar.gz", hash = "sha256:b6b0d6ecacec39a4fdd99cc19f4576f5219ce858e6fd8dbe7609df0b8dc56965", size = 67210 } +sdist = { url = "https://files.pythonhosted.org/packages/ac/cc/738f3011628920e027a11754d9cae9abec1aed00f7ae860abbf843755233/safetensors-0.6.2.tar.gz", hash = "sha256:43ff2aa0e6fa2dc3ea5524ac7ad93a9839256b8703761e76e2d0b2a3fa4f15d9", size = 197968, upload-time = "2025-08-08T13:13:58.654Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/18/ae/88f6c49dbd0cc4da0e08610019a3c78a7d390879a919411a410a1876d03a/safetensors-0.5.3-cp38-abi3-macosx_10_12_x86_64.whl", hash = "sha256:bd20eb133db8ed15b40110b7c00c6df51655a2998132193de2f75f72d99c7073", size = 436917 }, - { url = "https://files.pythonhosted.org/packages/b8/3b/11f1b4a2f5d2ab7da34ecc062b0bc301f2be024d110a6466726bec8c055c/safetensors-0.5.3-cp38-abi3-macosx_11_0_arm64.whl", hash = "sha256:21d01c14ff6c415c485616b8b0bf961c46b3b343ca59110d38d744e577f9cce7", size = 418419 }, - { url = "https://files.pythonhosted.org/packages/5d/9a/add3e6fef267658075c5a41573c26d42d80c935cdc992384dfae435feaef/safetensors-0.5.3-cp38-abi3-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:11bce6164887cd491ca75c2326a113ba934be596e22b28b1742ce27b1d076467", size = 459493 }, - { url = "https://files.pythonhosted.org/packages/df/5c/bf2cae92222513cc23b3ff85c4a1bb2811a2c3583ac0f8e8d502751de934/safetensors-0.5.3-cp38-abi3-manylinux_2_17_armv7l.manylinux2014_armv7l.whl", hash = "sha256:4a243be3590bc3301c821da7a18d87224ef35cbd3e5f5727e4e0728b8172411e", size = 472400 }, - { url = "https://files.pythonhosted.org/packages/58/11/7456afb740bd45782d0f4c8e8e1bb9e572f1bf82899fb6ace58af47b4282/safetensors-0.5.3-cp38-abi3-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:8bd84b12b1670a6f8e50f01e28156422a2bc07fb16fc4e98bded13039d688a0d", size = 522891 }, - { url = "https://files.pythonhosted.org/packages/57/3d/fe73a9d2ace487e7285f6e157afee2383bd1ddb911b7cb44a55cf812eae3/safetensors-0.5.3-cp38-abi3-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:391ac8cab7c829452175f871fcaf414aa1e292b5448bd02620f675a7f3e7abb9", size = 537694 }, - { url = "https://files.pythonhosted.org/packages/a6/f8/dae3421624fcc87a89d42e1898a798bc7ff72c61f38973a65d60df8f124c/safetensors-0.5.3-cp38-abi3-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:cead1fa41fc54b1e61089fa57452e8834f798cb1dc7a09ba3524f1eb08e0317a", size = 471642 }, - { url = "https://files.pythonhosted.org/packages/ce/20/1fbe16f9b815f6c5a672f5b760951e20e17e43f67f231428f871909a37f6/safetensors-0.5.3-cp38-abi3-manylinux_2_5_i686.manylinux1_i686.whl", hash = "sha256:1077f3e94182d72618357b04b5ced540ceb71c8a813d3319f1aba448e68a770d", size = 502241 }, - { url = "https://files.pythonhosted.org/packages/5f/18/8e108846b506487aa4629fe4116b27db65c3dde922de2c8e0cc1133f3f29/safetensors-0.5.3-cp38-abi3-musllinux_1_2_aarch64.whl", hash = "sha256:799021e78287bac619c7b3f3606730a22da4cda27759ddf55d37c8db7511c74b", size = 638001 }, - { url = "https://files.pythonhosted.org/packages/82/5a/c116111d8291af6c8c8a8b40628fe833b9db97d8141c2a82359d14d9e078/safetensors-0.5.3-cp38-abi3-musllinux_1_2_armv7l.whl", hash = "sha256:df26da01aaac504334644e1b7642fa000bfec820e7cef83aeac4e355e03195ff", size = 734013 }, - { url = "https://files.pythonhosted.org/packages/7d/ff/41fcc4d3b7de837963622e8610d998710705bbde9a8a17221d85e5d0baad/safetensors-0.5.3-cp38-abi3-musllinux_1_2_i686.whl", hash = "sha256:32c3ef2d7af8b9f52ff685ed0bc43913cdcde135089ae322ee576de93eae5135", size = 670687 }, - { url = "https://files.pythonhosted.org/packages/40/ad/2b113098e69c985a3d8fbda4b902778eae4a35b7d5188859b4a63d30c161/safetensors-0.5.3-cp38-abi3-musllinux_1_2_x86_64.whl", hash = "sha256:37f1521be045e56fc2b54c606d4455573e717b2d887c579ee1dbba5f868ece04", size = 643147 }, - { url = "https://files.pythonhosted.org/packages/0a/0c/95aeb51d4246bd9a3242d3d8349c1112b4ee7611a4b40f0c5c93b05f001d/safetensors-0.5.3-cp38-abi3-win32.whl", hash = "sha256:cfc0ec0846dcf6763b0ed3d1846ff36008c6e7290683b61616c4b040f6a54ace", size = 296677 }, - { url = "https://files.pythonhosted.org/packages/69/e2/b011c38e5394c4c18fb5500778a55ec43ad6106126e74723ffaee246f56e/safetensors-0.5.3-cp38-abi3-win_amd64.whl", hash = "sha256:836cbbc320b47e80acd40e44c8682db0e8ad7123209f69b093def21ec7cafd11", size = 308878 }, + { url = "https://files.pythonhosted.org/packages/4d/b1/3f5fd73c039fc87dba3ff8b5d528bfc5a32b597fea8e7a6a4800343a17c7/safetensors-0.6.2-cp38-abi3-macosx_10_12_x86_64.whl", hash = "sha256:9c85ede8ec58f120bad982ec47746981e210492a6db876882aa021446af8ffba", size = 454797, upload-time = "2025-08-08T13:13:52.066Z" }, + { url = "https://files.pythonhosted.org/packages/8c/c9/bb114c158540ee17907ec470d01980957fdaf87b4aa07914c24eba87b9c6/safetensors-0.6.2-cp38-abi3-macosx_11_0_arm64.whl", hash = "sha256:d6675cf4b39c98dbd7d940598028f3742e0375a6b4d4277e76beb0c35f4b843b", size = 432206, upload-time = "2025-08-08T13:13:50.931Z" }, + { url = "https://files.pythonhosted.org/packages/d3/8e/f70c34e47df3110e8e0bb268d90db8d4be8958a54ab0336c9be4fe86dac8/safetensors-0.6.2-cp38-abi3-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:1d2d2b3ce1e2509c68932ca03ab8f20570920cd9754b05063d4368ee52833ecd", size = 473261, upload-time = "2025-08-08T13:13:41.259Z" }, + { url = "https://files.pythonhosted.org/packages/2a/f5/be9c6a7c7ef773e1996dc214e73485286df1836dbd063e8085ee1976f9cb/safetensors-0.6.2-cp38-abi3-manylinux_2_17_armv7l.manylinux2014_armv7l.whl", hash = "sha256:93de35a18f46b0f5a6a1f9e26d91b442094f2df02e9fd7acf224cfec4238821a", size = 485117, upload-time = "2025-08-08T13:13:43.506Z" }, + { url = "https://files.pythonhosted.org/packages/c9/55/23f2d0a2c96ed8665bf17a30ab4ce5270413f4d74b6d87dd663258b9af31/safetensors-0.6.2-cp38-abi3-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:89a89b505f335640f9120fac65ddeb83e40f1fd081cb8ed88b505bdccec8d0a1", size = 616154, upload-time = "2025-08-08T13:13:45.096Z" }, + { url = "https://files.pythonhosted.org/packages/98/c6/affb0bd9ce02aa46e7acddbe087912a04d953d7a4d74b708c91b5806ef3f/safetensors-0.6.2-cp38-abi3-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:fc4d0d0b937e04bdf2ae6f70cd3ad51328635fe0e6214aa1fc811f3b576b3bda", size = 520713, upload-time = "2025-08-08T13:13:46.25Z" }, + { url = "https://files.pythonhosted.org/packages/fe/5d/5a514d7b88e310c8b146e2404e0dc161282e78634d9358975fd56dfd14be/safetensors-0.6.2-cp38-abi3-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:8045db2c872db8f4cbe3faa0495932d89c38c899c603f21e9b6486951a5ecb8f", size = 485835, upload-time = "2025-08-08T13:13:49.373Z" }, + { url = "https://files.pythonhosted.org/packages/7a/7b/4fc3b2ba62c352b2071bea9cfbad330fadda70579f617506ae1a2f129cab/safetensors-0.6.2-cp38-abi3-manylinux_2_5_i686.manylinux1_i686.whl", hash = "sha256:81e67e8bab9878bb568cffbc5f5e655adb38d2418351dc0859ccac158f753e19", size = 521503, upload-time = "2025-08-08T13:13:47.651Z" }, + { url = "https://files.pythonhosted.org/packages/5a/50/0057e11fe1f3cead9254315a6c106a16dd4b1a19cd247f7cc6414f6b7866/safetensors-0.6.2-cp38-abi3-musllinux_1_2_aarch64.whl", hash = "sha256:b0e4d029ab0a0e0e4fdf142b194514695b1d7d3735503ba700cf36d0fc7136ce", size = 652256, upload-time = "2025-08-08T13:13:53.167Z" }, + { url = "https://files.pythonhosted.org/packages/e9/29/473f789e4ac242593ac1656fbece6e1ecd860bb289e635e963667807afe3/safetensors-0.6.2-cp38-abi3-musllinux_1_2_armv7l.whl", hash = "sha256:fa48268185c52bfe8771e46325a1e21d317207bcabcb72e65c6e28e9ffeb29c7", size = 747281, upload-time = "2025-08-08T13:13:54.656Z" }, + { url = "https://files.pythonhosted.org/packages/68/52/f7324aad7f2df99e05525c84d352dc217e0fa637a4f603e9f2eedfbe2c67/safetensors-0.6.2-cp38-abi3-musllinux_1_2_i686.whl", hash = "sha256:d83c20c12c2d2f465997c51b7ecb00e407e5f94d7dec3ea0cc11d86f60d3fde5", size = 692286, upload-time = "2025-08-08T13:13:55.884Z" }, + { url = "https://files.pythonhosted.org/packages/ad/fe/cad1d9762868c7c5dc70c8620074df28ebb1a8e4c17d4c0cb031889c457e/safetensors-0.6.2-cp38-abi3-musllinux_1_2_x86_64.whl", hash = "sha256:d944cea65fad0ead848b6ec2c37cc0b197194bec228f8020054742190e9312ac", size = 655957, upload-time = "2025-08-08T13:13:57.029Z" }, + { url = "https://files.pythonhosted.org/packages/59/a7/e2158e17bbe57d104f0abbd95dff60dda916cf277c9f9663b4bf9bad8b6e/safetensors-0.6.2-cp38-abi3-win32.whl", hash = "sha256:cab75ca7c064d3911411461151cb69380c9225798a20e712b102edda2542ddb1", size = 308926, upload-time = "2025-08-08T13:14:01.095Z" }, + { url = "https://files.pythonhosted.org/packages/2c/c3/c0be1135726618dc1e28d181b8c442403d8dbb9e273fd791de2d4384bcdd/safetensors-0.6.2-cp38-abi3-win_amd64.whl", hash = "sha256:c7b214870df923cbc1593c3faee16bec59ea462758699bd3fee399d00aac072c", size = 320192, upload-time = "2025-08-08T13:13:59.467Z" }, ] [[package]] @@ -1321,58 +1545,58 @@ resolution-markers = [ dependencies = [ { name = "numpy", version = "2.2.6", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version < '3.11'" }, ] -sdist = { url = "https://files.pythonhosted.org/packages/0f/37/6964b830433e654ec7485e45a00fc9a27cf868d622838f6b6d9c5ec0d532/scipy-1.15.3.tar.gz", hash = "sha256:eae3cf522bc7df64b42cad3925c876e1b0b6c35c1337c93e12c0f366f55b0eaf", size = 59419214 } -wheels = [ - { url = "https://files.pythonhosted.org/packages/78/2f/4966032c5f8cc7e6a60f1b2e0ad686293b9474b65246b0c642e3ef3badd0/scipy-1.15.3-cp310-cp310-macosx_10_13_x86_64.whl", hash = "sha256:a345928c86d535060c9c2b25e71e87c39ab2f22fc96e9636bd74d1dbf9de448c", size = 38702770 }, - { url = "https://files.pythonhosted.org/packages/a0/6e/0c3bf90fae0e910c274db43304ebe25a6b391327f3f10b5dcc638c090795/scipy-1.15.3-cp310-cp310-macosx_12_0_arm64.whl", hash = "sha256:ad3432cb0f9ed87477a8d97f03b763fd1d57709f1bbde3c9369b1dff5503b253", size = 30094511 }, - { url = "https://files.pythonhosted.org/packages/ea/b1/4deb37252311c1acff7f101f6453f0440794f51b6eacb1aad4459a134081/scipy-1.15.3-cp310-cp310-macosx_14_0_arm64.whl", hash = "sha256:aef683a9ae6eb00728a542b796f52a5477b78252edede72b8327a886ab63293f", size = 22368151 }, - { url = "https://files.pythonhosted.org/packages/38/7d/f457626e3cd3c29b3a49ca115a304cebb8cc6f31b04678f03b216899d3c6/scipy-1.15.3-cp310-cp310-macosx_14_0_x86_64.whl", hash = "sha256:1c832e1bd78dea67d5c16f786681b28dd695a8cb1fb90af2e27580d3d0967e92", size = 25121732 }, - { url = "https://files.pythonhosted.org/packages/db/0a/92b1de4a7adc7a15dcf5bddc6e191f6f29ee663b30511ce20467ef9b82e4/scipy-1.15.3-cp310-cp310-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:263961f658ce2165bbd7b99fa5135195c3a12d9bef045345016b8b50c315cb82", size = 35547617 }, - { url = "https://files.pythonhosted.org/packages/8e/6d/41991e503e51fc1134502694c5fa7a1671501a17ffa12716a4a9151af3df/scipy-1.15.3-cp310-cp310-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:9e2abc762b0811e09a0d3258abee2d98e0c703eee49464ce0069590846f31d40", size = 37662964 }, - { url = "https://files.pythonhosted.org/packages/25/e1/3df8f83cb15f3500478c889be8fb18700813b95e9e087328230b98d547ff/scipy-1.15.3-cp310-cp310-musllinux_1_2_aarch64.whl", hash = "sha256:ed7284b21a7a0c8f1b6e5977ac05396c0d008b89e05498c8b7e8f4a1423bba0e", size = 37238749 }, - { url = "https://files.pythonhosted.org/packages/93/3e/b3257cf446f2a3533ed7809757039016b74cd6f38271de91682aa844cfc5/scipy-1.15.3-cp310-cp310-musllinux_1_2_x86_64.whl", hash = "sha256:5380741e53df2c566f4d234b100a484b420af85deb39ea35a1cc1be84ff53a5c", size = 40022383 }, - { url = "https://files.pythonhosted.org/packages/d1/84/55bc4881973d3f79b479a5a2e2df61c8c9a04fcb986a213ac9c02cfb659b/scipy-1.15.3-cp310-cp310-win_amd64.whl", hash = "sha256:9d61e97b186a57350f6d6fd72640f9e99d5a4a2b8fbf4b9ee9a841eab327dc13", size = 41259201 }, - { url = "https://files.pythonhosted.org/packages/96/ab/5cc9f80f28f6a7dff646c5756e559823614a42b1939d86dd0ed550470210/scipy-1.15.3-cp311-cp311-macosx_10_13_x86_64.whl", hash = "sha256:993439ce220d25e3696d1b23b233dd010169b62f6456488567e830654ee37a6b", size = 38714255 }, - { url = "https://files.pythonhosted.org/packages/4a/4a/66ba30abe5ad1a3ad15bfb0b59d22174012e8056ff448cb1644deccbfed2/scipy-1.15.3-cp311-cp311-macosx_12_0_arm64.whl", hash = "sha256:34716e281f181a02341ddeaad584205bd2fd3c242063bd3423d61ac259ca7eba", size = 30111035 }, - { url = "https://files.pythonhosted.org/packages/4b/fa/a7e5b95afd80d24313307f03624acc65801846fa75599034f8ceb9e2cbf6/scipy-1.15.3-cp311-cp311-macosx_14_0_arm64.whl", hash = "sha256:3b0334816afb8b91dab859281b1b9786934392aa3d527cd847e41bb6f45bee65", size = 22384499 }, - { url = "https://files.pythonhosted.org/packages/17/99/f3aaddccf3588bb4aea70ba35328c204cadd89517a1612ecfda5b2dd9d7a/scipy-1.15.3-cp311-cp311-macosx_14_0_x86_64.whl", hash = "sha256:6db907c7368e3092e24919b5e31c76998b0ce1684d51a90943cb0ed1b4ffd6c1", size = 25152602 }, - { url = "https://files.pythonhosted.org/packages/56/c5/1032cdb565f146109212153339f9cb8b993701e9fe56b1c97699eee12586/scipy-1.15.3-cp311-cp311-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:721d6b4ef5dc82ca8968c25b111e307083d7ca9091bc38163fb89243e85e3889", size = 35503415 }, - { url = "https://files.pythonhosted.org/packages/bd/37/89f19c8c05505d0601ed5650156e50eb881ae3918786c8fd7262b4ee66d3/scipy-1.15.3-cp311-cp311-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:39cb9c62e471b1bb3750066ecc3a3f3052b37751c7c3dfd0fd7e48900ed52982", size = 37652622 }, - { url = "https://files.pythonhosted.org/packages/7e/31/be59513aa9695519b18e1851bb9e487de66f2d31f835201f1b42f5d4d475/scipy-1.15.3-cp311-cp311-musllinux_1_2_aarch64.whl", hash = "sha256:795c46999bae845966368a3c013e0e00947932d68e235702b5c3f6ea799aa8c9", size = 37244796 }, - { url = "https://files.pythonhosted.org/packages/10/c0/4f5f3eeccc235632aab79b27a74a9130c6c35df358129f7ac8b29f562ac7/scipy-1.15.3-cp311-cp311-musllinux_1_2_x86_64.whl", hash = "sha256:18aaacb735ab38b38db42cb01f6b92a2d0d4b6aabefeb07f02849e47f8fb3594", size = 40047684 }, - { url = "https://files.pythonhosted.org/packages/ab/a7/0ddaf514ce8a8714f6ed243a2b391b41dbb65251affe21ee3077ec45ea9a/scipy-1.15.3-cp311-cp311-win_amd64.whl", hash = "sha256:ae48a786a28412d744c62fd7816a4118ef97e5be0bee968ce8f0a2fba7acf3bb", size = 41246504 }, - { url = "https://files.pythonhosted.org/packages/37/4b/683aa044c4162e10ed7a7ea30527f2cbd92e6999c10a8ed8edb253836e9c/scipy-1.15.3-cp312-cp312-macosx_10_13_x86_64.whl", hash = "sha256:6ac6310fdbfb7aa6612408bd2f07295bcbd3fda00d2d702178434751fe48e019", size = 38766735 }, - { url = "https://files.pythonhosted.org/packages/7b/7e/f30be3d03de07f25dc0ec926d1681fed5c732d759ac8f51079708c79e680/scipy-1.15.3-cp312-cp312-macosx_12_0_arm64.whl", hash = "sha256:185cd3d6d05ca4b44a8f1595af87f9c372bb6acf9c808e99aa3e9aa03bd98cf6", size = 30173284 }, - { url = "https://files.pythonhosted.org/packages/07/9c/0ddb0d0abdabe0d181c1793db51f02cd59e4901da6f9f7848e1f96759f0d/scipy-1.15.3-cp312-cp312-macosx_14_0_arm64.whl", hash = "sha256:05dc6abcd105e1a29f95eada46d4a3f251743cfd7d3ae8ddb4088047f24ea477", size = 22446958 }, - { url = "https://files.pythonhosted.org/packages/af/43/0bce905a965f36c58ff80d8bea33f1f9351b05fad4beaad4eae34699b7a1/scipy-1.15.3-cp312-cp312-macosx_14_0_x86_64.whl", hash = "sha256:06efcba926324df1696931a57a176c80848ccd67ce6ad020c810736bfd58eb1c", size = 25242454 }, - { url = "https://files.pythonhosted.org/packages/56/30/a6f08f84ee5b7b28b4c597aca4cbe545535c39fe911845a96414700b64ba/scipy-1.15.3-cp312-cp312-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:c05045d8b9bfd807ee1b9f38761993297b10b245f012b11b13b91ba8945f7e45", size = 35210199 }, - { url = "https://files.pythonhosted.org/packages/0b/1f/03f52c282437a168ee2c7c14a1a0d0781a9a4a8962d84ac05c06b4c5b555/scipy-1.15.3-cp312-cp312-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:271e3713e645149ea5ea3e97b57fdab61ce61333f97cfae392c28ba786f9bb49", size = 37309455 }, - { url = "https://files.pythonhosted.org/packages/89/b1/fbb53137f42c4bf630b1ffdfc2151a62d1d1b903b249f030d2b1c0280af8/scipy-1.15.3-cp312-cp312-musllinux_1_2_aarch64.whl", hash = "sha256:6cfd56fc1a8e53f6e89ba3a7a7251f7396412d655bca2aa5611c8ec9a6784a1e", size = 36885140 }, - { url = "https://files.pythonhosted.org/packages/2e/2e/025e39e339f5090df1ff266d021892694dbb7e63568edcfe43f892fa381d/scipy-1.15.3-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:0ff17c0bb1cb32952c09217d8d1eed9b53d1463e5f1dd6052c7857f83127d539", size = 39710549 }, - { url = "https://files.pythonhosted.org/packages/e6/eb/3bf6ea8ab7f1503dca3a10df2e4b9c3f6b3316df07f6c0ded94b281c7101/scipy-1.15.3-cp312-cp312-win_amd64.whl", hash = "sha256:52092bc0472cfd17df49ff17e70624345efece4e1a12b23783a1ac59a1b728ed", size = 40966184 }, - { url = "https://files.pythonhosted.org/packages/73/18/ec27848c9baae6e0d6573eda6e01a602e5649ee72c27c3a8aad673ebecfd/scipy-1.15.3-cp313-cp313-macosx_10_13_x86_64.whl", hash = "sha256:2c620736bcc334782e24d173c0fdbb7590a0a436d2fdf39310a8902505008759", size = 38728256 }, - { url = "https://files.pythonhosted.org/packages/74/cd/1aef2184948728b4b6e21267d53b3339762c285a46a274ebb7863c9e4742/scipy-1.15.3-cp313-cp313-macosx_12_0_arm64.whl", hash = "sha256:7e11270a000969409d37ed399585ee530b9ef6aa99d50c019de4cb01e8e54e62", size = 30109540 }, - { url = "https://files.pythonhosted.org/packages/5b/d8/59e452c0a255ec352bd0a833537a3bc1bfb679944c4938ab375b0a6b3a3e/scipy-1.15.3-cp313-cp313-macosx_14_0_arm64.whl", hash = "sha256:8c9ed3ba2c8a2ce098163a9bdb26f891746d02136995df25227a20e71c396ebb", size = 22383115 }, - { url = "https://files.pythonhosted.org/packages/08/f5/456f56bbbfccf696263b47095291040655e3cbaf05d063bdc7c7517f32ac/scipy-1.15.3-cp313-cp313-macosx_14_0_x86_64.whl", hash = "sha256:0bdd905264c0c9cfa74a4772cdb2070171790381a5c4d312c973382fc6eaf730", size = 25163884 }, - { url = "https://files.pythonhosted.org/packages/a2/66/a9618b6a435a0f0c0b8a6d0a2efb32d4ec5a85f023c2b79d39512040355b/scipy-1.15.3-cp313-cp313-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:79167bba085c31f38603e11a267d862957cbb3ce018d8b38f79ac043bc92d825", size = 35174018 }, - { url = "https://files.pythonhosted.org/packages/b5/09/c5b6734a50ad4882432b6bb7c02baf757f5b2f256041da5df242e2d7e6b6/scipy-1.15.3-cp313-cp313-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:c9deabd6d547aee2c9a81dee6cc96c6d7e9a9b1953f74850c179f91fdc729cb7", size = 37269716 }, - { url = "https://files.pythonhosted.org/packages/77/0a/eac00ff741f23bcabd352731ed9b8995a0a60ef57f5fd788d611d43d69a1/scipy-1.15.3-cp313-cp313-musllinux_1_2_aarch64.whl", hash = "sha256:dde4fc32993071ac0c7dd2d82569e544f0bdaff66269cb475e0f369adad13f11", size = 36872342 }, - { url = "https://files.pythonhosted.org/packages/fe/54/4379be86dd74b6ad81551689107360d9a3e18f24d20767a2d5b9253a3f0a/scipy-1.15.3-cp313-cp313-musllinux_1_2_x86_64.whl", hash = "sha256:f77f853d584e72e874d87357ad70f44b437331507d1c311457bed8ed2b956126", size = 39670869 }, - { url = "https://files.pythonhosted.org/packages/87/2e/892ad2862ba54f084ffe8cc4a22667eaf9c2bcec6d2bff1d15713c6c0703/scipy-1.15.3-cp313-cp313-win_amd64.whl", hash = "sha256:b90ab29d0c37ec9bf55424c064312930ca5f4bde15ee8619ee44e69319aab163", size = 40988851 }, - { url = "https://files.pythonhosted.org/packages/1b/e9/7a879c137f7e55b30d75d90ce3eb468197646bc7b443ac036ae3fe109055/scipy-1.15.3-cp313-cp313t-macosx_10_13_x86_64.whl", hash = "sha256:3ac07623267feb3ae308487c260ac684b32ea35fd81e12845039952f558047b8", size = 38863011 }, - { url = "https://files.pythonhosted.org/packages/51/d1/226a806bbd69f62ce5ef5f3ffadc35286e9fbc802f606a07eb83bf2359de/scipy-1.15.3-cp313-cp313t-macosx_12_0_arm64.whl", hash = "sha256:6487aa99c2a3d509a5227d9a5e889ff05830a06b2ce08ec30df6d79db5fcd5c5", size = 30266407 }, - { url = "https://files.pythonhosted.org/packages/e5/9b/f32d1d6093ab9eeabbd839b0f7619c62e46cc4b7b6dbf05b6e615bbd4400/scipy-1.15.3-cp313-cp313t-macosx_14_0_arm64.whl", hash = "sha256:50f9e62461c95d933d5c5ef4a1f2ebf9a2b4e83b0db374cb3f1de104d935922e", size = 22540030 }, - { url = "https://files.pythonhosted.org/packages/e7/29/c278f699b095c1a884f29fda126340fcc201461ee8bfea5c8bdb1c7c958b/scipy-1.15.3-cp313-cp313t-macosx_14_0_x86_64.whl", hash = "sha256:14ed70039d182f411ffc74789a16df3835e05dc469b898233a245cdfd7f162cb", size = 25218709 }, - { url = "https://files.pythonhosted.org/packages/24/18/9e5374b617aba742a990581373cd6b68a2945d65cc588482749ef2e64467/scipy-1.15.3-cp313-cp313t-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:0a769105537aa07a69468a0eefcd121be52006db61cdd8cac8a0e68980bbb723", size = 34809045 }, - { url = "https://files.pythonhosted.org/packages/e1/fe/9c4361e7ba2927074360856db6135ef4904d505e9b3afbbcb073c4008328/scipy-1.15.3-cp313-cp313t-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:9db984639887e3dffb3928d118145ffe40eff2fa40cb241a306ec57c219ebbbb", size = 36703062 }, - { url = "https://files.pythonhosted.org/packages/b7/8e/038ccfe29d272b30086b25a4960f757f97122cb2ec42e62b460d02fe98e9/scipy-1.15.3-cp313-cp313t-musllinux_1_2_aarch64.whl", hash = "sha256:40e54d5c7e7ebf1aa596c374c49fa3135f04648a0caabcb66c52884b943f02b4", size = 36393132 }, - { url = "https://files.pythonhosted.org/packages/10/7e/5c12285452970be5bdbe8352c619250b97ebf7917d7a9a9e96b8a8140f17/scipy-1.15.3-cp313-cp313t-musllinux_1_2_x86_64.whl", hash = "sha256:5e721fed53187e71d0ccf382b6bf977644c533e506c4d33c3fb24de89f5c3ed5", size = 38979503 }, - { url = "https://files.pythonhosted.org/packages/81/06/0a5e5349474e1cbc5757975b21bd4fad0e72ebf138c5592f191646154e06/scipy-1.15.3-cp313-cp313t-win_amd64.whl", hash = "sha256:76ad1fb5f8752eabf0fa02e4cc0336b4e8f021e2d5f061ed37d6d264db35e3ca", size = 40308097 }, +sdist = { url = "https://files.pythonhosted.org/packages/0f/37/6964b830433e654ec7485e45a00fc9a27cf868d622838f6b6d9c5ec0d532/scipy-1.15.3.tar.gz", hash = "sha256:eae3cf522bc7df64b42cad3925c876e1b0b6c35c1337c93e12c0f366f55b0eaf", size = 59419214, upload-time = "2025-05-08T16:13:05.955Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/78/2f/4966032c5f8cc7e6a60f1b2e0ad686293b9474b65246b0c642e3ef3badd0/scipy-1.15.3-cp310-cp310-macosx_10_13_x86_64.whl", hash = "sha256:a345928c86d535060c9c2b25e71e87c39ab2f22fc96e9636bd74d1dbf9de448c", size = 38702770, upload-time = "2025-05-08T16:04:20.849Z" }, + { url = "https://files.pythonhosted.org/packages/a0/6e/0c3bf90fae0e910c274db43304ebe25a6b391327f3f10b5dcc638c090795/scipy-1.15.3-cp310-cp310-macosx_12_0_arm64.whl", hash = "sha256:ad3432cb0f9ed87477a8d97f03b763fd1d57709f1bbde3c9369b1dff5503b253", size = 30094511, upload-time = "2025-05-08T16:04:27.103Z" }, + { url = "https://files.pythonhosted.org/packages/ea/b1/4deb37252311c1acff7f101f6453f0440794f51b6eacb1aad4459a134081/scipy-1.15.3-cp310-cp310-macosx_14_0_arm64.whl", hash = "sha256:aef683a9ae6eb00728a542b796f52a5477b78252edede72b8327a886ab63293f", size = 22368151, upload-time = "2025-05-08T16:04:31.731Z" }, + { url = "https://files.pythonhosted.org/packages/38/7d/f457626e3cd3c29b3a49ca115a304cebb8cc6f31b04678f03b216899d3c6/scipy-1.15.3-cp310-cp310-macosx_14_0_x86_64.whl", hash = "sha256:1c832e1bd78dea67d5c16f786681b28dd695a8cb1fb90af2e27580d3d0967e92", size = 25121732, upload-time = "2025-05-08T16:04:36.596Z" }, + { url = "https://files.pythonhosted.org/packages/db/0a/92b1de4a7adc7a15dcf5bddc6e191f6f29ee663b30511ce20467ef9b82e4/scipy-1.15.3-cp310-cp310-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:263961f658ce2165bbd7b99fa5135195c3a12d9bef045345016b8b50c315cb82", size = 35547617, upload-time = "2025-05-08T16:04:43.546Z" }, + { url = "https://files.pythonhosted.org/packages/8e/6d/41991e503e51fc1134502694c5fa7a1671501a17ffa12716a4a9151af3df/scipy-1.15.3-cp310-cp310-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:9e2abc762b0811e09a0d3258abee2d98e0c703eee49464ce0069590846f31d40", size = 37662964, upload-time = "2025-05-08T16:04:49.431Z" }, + { url = "https://files.pythonhosted.org/packages/25/e1/3df8f83cb15f3500478c889be8fb18700813b95e9e087328230b98d547ff/scipy-1.15.3-cp310-cp310-musllinux_1_2_aarch64.whl", hash = "sha256:ed7284b21a7a0c8f1b6e5977ac05396c0d008b89e05498c8b7e8f4a1423bba0e", size = 37238749, upload-time = "2025-05-08T16:04:55.215Z" }, + { url = "https://files.pythonhosted.org/packages/93/3e/b3257cf446f2a3533ed7809757039016b74cd6f38271de91682aa844cfc5/scipy-1.15.3-cp310-cp310-musllinux_1_2_x86_64.whl", hash = "sha256:5380741e53df2c566f4d234b100a484b420af85deb39ea35a1cc1be84ff53a5c", size = 40022383, upload-time = "2025-05-08T16:05:01.914Z" }, + { url = "https://files.pythonhosted.org/packages/d1/84/55bc4881973d3f79b479a5a2e2df61c8c9a04fcb986a213ac9c02cfb659b/scipy-1.15.3-cp310-cp310-win_amd64.whl", hash = "sha256:9d61e97b186a57350f6d6fd72640f9e99d5a4a2b8fbf4b9ee9a841eab327dc13", size = 41259201, upload-time = "2025-05-08T16:05:08.166Z" }, + { url = "https://files.pythonhosted.org/packages/96/ab/5cc9f80f28f6a7dff646c5756e559823614a42b1939d86dd0ed550470210/scipy-1.15.3-cp311-cp311-macosx_10_13_x86_64.whl", hash = "sha256:993439ce220d25e3696d1b23b233dd010169b62f6456488567e830654ee37a6b", size = 38714255, upload-time = "2025-05-08T16:05:14.596Z" }, + { url = "https://files.pythonhosted.org/packages/4a/4a/66ba30abe5ad1a3ad15bfb0b59d22174012e8056ff448cb1644deccbfed2/scipy-1.15.3-cp311-cp311-macosx_12_0_arm64.whl", hash = "sha256:34716e281f181a02341ddeaad584205bd2fd3c242063bd3423d61ac259ca7eba", size = 30111035, upload-time = "2025-05-08T16:05:20.152Z" }, + { url = "https://files.pythonhosted.org/packages/4b/fa/a7e5b95afd80d24313307f03624acc65801846fa75599034f8ceb9e2cbf6/scipy-1.15.3-cp311-cp311-macosx_14_0_arm64.whl", hash = "sha256:3b0334816afb8b91dab859281b1b9786934392aa3d527cd847e41bb6f45bee65", size = 22384499, upload-time = "2025-05-08T16:05:24.494Z" }, + { url = "https://files.pythonhosted.org/packages/17/99/f3aaddccf3588bb4aea70ba35328c204cadd89517a1612ecfda5b2dd9d7a/scipy-1.15.3-cp311-cp311-macosx_14_0_x86_64.whl", hash = "sha256:6db907c7368e3092e24919b5e31c76998b0ce1684d51a90943cb0ed1b4ffd6c1", size = 25152602, upload-time = "2025-05-08T16:05:29.313Z" }, + { url = "https://files.pythonhosted.org/packages/56/c5/1032cdb565f146109212153339f9cb8b993701e9fe56b1c97699eee12586/scipy-1.15.3-cp311-cp311-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:721d6b4ef5dc82ca8968c25b111e307083d7ca9091bc38163fb89243e85e3889", size = 35503415, upload-time = "2025-05-08T16:05:34.699Z" }, + { url = "https://files.pythonhosted.org/packages/bd/37/89f19c8c05505d0601ed5650156e50eb881ae3918786c8fd7262b4ee66d3/scipy-1.15.3-cp311-cp311-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:39cb9c62e471b1bb3750066ecc3a3f3052b37751c7c3dfd0fd7e48900ed52982", size = 37652622, upload-time = "2025-05-08T16:05:40.762Z" }, + { url = "https://files.pythonhosted.org/packages/7e/31/be59513aa9695519b18e1851bb9e487de66f2d31f835201f1b42f5d4d475/scipy-1.15.3-cp311-cp311-musllinux_1_2_aarch64.whl", hash = "sha256:795c46999bae845966368a3c013e0e00947932d68e235702b5c3f6ea799aa8c9", size = 37244796, upload-time = "2025-05-08T16:05:48.119Z" }, + { url = "https://files.pythonhosted.org/packages/10/c0/4f5f3eeccc235632aab79b27a74a9130c6c35df358129f7ac8b29f562ac7/scipy-1.15.3-cp311-cp311-musllinux_1_2_x86_64.whl", hash = "sha256:18aaacb735ab38b38db42cb01f6b92a2d0d4b6aabefeb07f02849e47f8fb3594", size = 40047684, upload-time = "2025-05-08T16:05:54.22Z" }, + { url = "https://files.pythonhosted.org/packages/ab/a7/0ddaf514ce8a8714f6ed243a2b391b41dbb65251affe21ee3077ec45ea9a/scipy-1.15.3-cp311-cp311-win_amd64.whl", hash = "sha256:ae48a786a28412d744c62fd7816a4118ef97e5be0bee968ce8f0a2fba7acf3bb", size = 41246504, upload-time = "2025-05-08T16:06:00.437Z" }, + { url = "https://files.pythonhosted.org/packages/37/4b/683aa044c4162e10ed7a7ea30527f2cbd92e6999c10a8ed8edb253836e9c/scipy-1.15.3-cp312-cp312-macosx_10_13_x86_64.whl", hash = "sha256:6ac6310fdbfb7aa6612408bd2f07295bcbd3fda00d2d702178434751fe48e019", size = 38766735, upload-time = "2025-05-08T16:06:06.471Z" }, + { url = "https://files.pythonhosted.org/packages/7b/7e/f30be3d03de07f25dc0ec926d1681fed5c732d759ac8f51079708c79e680/scipy-1.15.3-cp312-cp312-macosx_12_0_arm64.whl", hash = "sha256:185cd3d6d05ca4b44a8f1595af87f9c372bb6acf9c808e99aa3e9aa03bd98cf6", size = 30173284, upload-time = "2025-05-08T16:06:11.686Z" }, + { url = "https://files.pythonhosted.org/packages/07/9c/0ddb0d0abdabe0d181c1793db51f02cd59e4901da6f9f7848e1f96759f0d/scipy-1.15.3-cp312-cp312-macosx_14_0_arm64.whl", hash = "sha256:05dc6abcd105e1a29f95eada46d4a3f251743cfd7d3ae8ddb4088047f24ea477", size = 22446958, upload-time = "2025-05-08T16:06:15.97Z" }, + { url = "https://files.pythonhosted.org/packages/af/43/0bce905a965f36c58ff80d8bea33f1f9351b05fad4beaad4eae34699b7a1/scipy-1.15.3-cp312-cp312-macosx_14_0_x86_64.whl", hash = "sha256:06efcba926324df1696931a57a176c80848ccd67ce6ad020c810736bfd58eb1c", size = 25242454, upload-time = "2025-05-08T16:06:20.394Z" }, + { url = "https://files.pythonhosted.org/packages/56/30/a6f08f84ee5b7b28b4c597aca4cbe545535c39fe911845a96414700b64ba/scipy-1.15.3-cp312-cp312-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:c05045d8b9bfd807ee1b9f38761993297b10b245f012b11b13b91ba8945f7e45", size = 35210199, upload-time = "2025-05-08T16:06:26.159Z" }, + { url = "https://files.pythonhosted.org/packages/0b/1f/03f52c282437a168ee2c7c14a1a0d0781a9a4a8962d84ac05c06b4c5b555/scipy-1.15.3-cp312-cp312-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:271e3713e645149ea5ea3e97b57fdab61ce61333f97cfae392c28ba786f9bb49", size = 37309455, upload-time = "2025-05-08T16:06:32.778Z" }, + { url = "https://files.pythonhosted.org/packages/89/b1/fbb53137f42c4bf630b1ffdfc2151a62d1d1b903b249f030d2b1c0280af8/scipy-1.15.3-cp312-cp312-musllinux_1_2_aarch64.whl", hash = "sha256:6cfd56fc1a8e53f6e89ba3a7a7251f7396412d655bca2aa5611c8ec9a6784a1e", size = 36885140, upload-time = "2025-05-08T16:06:39.249Z" }, + { url = "https://files.pythonhosted.org/packages/2e/2e/025e39e339f5090df1ff266d021892694dbb7e63568edcfe43f892fa381d/scipy-1.15.3-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:0ff17c0bb1cb32952c09217d8d1eed9b53d1463e5f1dd6052c7857f83127d539", size = 39710549, upload-time = "2025-05-08T16:06:45.729Z" }, + { url = "https://files.pythonhosted.org/packages/e6/eb/3bf6ea8ab7f1503dca3a10df2e4b9c3f6b3316df07f6c0ded94b281c7101/scipy-1.15.3-cp312-cp312-win_amd64.whl", hash = "sha256:52092bc0472cfd17df49ff17e70624345efece4e1a12b23783a1ac59a1b728ed", size = 40966184, upload-time = "2025-05-08T16:06:52.623Z" }, + { url = "https://files.pythonhosted.org/packages/73/18/ec27848c9baae6e0d6573eda6e01a602e5649ee72c27c3a8aad673ebecfd/scipy-1.15.3-cp313-cp313-macosx_10_13_x86_64.whl", hash = "sha256:2c620736bcc334782e24d173c0fdbb7590a0a436d2fdf39310a8902505008759", size = 38728256, upload-time = "2025-05-08T16:06:58.696Z" }, + { url = "https://files.pythonhosted.org/packages/74/cd/1aef2184948728b4b6e21267d53b3339762c285a46a274ebb7863c9e4742/scipy-1.15.3-cp313-cp313-macosx_12_0_arm64.whl", hash = "sha256:7e11270a000969409d37ed399585ee530b9ef6aa99d50c019de4cb01e8e54e62", size = 30109540, upload-time = "2025-05-08T16:07:04.209Z" }, + { url = "https://files.pythonhosted.org/packages/5b/d8/59e452c0a255ec352bd0a833537a3bc1bfb679944c4938ab375b0a6b3a3e/scipy-1.15.3-cp313-cp313-macosx_14_0_arm64.whl", hash = "sha256:8c9ed3ba2c8a2ce098163a9bdb26f891746d02136995df25227a20e71c396ebb", size = 22383115, upload-time = "2025-05-08T16:07:08.998Z" }, + { url = "https://files.pythonhosted.org/packages/08/f5/456f56bbbfccf696263b47095291040655e3cbaf05d063bdc7c7517f32ac/scipy-1.15.3-cp313-cp313-macosx_14_0_x86_64.whl", hash = "sha256:0bdd905264c0c9cfa74a4772cdb2070171790381a5c4d312c973382fc6eaf730", size = 25163884, upload-time = "2025-05-08T16:07:14.091Z" }, + { url = "https://files.pythonhosted.org/packages/a2/66/a9618b6a435a0f0c0b8a6d0a2efb32d4ec5a85f023c2b79d39512040355b/scipy-1.15.3-cp313-cp313-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:79167bba085c31f38603e11a267d862957cbb3ce018d8b38f79ac043bc92d825", size = 35174018, upload-time = "2025-05-08T16:07:19.427Z" }, + { url = "https://files.pythonhosted.org/packages/b5/09/c5b6734a50ad4882432b6bb7c02baf757f5b2f256041da5df242e2d7e6b6/scipy-1.15.3-cp313-cp313-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:c9deabd6d547aee2c9a81dee6cc96c6d7e9a9b1953f74850c179f91fdc729cb7", size = 37269716, upload-time = "2025-05-08T16:07:25.712Z" }, + { url = "https://files.pythonhosted.org/packages/77/0a/eac00ff741f23bcabd352731ed9b8995a0a60ef57f5fd788d611d43d69a1/scipy-1.15.3-cp313-cp313-musllinux_1_2_aarch64.whl", hash = "sha256:dde4fc32993071ac0c7dd2d82569e544f0bdaff66269cb475e0f369adad13f11", size = 36872342, upload-time = "2025-05-08T16:07:31.468Z" }, + { url = "https://files.pythonhosted.org/packages/fe/54/4379be86dd74b6ad81551689107360d9a3e18f24d20767a2d5b9253a3f0a/scipy-1.15.3-cp313-cp313-musllinux_1_2_x86_64.whl", hash = "sha256:f77f853d584e72e874d87357ad70f44b437331507d1c311457bed8ed2b956126", size = 39670869, upload-time = "2025-05-08T16:07:38.002Z" }, + { url = "https://files.pythonhosted.org/packages/87/2e/892ad2862ba54f084ffe8cc4a22667eaf9c2bcec6d2bff1d15713c6c0703/scipy-1.15.3-cp313-cp313-win_amd64.whl", hash = "sha256:b90ab29d0c37ec9bf55424c064312930ca5f4bde15ee8619ee44e69319aab163", size = 40988851, upload-time = "2025-05-08T16:08:33.671Z" }, + { url = "https://files.pythonhosted.org/packages/1b/e9/7a879c137f7e55b30d75d90ce3eb468197646bc7b443ac036ae3fe109055/scipy-1.15.3-cp313-cp313t-macosx_10_13_x86_64.whl", hash = "sha256:3ac07623267feb3ae308487c260ac684b32ea35fd81e12845039952f558047b8", size = 38863011, upload-time = "2025-05-08T16:07:44.039Z" }, + { url = "https://files.pythonhosted.org/packages/51/d1/226a806bbd69f62ce5ef5f3ffadc35286e9fbc802f606a07eb83bf2359de/scipy-1.15.3-cp313-cp313t-macosx_12_0_arm64.whl", hash = "sha256:6487aa99c2a3d509a5227d9a5e889ff05830a06b2ce08ec30df6d79db5fcd5c5", size = 30266407, upload-time = "2025-05-08T16:07:49.891Z" }, + { url = "https://files.pythonhosted.org/packages/e5/9b/f32d1d6093ab9eeabbd839b0f7619c62e46cc4b7b6dbf05b6e615bbd4400/scipy-1.15.3-cp313-cp313t-macosx_14_0_arm64.whl", hash = "sha256:50f9e62461c95d933d5c5ef4a1f2ebf9a2b4e83b0db374cb3f1de104d935922e", size = 22540030, upload-time = "2025-05-08T16:07:54.121Z" }, + { url = "https://files.pythonhosted.org/packages/e7/29/c278f699b095c1a884f29fda126340fcc201461ee8bfea5c8bdb1c7c958b/scipy-1.15.3-cp313-cp313t-macosx_14_0_x86_64.whl", hash = "sha256:14ed70039d182f411ffc74789a16df3835e05dc469b898233a245cdfd7f162cb", size = 25218709, upload-time = "2025-05-08T16:07:58.506Z" }, + { url = "https://files.pythonhosted.org/packages/24/18/9e5374b617aba742a990581373cd6b68a2945d65cc588482749ef2e64467/scipy-1.15.3-cp313-cp313t-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:0a769105537aa07a69468a0eefcd121be52006db61cdd8cac8a0e68980bbb723", size = 34809045, upload-time = "2025-05-08T16:08:03.929Z" }, + { url = "https://files.pythonhosted.org/packages/e1/fe/9c4361e7ba2927074360856db6135ef4904d505e9b3afbbcb073c4008328/scipy-1.15.3-cp313-cp313t-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:9db984639887e3dffb3928d118145ffe40eff2fa40cb241a306ec57c219ebbbb", size = 36703062, upload-time = "2025-05-08T16:08:09.558Z" }, + { url = "https://files.pythonhosted.org/packages/b7/8e/038ccfe29d272b30086b25a4960f757f97122cb2ec42e62b460d02fe98e9/scipy-1.15.3-cp313-cp313t-musllinux_1_2_aarch64.whl", hash = "sha256:40e54d5c7e7ebf1aa596c374c49fa3135f04648a0caabcb66c52884b943f02b4", size = 36393132, upload-time = "2025-05-08T16:08:15.34Z" }, + { url = "https://files.pythonhosted.org/packages/10/7e/5c12285452970be5bdbe8352c619250b97ebf7917d7a9a9e96b8a8140f17/scipy-1.15.3-cp313-cp313t-musllinux_1_2_x86_64.whl", hash = "sha256:5e721fed53187e71d0ccf382b6bf977644c533e506c4d33c3fb24de89f5c3ed5", size = 38979503, upload-time = "2025-05-08T16:08:21.513Z" }, + { url = "https://files.pythonhosted.org/packages/81/06/0a5e5349474e1cbc5757975b21bd4fad0e72ebf138c5592f191646154e06/scipy-1.15.3-cp313-cp313t-win_amd64.whl", hash = "sha256:76ad1fb5f8752eabf0fa02e4cc0336b4e8f021e2d5f061ed37d6d264db35e3ca", size = 40308097, upload-time = "2025-05-08T16:08:27.627Z" }, ] [[package]] name = "scipy" -version = "1.16.0" +version = "1.16.2" source = { registry = "https://pypi.org/simple" } resolution-markers = [ "python_full_version >= '3.13'", @@ -1380,313 +1604,329 @@ resolution-markers = [ "python_full_version == '3.11.*'", ] dependencies = [ - { name = "numpy", version = "2.3.1", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version >= '3.11'" }, -] -sdist = { url = "https://files.pythonhosted.org/packages/81/18/b06a83f0c5ee8cddbde5e3f3d0bb9b702abfa5136ef6d4620ff67df7eee5/scipy-1.16.0.tar.gz", hash = "sha256:b5ef54021e832869c8cfb03bc3bf20366cbcd426e02a58e8a58d7584dfbb8f62", size = 30581216 } -wheels = [ - { url = "https://files.pythonhosted.org/packages/d9/f8/53fc4884df6b88afd5f5f00240bdc49fee2999c7eff3acf5953eb15bc6f8/scipy-1.16.0-cp311-cp311-macosx_10_14_x86_64.whl", hash = "sha256:deec06d831b8f6b5fb0b652433be6a09db29e996368ce5911faf673e78d20085", size = 36447362 }, - { url = "https://files.pythonhosted.org/packages/c9/25/fad8aa228fa828705142a275fc593d701b1817c98361a2d6b526167d07bc/scipy-1.16.0-cp311-cp311-macosx_12_0_arm64.whl", hash = "sha256:d30c0fe579bb901c61ab4bb7f3eeb7281f0d4c4a7b52dbf563c89da4fd2949be", size = 28547120 }, - { url = "https://files.pythonhosted.org/packages/8d/be/d324ddf6b89fd1c32fecc307f04d095ce84abb52d2e88fab29d0cd8dc7a8/scipy-1.16.0-cp311-cp311-macosx_14_0_arm64.whl", hash = "sha256:b2243561b45257f7391d0f49972fca90d46b79b8dbcb9b2cb0f9df928d370ad4", size = 20818922 }, - { url = "https://files.pythonhosted.org/packages/cd/e0/cf3f39e399ac83fd0f3ba81ccc5438baba7cfe02176be0da55ff3396f126/scipy-1.16.0-cp311-cp311-macosx_14_0_x86_64.whl", hash = "sha256:e6d7dfc148135e9712d87c5f7e4f2ddc1304d1582cb3a7d698bbadedb61c7afd", size = 23409695 }, - { url = "https://files.pythonhosted.org/packages/5b/61/d92714489c511d3ffd6830ac0eb7f74f243679119eed8b9048e56b9525a1/scipy-1.16.0-cp311-cp311-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:90452f6a9f3fe5a2cf3748e7be14f9cc7d9b124dce19667b54f5b429d680d539", size = 33444586 }, - { url = "https://files.pythonhosted.org/packages/af/2c/40108915fd340c830aee332bb85a9160f99e90893e58008b659b9f3dddc0/scipy-1.16.0-cp311-cp311-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:a2f0bf2f58031c8701a8b601df41701d2a7be17c7ffac0a4816aeba89c4cdac8", size = 35284126 }, - { url = "https://files.pythonhosted.org/packages/d3/30/e9eb0ad3d0858df35d6c703cba0a7e16a18a56a9e6b211d861fc6f261c5f/scipy-1.16.0-cp311-cp311-musllinux_1_2_aarch64.whl", hash = "sha256:6c4abb4c11fc0b857474241b812ce69ffa6464b4bd8f4ecb786cf240367a36a7", size = 35608257 }, - { url = "https://files.pythonhosted.org/packages/c8/ff/950ee3e0d612b375110d8cda211c1f787764b4c75e418a4b71f4a5b1e07f/scipy-1.16.0-cp311-cp311-musllinux_1_2_x86_64.whl", hash = "sha256:b370f8f6ac6ef99815b0d5c9f02e7ade77b33007d74802efc8316c8db98fd11e", size = 38040541 }, - { url = "https://files.pythonhosted.org/packages/8b/c9/750d34788288d64ffbc94fdb4562f40f609d3f5ef27ab4f3a4ad00c9033e/scipy-1.16.0-cp311-cp311-win_amd64.whl", hash = "sha256:a16ba90847249bedce8aa404a83fb8334b825ec4a8e742ce6012a7a5e639f95c", size = 38570814 }, - { url = "https://files.pythonhosted.org/packages/01/c0/c943bc8d2bbd28123ad0f4f1eef62525fa1723e84d136b32965dcb6bad3a/scipy-1.16.0-cp312-cp312-macosx_10_14_x86_64.whl", hash = "sha256:7eb6bd33cef4afb9fa5f1fb25df8feeb1e52d94f21a44f1d17805b41b1da3180", size = 36459071 }, - { url = "https://files.pythonhosted.org/packages/99/0d/270e2e9f1a4db6ffbf84c9a0b648499842046e4e0d9b2275d150711b3aba/scipy-1.16.0-cp312-cp312-macosx_12_0_arm64.whl", hash = "sha256:1dbc8fdba23e4d80394ddfab7a56808e3e6489176d559c6c71935b11a2d59db1", size = 28490500 }, - { url = "https://files.pythonhosted.org/packages/1c/22/01d7ddb07cff937d4326198ec8d10831367a708c3da72dfd9b7ceaf13028/scipy-1.16.0-cp312-cp312-macosx_14_0_arm64.whl", hash = "sha256:7dcf42c380e1e3737b343dec21095c9a9ad3f9cbe06f9c05830b44b1786c9e90", size = 20762345 }, - { url = "https://files.pythonhosted.org/packages/34/7f/87fd69856569ccdd2a5873fe5d7b5bbf2ad9289d7311d6a3605ebde3a94b/scipy-1.16.0-cp312-cp312-macosx_14_0_x86_64.whl", hash = "sha256:26ec28675f4a9d41587266084c626b02899db373717d9312fa96ab17ca1ae94d", size = 23418563 }, - { url = "https://files.pythonhosted.org/packages/f6/f1/e4f4324fef7f54160ab749efbab6a4bf43678a9eb2e9817ed71a0a2fd8de/scipy-1.16.0-cp312-cp312-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:952358b7e58bd3197cfbd2f2f2ba829f258404bdf5db59514b515a8fe7a36c52", size = 33203951 }, - { url = "https://files.pythonhosted.org/packages/6d/f0/b6ac354a956384fd8abee2debbb624648125b298f2c4a7b4f0d6248048a5/scipy-1.16.0-cp312-cp312-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:03931b4e870c6fef5b5c0970d52c9f6ddd8c8d3e934a98f09308377eba6f3824", size = 35070225 }, - { url = "https://files.pythonhosted.org/packages/e5/73/5cbe4a3fd4bc3e2d67ffad02c88b83edc88f381b73ab982f48f3df1a7790/scipy-1.16.0-cp312-cp312-musllinux_1_2_aarch64.whl", hash = "sha256:512c4f4f85912767c351a0306824ccca6fd91307a9f4318efe8fdbd9d30562ef", size = 35389070 }, - { url = "https://files.pythonhosted.org/packages/86/e8/a60da80ab9ed68b31ea5a9c6dfd3c2f199347429f229bf7f939a90d96383/scipy-1.16.0-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:e69f798847e9add03d512eaf5081a9a5c9a98757d12e52e6186ed9681247a1ac", size = 37825287 }, - { url = "https://files.pythonhosted.org/packages/ea/b5/29fece1a74c6a94247f8a6fb93f5b28b533338e9c34fdcc9cfe7a939a767/scipy-1.16.0-cp312-cp312-win_amd64.whl", hash = "sha256:adf9b1999323ba335adc5d1dc7add4781cb5a4b0ef1e98b79768c05c796c4e49", size = 38431929 }, - { url = "https://files.pythonhosted.org/packages/46/95/0746417bc24be0c2a7b7563946d61f670a3b491b76adede420e9d173841f/scipy-1.16.0-cp313-cp313-macosx_10_14_x86_64.whl", hash = "sha256:e9f414cbe9ca289a73e0cc92e33a6a791469b6619c240aa32ee18abdce8ab451", size = 36418162 }, - { url = "https://files.pythonhosted.org/packages/19/5a/914355a74481b8e4bbccf67259bbde171348a3f160b67b4945fbc5f5c1e5/scipy-1.16.0-cp313-cp313-macosx_12_0_arm64.whl", hash = "sha256:bbba55fb97ba3cdef9b1ee973f06b09d518c0c7c66a009c729c7d1592be1935e", size = 28465985 }, - { url = "https://files.pythonhosted.org/packages/58/46/63477fc1246063855969cbefdcee8c648ba4b17f67370bd542ba56368d0b/scipy-1.16.0-cp313-cp313-macosx_14_0_arm64.whl", hash = "sha256:58e0d4354eacb6004e7aa1cd350e5514bd0270acaa8d5b36c0627bb3bb486974", size = 20737961 }, - { url = "https://files.pythonhosted.org/packages/93/86/0fbb5588b73555e40f9d3d6dde24ee6fac7d8e301a27f6f0cab9d8f66ff2/scipy-1.16.0-cp313-cp313-macosx_14_0_x86_64.whl", hash = "sha256:75b2094ec975c80efc273567436e16bb794660509c12c6a31eb5c195cbf4b6dc", size = 23377941 }, - { url = "https://files.pythonhosted.org/packages/ca/80/a561f2bf4c2da89fa631b3cbf31d120e21ea95db71fd9ec00cb0247c7a93/scipy-1.16.0-cp313-cp313-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:6b65d232157a380fdd11a560e7e21cde34fdb69d65c09cb87f6cc024ee376351", size = 33196703 }, - { url = "https://files.pythonhosted.org/packages/11/6b/3443abcd0707d52e48eb315e33cc669a95e29fc102229919646f5a501171/scipy-1.16.0-cp313-cp313-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:1d8747f7736accd39289943f7fe53a8333be7f15a82eea08e4afe47d79568c32", size = 35083410 }, - { url = "https://files.pythonhosted.org/packages/20/ab/eb0fc00e1e48961f1bd69b7ad7e7266896fe5bad4ead91b5fc6b3561bba4/scipy-1.16.0-cp313-cp313-musllinux_1_2_aarch64.whl", hash = "sha256:eb9f147a1b8529bb7fec2a85cf4cf42bdfadf9e83535c309a11fdae598c88e8b", size = 35387829 }, - { url = "https://files.pythonhosted.org/packages/57/9e/d6fc64e41fad5d481c029ee5a49eefc17f0b8071d636a02ceee44d4a0de2/scipy-1.16.0-cp313-cp313-musllinux_1_2_x86_64.whl", hash = "sha256:d2b83c37edbfa837a8923d19c749c1935ad3d41cf196006a24ed44dba2ec4358", size = 37841356 }, - { url = "https://files.pythonhosted.org/packages/7c/a7/4c94bbe91f12126b8bf6709b2471900577b7373a4fd1f431f28ba6f81115/scipy-1.16.0-cp313-cp313-win_amd64.whl", hash = "sha256:79a3c13d43c95aa80b87328a46031cf52508cf5f4df2767602c984ed1d3c6bbe", size = 38403710 }, - { url = "https://files.pythonhosted.org/packages/47/20/965da8497f6226e8fa90ad3447b82ed0e28d942532e92dd8b91b43f100d4/scipy-1.16.0-cp313-cp313t-macosx_10_14_x86_64.whl", hash = "sha256:f91b87e1689f0370690e8470916fe1b2308e5b2061317ff76977c8f836452a47", size = 36813833 }, - { url = "https://files.pythonhosted.org/packages/28/f4/197580c3dac2d234e948806e164601c2df6f0078ed9f5ad4a62685b7c331/scipy-1.16.0-cp313-cp313t-macosx_12_0_arm64.whl", hash = "sha256:88a6ca658fb94640079e7a50b2ad3b67e33ef0f40e70bdb7dc22017dae73ac08", size = 28974431 }, - { url = "https://files.pythonhosted.org/packages/8a/fc/e18b8550048d9224426e76906694c60028dbdb65d28b1372b5503914b89d/scipy-1.16.0-cp313-cp313t-macosx_14_0_arm64.whl", hash = "sha256:ae902626972f1bd7e4e86f58fd72322d7f4ec7b0cfc17b15d4b7006efc385176", size = 21246454 }, - { url = "https://files.pythonhosted.org/packages/8c/48/07b97d167e0d6a324bfd7484cd0c209cc27338b67e5deadae578cf48e809/scipy-1.16.0-cp313-cp313t-macosx_14_0_x86_64.whl", hash = "sha256:8cb824c1fc75ef29893bc32b3ddd7b11cf9ab13c1127fe26413a05953b8c32ed", size = 23772979 }, - { url = "https://files.pythonhosted.org/packages/4c/4f/9efbd3f70baf9582edf271db3002b7882c875ddd37dc97f0f675ad68679f/scipy-1.16.0-cp313-cp313t-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:de2db7250ff6514366a9709c2cba35cb6d08498e961cba20d7cff98a7ee88938", size = 33341972 }, - { url = "https://files.pythonhosted.org/packages/3f/dc/9e496a3c5dbe24e76ee24525155ab7f659c20180bab058ef2c5fa7d9119c/scipy-1.16.0-cp313-cp313t-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:e85800274edf4db8dd2e4e93034f92d1b05c9421220e7ded9988b16976f849c1", size = 35185476 }, - { url = "https://files.pythonhosted.org/packages/ce/b3/21001cff985a122ba434c33f2c9d7d1dc3b669827e94f4fc4e1fe8b9dfd8/scipy-1.16.0-cp313-cp313t-musllinux_1_2_aarch64.whl", hash = "sha256:4f720300a3024c237ace1cb11f9a84c38beb19616ba7c4cdcd771047a10a1706", size = 35570990 }, - { url = "https://files.pythonhosted.org/packages/e5/d3/7ba42647d6709251cdf97043d0c107e0317e152fa2f76873b656b509ff55/scipy-1.16.0-cp313-cp313t-musllinux_1_2_x86_64.whl", hash = "sha256:aad603e9339ddb676409b104c48a027e9916ce0d2838830691f39552b38a352e", size = 37950262 }, - { url = "https://files.pythonhosted.org/packages/eb/c4/231cac7a8385394ebbbb4f1ca662203e9d8c332825ab4f36ffc3ead09a42/scipy-1.16.0-cp313-cp313t-win_amd64.whl", hash = "sha256:f56296fefca67ba605fd74d12f7bd23636267731a72cb3947963e76b8c0a25db", size = 38515076 }, -] - -[[package]] -name = "setuptools" -version = "80.9.0" -source = { registry = "https://pypi.org/simple" } -sdist = { url = "https://files.pythonhosted.org/packages/18/5d/3bf57dcd21979b887f014ea83c24ae194cfcd12b9e0fda66b957c69d1fca/setuptools-80.9.0.tar.gz", hash = "sha256:f36b47402ecde768dbfafc46e8e4207b4360c654f1f3bb84475f0a28628fb19c", size = 1319958 } -wheels = [ - { url = "https://files.pythonhosted.org/packages/a3/dc/17031897dae0efacfea57dfd3a82fdd2a2aeb58e0ff71b77b87e44edc772/setuptools-80.9.0-py3-none-any.whl", hash = "sha256:062d34222ad13e0cc312a4c02d73f059e86a4acbfbdea8f8f76b28c99f306922", size = 1201486 }, + { name = "numpy", version = "2.3.3", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version >= '3.11'" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/4c/3b/546a6f0bfe791bbb7f8d591613454d15097e53f906308ec6f7c1ce588e8e/scipy-1.16.2.tar.gz", hash = "sha256:af029b153d243a80afb6eabe40b0a07f8e35c9adc269c019f364ad747f826a6b", size = 30580599, upload-time = "2025-09-11T17:48:08.271Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/0b/ef/37ed4b213d64b48422df92560af7300e10fe30b5d665dd79932baebee0c6/scipy-1.16.2-cp311-cp311-macosx_10_14_x86_64.whl", hash = "sha256:6ab88ea43a57da1af33292ebd04b417e8e2eaf9d5aa05700be8d6e1b6501cd92", size = 36619956, upload-time = "2025-09-11T17:39:20.5Z" }, + { url = "https://files.pythonhosted.org/packages/85/ab/5c2eba89b9416961a982346a4d6a647d78c91ec96ab94ed522b3b6baf444/scipy-1.16.2-cp311-cp311-macosx_12_0_arm64.whl", hash = "sha256:c95e96c7305c96ede73a7389f46ccd6c659c4da5ef1b2789466baeaed3622b6e", size = 28931117, upload-time = "2025-09-11T17:39:29.06Z" }, + { url = "https://files.pythonhosted.org/packages/80/d1/eed51ab64d227fe60229a2d57fb60ca5898cfa50ba27d4f573e9e5f0b430/scipy-1.16.2-cp311-cp311-macosx_14_0_arm64.whl", hash = "sha256:87eb178db04ece7c698220d523c170125dbffebb7af0345e66c3554f6f60c173", size = 20921997, upload-time = "2025-09-11T17:39:34.892Z" }, + { url = "https://files.pythonhosted.org/packages/be/7c/33ea3e23bbadde96726edba6bf9111fb1969d14d9d477ffa202c67bec9da/scipy-1.16.2-cp311-cp311-macosx_14_0_x86_64.whl", hash = "sha256:4e409eac067dcee96a57fbcf424c13f428037827ec7ee3cb671ff525ca4fc34d", size = 23523374, upload-time = "2025-09-11T17:39:40.846Z" }, + { url = "https://files.pythonhosted.org/packages/96/0b/7399dc96e1e3f9a05e258c98d716196a34f528eef2ec55aad651ed136d03/scipy-1.16.2-cp311-cp311-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:e574be127bb760f0dad24ff6e217c80213d153058372362ccb9555a10fc5e8d2", size = 33583702, upload-time = "2025-09-11T17:39:49.011Z" }, + { url = "https://files.pythonhosted.org/packages/1a/bc/a5c75095089b96ea72c1bd37a4497c24b581ec73db4ef58ebee142ad2d14/scipy-1.16.2-cp311-cp311-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:f5db5ba6188d698ba7abab982ad6973265b74bb40a1efe1821b58c87f73892b9", size = 35883427, upload-time = "2025-09-11T17:39:57.406Z" }, + { url = "https://files.pythonhosted.org/packages/ab/66/e25705ca3d2b87b97fe0a278a24b7f477b4023a926847935a1a71488a6a6/scipy-1.16.2-cp311-cp311-musllinux_1_2_aarch64.whl", hash = "sha256:ec6e74c4e884104ae006d34110677bfe0098203a3fec2f3faf349f4cb05165e3", size = 36212940, upload-time = "2025-09-11T17:40:06.013Z" }, + { url = "https://files.pythonhosted.org/packages/d6/fd/0bb911585e12f3abdd603d721d83fc1c7492835e1401a0e6d498d7822b4b/scipy-1.16.2-cp311-cp311-musllinux_1_2_x86_64.whl", hash = "sha256:912f46667d2d3834bc3d57361f854226475f695eb08c08a904aadb1c936b6a88", size = 38865092, upload-time = "2025-09-11T17:40:15.143Z" }, + { url = "https://files.pythonhosted.org/packages/d6/73/c449a7d56ba6e6f874183759f8483cde21f900a8be117d67ffbb670c2958/scipy-1.16.2-cp311-cp311-win_amd64.whl", hash = "sha256:91e9e8a37befa5a69e9cacbe0bcb79ae5afb4a0b130fd6db6ee6cc0d491695fa", size = 38687626, upload-time = "2025-09-11T17:40:24.041Z" }, + { url = "https://files.pythonhosted.org/packages/68/72/02f37316adf95307f5d9e579023c6899f89ff3a051fa079dbd6faafc48e5/scipy-1.16.2-cp311-cp311-win_arm64.whl", hash = "sha256:f3bf75a6dcecab62afde4d1f973f1692be013110cad5338007927db8da73249c", size = 25503506, upload-time = "2025-09-11T17:40:30.703Z" }, + { url = "https://files.pythonhosted.org/packages/b7/8d/6396e00db1282279a4ddd507c5f5e11f606812b608ee58517ce8abbf883f/scipy-1.16.2-cp312-cp312-macosx_10_14_x86_64.whl", hash = "sha256:89d6c100fa5c48472047632e06f0876b3c4931aac1f4291afc81a3644316bb0d", size = 36646259, upload-time = "2025-09-11T17:40:39.329Z" }, + { url = "https://files.pythonhosted.org/packages/3b/93/ea9edd7e193fceb8eef149804491890bde73fb169c896b61aa3e2d1e4e77/scipy-1.16.2-cp312-cp312-macosx_12_0_arm64.whl", hash = "sha256:ca748936cd579d3f01928b30a17dc474550b01272d8046e3e1ee593f23620371", size = 28888976, upload-time = "2025-09-11T17:40:46.82Z" }, + { url = "https://files.pythonhosted.org/packages/91/4d/281fddc3d80fd738ba86fd3aed9202331180b01e2c78eaae0642f22f7e83/scipy-1.16.2-cp312-cp312-macosx_14_0_arm64.whl", hash = "sha256:fac4f8ce2ddb40e2e3d0f7ec36d2a1e7f92559a2471e59aec37bd8d9de01fec0", size = 20879905, upload-time = "2025-09-11T17:40:52.545Z" }, + { url = "https://files.pythonhosted.org/packages/69/40/b33b74c84606fd301b2915f0062e45733c6ff5708d121dd0deaa8871e2d0/scipy-1.16.2-cp312-cp312-macosx_14_0_x86_64.whl", hash = "sha256:033570f1dcefd79547a88e18bccacff025c8c647a330381064f561d43b821232", size = 23553066, upload-time = "2025-09-11T17:40:59.014Z" }, + { url = "https://files.pythonhosted.org/packages/55/a7/22c739e2f21a42cc8f16bc76b47cff4ed54fbe0962832c589591c2abec34/scipy-1.16.2-cp312-cp312-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:ea3421209bf00c8a5ef2227de496601087d8f638a2363ee09af059bd70976dc1", size = 33336407, upload-time = "2025-09-11T17:41:06.796Z" }, + { url = "https://files.pythonhosted.org/packages/53/11/a0160990b82999b45874dc60c0c183d3a3a969a563fffc476d5a9995c407/scipy-1.16.2-cp312-cp312-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:f66bd07ba6f84cd4a380b41d1bf3c59ea488b590a2ff96744845163309ee8e2f", size = 35673281, upload-time = "2025-09-11T17:41:15.055Z" }, + { url = "https://files.pythonhosted.org/packages/96/53/7ef48a4cfcf243c3d0f1643f5887c81f29fdf76911c4e49331828e19fc0a/scipy-1.16.2-cp312-cp312-musllinux_1_2_aarch64.whl", hash = "sha256:5e9feab931bd2aea4a23388c962df6468af3d808ddf2d40f94a81c5dc38f32ef", size = 36004222, upload-time = "2025-09-11T17:41:23.868Z" }, + { url = "https://files.pythonhosted.org/packages/49/7f/71a69e0afd460049d41c65c630c919c537815277dfea214031005f474d78/scipy-1.16.2-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:03dfc75e52f72cf23ec2ced468645321407faad8f0fe7b1f5b49264adbc29cb1", size = 38664586, upload-time = "2025-09-11T17:41:31.021Z" }, + { url = "https://files.pythonhosted.org/packages/34/95/20e02ca66fb495a95fba0642fd48e0c390d0ece9b9b14c6e931a60a12dea/scipy-1.16.2-cp312-cp312-win_amd64.whl", hash = "sha256:0ce54e07bbb394b417457409a64fd015be623f36e330ac49306433ffe04bc97e", size = 38550641, upload-time = "2025-09-11T17:41:36.61Z" }, + { url = "https://files.pythonhosted.org/packages/92/ad/13646b9beb0a95528ca46d52b7babafbe115017814a611f2065ee4e61d20/scipy-1.16.2-cp312-cp312-win_arm64.whl", hash = "sha256:2a8ffaa4ac0df81a0b94577b18ee079f13fecdb924df3328fc44a7dc5ac46851", size = 25456070, upload-time = "2025-09-11T17:41:41.3Z" }, + { url = "https://files.pythonhosted.org/packages/c1/27/c5b52f1ee81727a9fc457f5ac1e9bf3d6eab311805ea615c83c27ba06400/scipy-1.16.2-cp313-cp313-macosx_10_14_x86_64.whl", hash = "sha256:84f7bf944b43e20b8a894f5fe593976926744f6c185bacfcbdfbb62736b5cc70", size = 36604856, upload-time = "2025-09-11T17:41:47.695Z" }, + { url = "https://files.pythonhosted.org/packages/32/a9/15c20d08e950b540184caa8ced675ba1128accb0e09c653780ba023a4110/scipy-1.16.2-cp313-cp313-macosx_12_0_arm64.whl", hash = "sha256:5c39026d12edc826a1ef2ad35ad1e6d7f087f934bb868fc43fa3049c8b8508f9", size = 28864626, upload-time = "2025-09-11T17:41:52.642Z" }, + { url = "https://files.pythonhosted.org/packages/4c/fc/ea36098df653cca26062a627c1a94b0de659e97127c8491e18713ca0e3b9/scipy-1.16.2-cp313-cp313-macosx_14_0_arm64.whl", hash = "sha256:e52729ffd45b68777c5319560014d6fd251294200625d9d70fd8626516fc49f5", size = 20855689, upload-time = "2025-09-11T17:41:57.886Z" }, + { url = "https://files.pythonhosted.org/packages/dc/6f/d0b53be55727f3e6d7c72687ec18ea6d0047cf95f1f77488b99a2bafaee1/scipy-1.16.2-cp313-cp313-macosx_14_0_x86_64.whl", hash = "sha256:024dd4a118cccec09ca3209b7e8e614931a6ffb804b2a601839499cb88bdf925", size = 23512151, upload-time = "2025-09-11T17:42:02.303Z" }, + { url = "https://files.pythonhosted.org/packages/11/85/bf7dab56e5c4b1d3d8eef92ca8ede788418ad38a7dc3ff50262f00808760/scipy-1.16.2-cp313-cp313-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:7a5dc7ee9c33019973a470556081b0fd3c9f4c44019191039f9769183141a4d9", size = 33329824, upload-time = "2025-09-11T17:42:07.549Z" }, + { url = "https://files.pythonhosted.org/packages/da/6a/1a927b14ddc7714111ea51f4e568203b2bb6ed59bdd036d62127c1a360c8/scipy-1.16.2-cp313-cp313-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:c2275ff105e508942f99d4e3bc56b6ef5e4b3c0af970386ca56b777608ce95b7", size = 35681881, upload-time = "2025-09-11T17:42:13.255Z" }, + { url = "https://files.pythonhosted.org/packages/c1/5f/331148ea5780b4fcc7007a4a6a6ee0a0c1507a796365cc642d4d226e1c3a/scipy-1.16.2-cp313-cp313-musllinux_1_2_aarch64.whl", hash = "sha256:af80196eaa84f033e48444d2e0786ec47d328ba00c71e4299b602235ffef9acb", size = 36006219, upload-time = "2025-09-11T17:42:18.765Z" }, + { url = "https://files.pythonhosted.org/packages/46/3a/e991aa9d2aec723b4a8dcfbfc8365edec5d5e5f9f133888067f1cbb7dfc1/scipy-1.16.2-cp313-cp313-musllinux_1_2_x86_64.whl", hash = "sha256:9fb1eb735fe3d6ed1f89918224e3385fbf6f9e23757cacc35f9c78d3b712dd6e", size = 38682147, upload-time = "2025-09-11T17:42:25.177Z" }, + { url = "https://files.pythonhosted.org/packages/a1/57/0f38e396ad19e41b4c5db66130167eef8ee620a49bc7d0512e3bb67e0cab/scipy-1.16.2-cp313-cp313-win_amd64.whl", hash = "sha256:fda714cf45ba43c9d3bae8f2585c777f64e3f89a2e073b668b32ede412d8f52c", size = 38520766, upload-time = "2025-09-11T17:43:25.342Z" }, + { url = "https://files.pythonhosted.org/packages/1b/a5/85d3e867b6822d331e26c862a91375bb7746a0b458db5effa093d34cdb89/scipy-1.16.2-cp313-cp313-win_arm64.whl", hash = "sha256:2f5350da923ccfd0b00e07c3e5cfb316c1c0d6c1d864c07a72d092e9f20db104", size = 25451169, upload-time = "2025-09-11T17:43:30.198Z" }, + { url = "https://files.pythonhosted.org/packages/09/d9/60679189bcebda55992d1a45498de6d080dcaf21ce0c8f24f888117e0c2d/scipy-1.16.2-cp313-cp313t-macosx_10_14_x86_64.whl", hash = "sha256:53d8d2ee29b925344c13bda64ab51785f016b1b9617849dac10897f0701b20c1", size = 37012682, upload-time = "2025-09-11T17:42:30.677Z" }, + { url = "https://files.pythonhosted.org/packages/83/be/a99d13ee4d3b7887a96f8c71361b9659ba4ef34da0338f14891e102a127f/scipy-1.16.2-cp313-cp313t-macosx_12_0_arm64.whl", hash = "sha256:9e05e33657efb4c6a9d23bd8300101536abd99c85cca82da0bffff8d8764d08a", size = 29389926, upload-time = "2025-09-11T17:42:35.845Z" }, + { url = "https://files.pythonhosted.org/packages/bf/0a/130164a4881cec6ca8c00faf3b57926f28ed429cd6001a673f83c7c2a579/scipy-1.16.2-cp313-cp313t-macosx_14_0_arm64.whl", hash = "sha256:7fe65b36036357003b3ef9d37547abeefaa353b237e989c21027b8ed62b12d4f", size = 21381152, upload-time = "2025-09-11T17:42:40.07Z" }, + { url = "https://files.pythonhosted.org/packages/47/a6/503ffb0310ae77fba874e10cddfc4a1280bdcca1d13c3751b8c3c2996cf8/scipy-1.16.2-cp313-cp313t-macosx_14_0_x86_64.whl", hash = "sha256:6406d2ac6d40b861cccf57f49592f9779071655e9f75cd4f977fa0bdd09cb2e4", size = 23914410, upload-time = "2025-09-11T17:42:44.313Z" }, + { url = "https://files.pythonhosted.org/packages/fa/c7/1147774bcea50d00c02600aadaa919facbd8537997a62496270133536ed6/scipy-1.16.2-cp313-cp313t-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:ff4dc42bd321991fbf611c23fc35912d690f731c9914bf3af8f417e64aca0f21", size = 33481880, upload-time = "2025-09-11T17:42:49.325Z" }, + { url = "https://files.pythonhosted.org/packages/6a/74/99d5415e4c3e46b2586f30cdbecb95e101c7192628a484a40dd0d163811a/scipy-1.16.2-cp313-cp313t-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:654324826654d4d9133e10675325708fb954bc84dae6e9ad0a52e75c6b1a01d7", size = 35791425, upload-time = "2025-09-11T17:42:54.711Z" }, + { url = "https://files.pythonhosted.org/packages/1b/ee/a6559de7c1cc710e938c0355d9d4fbcd732dac4d0d131959d1f3b63eb29c/scipy-1.16.2-cp313-cp313t-musllinux_1_2_aarch64.whl", hash = "sha256:63870a84cd15c44e65220eaed2dac0e8f8b26bbb991456a033c1d9abfe8a94f8", size = 36178622, upload-time = "2025-09-11T17:43:00.375Z" }, + { url = "https://files.pythonhosted.org/packages/4e/7b/f127a5795d5ba8ece4e0dce7d4a9fb7cb9e4f4757137757d7a69ab7d4f1a/scipy-1.16.2-cp313-cp313t-musllinux_1_2_x86_64.whl", hash = "sha256:fa01f0f6a3050fa6a9771a95d5faccc8e2f5a92b4a2e5440a0fa7264a2398472", size = 38783985, upload-time = "2025-09-11T17:43:06.661Z" }, + { url = "https://files.pythonhosted.org/packages/3e/9f/bc81c1d1e033951eb5912cd3750cc005943afa3e65a725d2443a3b3c4347/scipy-1.16.2-cp313-cp313t-win_amd64.whl", hash = "sha256:116296e89fba96f76353a8579820c2512f6e55835d3fad7780fece04367de351", size = 38631367, upload-time = "2025-09-11T17:43:14.44Z" }, + { url = "https://files.pythonhosted.org/packages/d6/5e/2cc7555fd81d01814271412a1d59a289d25f8b63208a0a16c21069d55d3e/scipy-1.16.2-cp313-cp313t-win_arm64.whl", hash = "sha256:98e22834650be81d42982360382b43b17f7ba95e0e6993e2a4f5b9ad9283a94d", size = 25787992, upload-time = "2025-09-11T17:43:19.745Z" }, + { url = "https://files.pythonhosted.org/packages/8b/ac/ad8951250516db71619f0bd3b2eb2448db04b720a003dd98619b78b692c0/scipy-1.16.2-cp314-cp314-macosx_10_14_x86_64.whl", hash = "sha256:567e77755019bb7461513c87f02bb73fb65b11f049aaaa8ca17cfaa5a5c45d77", size = 36595109, upload-time = "2025-09-11T17:43:35.713Z" }, + { url = "https://files.pythonhosted.org/packages/ff/f6/5779049ed119c5b503b0f3dc6d6f3f68eefc3a9190d4ad4c276f854f051b/scipy-1.16.2-cp314-cp314-macosx_12_0_arm64.whl", hash = "sha256:17d9bb346194e8967296621208fcdfd39b55498ef7d2f376884d5ac47cec1a70", size = 28859110, upload-time = "2025-09-11T17:43:40.814Z" }, + { url = "https://files.pythonhosted.org/packages/82/09/9986e410ae38bf0a0c737ff8189ac81a93b8e42349aac009891c054403d7/scipy-1.16.2-cp314-cp314-macosx_14_0_arm64.whl", hash = "sha256:0a17541827a9b78b777d33b623a6dcfe2ef4a25806204d08ead0768f4e529a88", size = 20850110, upload-time = "2025-09-11T17:43:44.981Z" }, + { url = "https://files.pythonhosted.org/packages/0d/ad/485cdef2d9215e2a7df6d61b81d2ac073dfacf6ae24b9ae87274c4e936ae/scipy-1.16.2-cp314-cp314-macosx_14_0_x86_64.whl", hash = "sha256:d7d4c6ba016ffc0f9568d012f5f1eb77ddd99412aea121e6fa8b4c3b7cbad91f", size = 23497014, upload-time = "2025-09-11T17:43:49.074Z" }, + { url = "https://files.pythonhosted.org/packages/a7/74/f6a852e5d581122b8f0f831f1d1e32fb8987776ed3658e95c377d308ed86/scipy-1.16.2-cp314-cp314-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:9702c4c023227785c779cba2e1d6f7635dbb5b2e0936cdd3a4ecb98d78fd41eb", size = 33401155, upload-time = "2025-09-11T17:43:54.661Z" }, + { url = "https://files.pythonhosted.org/packages/d9/f5/61d243bbc7c6e5e4e13dde9887e84a5cbe9e0f75fd09843044af1590844e/scipy-1.16.2-cp314-cp314-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:d1cdf0ac28948d225decdefcc45ad7dd91716c29ab56ef32f8e0d50657dffcc7", size = 35691174, upload-time = "2025-09-11T17:44:00.101Z" }, + { url = "https://files.pythonhosted.org/packages/03/99/59933956331f8cc57e406cdb7a483906c74706b156998f322913e789c7e1/scipy-1.16.2-cp314-cp314-musllinux_1_2_aarch64.whl", hash = "sha256:70327d6aa572a17c2941cdfb20673f82e536e91850a2e4cb0c5b858b690e1548", size = 36070752, upload-time = "2025-09-11T17:44:05.619Z" }, + { url = "https://files.pythonhosted.org/packages/c6/7d/00f825cfb47ee19ef74ecf01244b43e95eae74e7e0ff796026ea7cd98456/scipy-1.16.2-cp314-cp314-musllinux_1_2_x86_64.whl", hash = "sha256:5221c0b2a4b58aa7c4ed0387d360fd90ee9086d383bb34d9f2789fafddc8a936", size = 38701010, upload-time = "2025-09-11T17:44:11.322Z" }, + { url = "https://files.pythonhosted.org/packages/e4/9f/b62587029980378304ba5a8563d376c96f40b1e133daacee76efdcae32de/scipy-1.16.2-cp314-cp314-win_amd64.whl", hash = "sha256:f5a85d7b2b708025af08f060a496dd261055b617d776fc05a1a1cc69e09fe9ff", size = 39360061, upload-time = "2025-09-11T17:45:09.814Z" }, + { url = "https://files.pythonhosted.org/packages/82/04/7a2f1609921352c7fbee0815811b5050582f67f19983096c4769867ca45f/scipy-1.16.2-cp314-cp314-win_arm64.whl", hash = "sha256:2cc73a33305b4b24556957d5857d6253ce1e2dcd67fa0ff46d87d1670b3e1e1d", size = 26126914, upload-time = "2025-09-11T17:45:14.73Z" }, + { url = "https://files.pythonhosted.org/packages/51/b9/60929ce350c16b221928725d2d1d7f86cf96b8bc07415547057d1196dc92/scipy-1.16.2-cp314-cp314t-macosx_10_14_x86_64.whl", hash = "sha256:9ea2a3fed83065d77367775d689401a703d0f697420719ee10c0780bcab594d8", size = 37013193, upload-time = "2025-09-11T17:44:16.757Z" }, + { url = "https://files.pythonhosted.org/packages/2a/41/ed80e67782d4bc5fc85a966bc356c601afddd175856ba7c7bb6d9490607e/scipy-1.16.2-cp314-cp314t-macosx_12_0_arm64.whl", hash = "sha256:7280d926f11ca945c3ef92ba960fa924e1465f8d07ce3a9923080363390624c4", size = 29390172, upload-time = "2025-09-11T17:44:21.783Z" }, + { url = "https://files.pythonhosted.org/packages/c4/a3/2f673ace4090452696ccded5f5f8efffb353b8f3628f823a110e0170b605/scipy-1.16.2-cp314-cp314t-macosx_14_0_arm64.whl", hash = "sha256:8afae1756f6a1fe04636407ef7dbece33d826a5d462b74f3d0eb82deabefd831", size = 21381326, upload-time = "2025-09-11T17:44:25.982Z" }, + { url = "https://files.pythonhosted.org/packages/42/bf/59df61c5d51395066c35836b78136accf506197617c8662e60ea209881e1/scipy-1.16.2-cp314-cp314t-macosx_14_0_x86_64.whl", hash = "sha256:5c66511f29aa8d233388e7416a3f20d5cae7a2744d5cee2ecd38c081f4e861b3", size = 23915036, upload-time = "2025-09-11T17:44:30.527Z" }, + { url = "https://files.pythonhosted.org/packages/91/c3/edc7b300dc16847ad3672f1a6f3f7c5d13522b21b84b81c265f4f2760d4a/scipy-1.16.2-cp314-cp314t-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:efe6305aeaa0e96b0ccca5ff647a43737d9a092064a3894e46c414db84bc54ac", size = 33484341, upload-time = "2025-09-11T17:44:35.981Z" }, + { url = "https://files.pythonhosted.org/packages/26/c7/24d1524e72f06ff141e8d04b833c20db3021020563272ccb1b83860082a9/scipy-1.16.2-cp314-cp314t-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:7f3a337d9ae06a1e8d655ee9d8ecb835ea5ddcdcbd8d23012afa055ab014f374", size = 35790840, upload-time = "2025-09-11T17:44:41.76Z" }, + { url = "https://files.pythonhosted.org/packages/aa/b7/5aaad984eeedd56858dc33d75efa59e8ce798d918e1033ef62d2708f2c3d/scipy-1.16.2-cp314-cp314t-musllinux_1_2_aarch64.whl", hash = "sha256:bab3605795d269067d8ce78a910220262711b753de8913d3deeaedb5dded3bb6", size = 36174716, upload-time = "2025-09-11T17:44:47.316Z" }, + { url = "https://files.pythonhosted.org/packages/fd/c2/e276a237acb09824822b0ada11b028ed4067fdc367a946730979feacb870/scipy-1.16.2-cp314-cp314t-musllinux_1_2_x86_64.whl", hash = "sha256:b0348d8ddb55be2a844c518cd8cc8deeeb8aeba707cf834db5758fc89b476a2c", size = 38790088, upload-time = "2025-09-11T17:44:53.011Z" }, + { url = "https://files.pythonhosted.org/packages/c6/b4/5c18a766e8353015439f3780f5fc473f36f9762edc1a2e45da3ff5a31b21/scipy-1.16.2-cp314-cp314t-win_amd64.whl", hash = "sha256:26284797e38b8a75e14ea6631d29bda11e76ceaa6ddb6fdebbfe4c4d90faf2f9", size = 39457455, upload-time = "2025-09-11T17:44:58.899Z" }, + { url = "https://files.pythonhosted.org/packages/97/30/2f9a5243008f76dfc5dee9a53dfb939d9b31e16ce4bd4f2e628bfc5d89d2/scipy-1.16.2-cp314-cp314t-win_arm64.whl", hash = "sha256:d2a4472c231328d4de38d5f1f68fdd6d28a615138f842580a8a321b5845cf779", size = 26448374, upload-time = "2025-09-11T17:45:03.45Z" }, ] [[package]] name = "simplejson" -version = "3.20.1" -source = { registry = "https://pypi.org/simple" } -sdist = { url = "https://files.pythonhosted.org/packages/af/92/51b417685abd96b31308b61b9acce7ec50d8e1de8fbc39a7fd4962c60689/simplejson-3.20.1.tar.gz", hash = "sha256:e64139b4ec4f1f24c142ff7dcafe55a22b811a74d86d66560c8815687143037d", size = 85591 } -wheels = [ - { url = "https://files.pythonhosted.org/packages/25/c4/627214fb418cd4a17fb0230ff0b6c3bb4a85cbb48dd69c85dcc3b85df828/simplejson-3.20.1-cp310-cp310-macosx_10_9_universal2.whl", hash = "sha256:e580aa65d5f6c3bf41b9b4afe74be5d5ddba9576701c107c772d936ea2b5043a", size = 93790 }, - { url = "https://files.pythonhosted.org/packages/15/ca/56a6a2a33cbcf330c4d71af3f827c47e4e0ba791e78f2642f3d1ab02ff31/simplejson-3.20.1-cp310-cp310-macosx_10_9_x86_64.whl", hash = "sha256:4a586ce4f78cec11f22fe55c5bee0f067e803aab9bad3441afe2181693b5ebb5", size = 75707 }, - { url = "https://files.pythonhosted.org/packages/a9/c8/3d92b67e03a3b6207d97202669f9454ed700b35ade9bd4428265a078fb6c/simplejson-3.20.1-cp310-cp310-macosx_11_0_arm64.whl", hash = "sha256:74a1608f9e6e8c27a4008d70a54270868306d80ed48c9df7872f9f4b8ac87808", size = 75700 }, - { url = "https://files.pythonhosted.org/packages/74/30/20001219d6fdca4aaa3974c96dfb6955a766b4e2cc950505a5b51fd050b0/simplejson-3.20.1-cp310-cp310-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:03db8cb64154189a92a7786209f24e391644f3a3fa335658be2df2af1960b8d8", size = 138672 }, - { url = "https://files.pythonhosted.org/packages/21/47/50157810876c2a7ebbd6e6346ec25eda841fe061fecaa02538a7742a3d2a/simplejson-3.20.1-cp310-cp310-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:eea7e2b7d858f6fdfbf0fe3cb846d6bd8a45446865bc09960e51f3d473c2271b", size = 146616 }, - { url = "https://files.pythonhosted.org/packages/95/60/8c97cdc93096437b0aca2745aca63c880fe2315fd7f6a6ce6edbb344a2ae/simplejson-3.20.1-cp310-cp310-manylinux_2_5_i686.manylinux1_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:e66712b17d8425bb7ff8968d4c7c7fd5a2dd7bd63728b28356223c000dd2f91f", size = 134344 }, - { url = "https://files.pythonhosted.org/packages/bb/9e/da184f0e9bb3a5d7ffcde713bd41b4fe46cca56b6f24d9bd155fac56805a/simplejson-3.20.1-cp310-cp310-manylinux_2_5_x86_64.manylinux1_x86_64.manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:a2cc4f6486f9f515b62f5831ff1888886619b84fc837de68f26d919ba7bbdcbc", size = 138017 }, - { url = "https://files.pythonhosted.org/packages/31/db/00d1a8d9b036db98f678c8a3c69ed17d2894d1768d7a00576e787ad3e546/simplejson-3.20.1-cp310-cp310-musllinux_1_2_aarch64.whl", hash = "sha256:a3c2df555ee4016148fa192e2b9cd9e60bc1d40769366134882685e90aee2a1e", size = 140118 }, - { url = "https://files.pythonhosted.org/packages/52/21/57fc47eab8c1c73390b933a5ba9271f08e3e1ec83162c580357f28f5b97c/simplejson-3.20.1-cp310-cp310-musllinux_1_2_i686.whl", hash = "sha256:78520f04b7548a5e476b5396c0847e066f1e0a4c0c5e920da1ad65e95f410b11", size = 140314 }, - { url = "https://files.pythonhosted.org/packages/ad/cc/7cfd78d1e0fa5e57350b98cfe77353b6dfa13dce21afa4060e1019223852/simplejson-3.20.1-cp310-cp310-musllinux_1_2_ppc64le.whl", hash = "sha256:f4bd49ecde87b0fe9f55cc971449a32832bca9910821f7072bbfae1155eaa007", size = 148544 }, - { url = "https://files.pythonhosted.org/packages/63/26/1c894a1c2bd95dc8be0cf5a2fa73b0d173105b6ca18c90cb981ff10443d0/simplejson-3.20.1-cp310-cp310-musllinux_1_2_x86_64.whl", hash = "sha256:7eaae2b88eb5da53caaffdfa50e2e12022553949b88c0df4f9a9663609373f72", size = 141172 }, - { url = "https://files.pythonhosted.org/packages/93/27/0717dccc10cd9988dbf1314def52ab32678a95a95328bb37cafacf499400/simplejson-3.20.1-cp310-cp310-win32.whl", hash = "sha256:e836fb88902799eac8debc2b642300748f4860a197fa3d9ea502112b6bb8e142", size = 74181 }, - { url = "https://files.pythonhosted.org/packages/5f/af/593f896573f306519332d4287b1ab8b7b888c239bbd5159f7054d7055c2d/simplejson-3.20.1-cp310-cp310-win_amd64.whl", hash = "sha256:b122a19b552b212fc3b5b96fc5ce92333d4a9ac0a800803e1f17ebb16dac4be5", size = 75738 }, - { url = "https://files.pythonhosted.org/packages/76/59/74bc90d1c051bc2432c96b34bd4e8036875ab58b4fcbe4d6a5a76985f853/simplejson-3.20.1-cp311-cp311-macosx_10_9_universal2.whl", hash = "sha256:325b8c107253d3217e89d7b50c71015b5b31e2433e6c5bf38967b2f80630a8ca", size = 92132 }, - { url = "https://files.pythonhosted.org/packages/71/c7/1970916e0c51794fff89f76da2f632aaf0b259b87753c88a8c409623d3e1/simplejson-3.20.1-cp311-cp311-macosx_10_9_x86_64.whl", hash = "sha256:88a7baa8211089b9e58d78fbc1b0b322103f3f3d459ff16f03a36cece0d0fcf0", size = 74956 }, - { url = "https://files.pythonhosted.org/packages/c8/0d/98cc5909180463f1d75fac7180de62d4cdb4e82c4fef276b9e591979372c/simplejson-3.20.1-cp311-cp311-macosx_11_0_arm64.whl", hash = "sha256:299b1007b8101d50d95bc0db1bf5c38dc372e85b504cf77f596462083ee77e3f", size = 74772 }, - { url = "https://files.pythonhosted.org/packages/e1/94/a30a5211a90d67725a3e8fcc1c788189f2ae2ed2b96b63ed15d0b7f5d6bb/simplejson-3.20.1-cp311-cp311-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:03ec618ed65caab48e81e3ed29586236a8e57daef792f1f3bb59504a7e98cd10", size = 143575 }, - { url = "https://files.pythonhosted.org/packages/ee/08/cdb6821f1058eb5db46d252de69ff7e6c53f05f1bae6368fe20d5b51d37e/simplejson-3.20.1-cp311-cp311-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:cd2cdead1d3197f0ff43373cf4730213420523ba48697743e135e26f3d179f38", size = 153241 }, - { url = "https://files.pythonhosted.org/packages/4c/2d/ca3caeea0bdc5efc5503d5f57a2dfb56804898fb196dfada121323ee0ccb/simplejson-3.20.1-cp311-cp311-manylinux_2_5_i686.manylinux1_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:3466d2839fdc83e1af42e07b90bc8ff361c4e8796cd66722a40ba14e458faddd", size = 141500 }, - { url = "https://files.pythonhosted.org/packages/e1/33/d3e0779d5c58245e7370c98eb969275af6b7a4a5aec3b97cbf85f09ad328/simplejson-3.20.1-cp311-cp311-manylinux_2_5_x86_64.manylinux1_x86_64.manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:d492ed8e92f3a9f9be829205f44b1d0a89af6582f0cf43e0d129fa477b93fe0c", size = 144757 }, - { url = "https://files.pythonhosted.org/packages/54/53/2d93128bb55861b2fa36c5944f38da51a0bc6d83e513afc6f7838440dd15/simplejson-3.20.1-cp311-cp311-musllinux_1_2_aarch64.whl", hash = "sha256:f924b485537b640dc69434565463fd6fc0c68c65a8c6e01a823dd26c9983cf79", size = 144409 }, - { url = "https://files.pythonhosted.org/packages/99/4c/dac310a98f897ad3435b4bdc836d92e78f09e38c5dbf28211ed21dc59fa2/simplejson-3.20.1-cp311-cp311-musllinux_1_2_i686.whl", hash = "sha256:9e8eacf6a3491bf76ea91a8d46726368a6be0eb94993f60b8583550baae9439e", size = 146082 }, - { url = "https://files.pythonhosted.org/packages/ee/22/d7ba958cfed39827335b82656b1c46f89678faecda9a7677b47e87b48ee6/simplejson-3.20.1-cp311-cp311-musllinux_1_2_ppc64le.whl", hash = "sha256:d34d04bf90b4cea7c22d8b19091633908f14a096caa301b24c2f3d85b5068fb8", size = 154339 }, - { url = "https://files.pythonhosted.org/packages/b8/c8/b072b741129406a7086a0799c6f5d13096231bf35fdd87a0cffa789687fc/simplejson-3.20.1-cp311-cp311-musllinux_1_2_x86_64.whl", hash = "sha256:69dd28d4ce38390ea4aaf212902712c0fd1093dc4c1ff67e09687c3c3e15a749", size = 147915 }, - { url = "https://files.pythonhosted.org/packages/6c/46/8347e61e9cf3db5342a42f7fd30a81b4f5cf85977f916852d7674a540907/simplejson-3.20.1-cp311-cp311-win32.whl", hash = "sha256:dfe7a9da5fd2a3499436cd350f31539e0a6ded5da6b5b3d422df016444d65e43", size = 73972 }, - { url = "https://files.pythonhosted.org/packages/01/85/b52f24859237b4e9d523d5655796d911ba3d46e242eb1959c45b6af5aedd/simplejson-3.20.1-cp311-cp311-win_amd64.whl", hash = "sha256:896a6c04d7861d507d800da7642479c3547060bf97419d9ef73d98ced8258766", size = 75595 }, - { url = "https://files.pythonhosted.org/packages/8d/eb/34c16a1ac9ba265d024dc977ad84e1659d931c0a700967c3e59a98ed7514/simplejson-3.20.1-cp312-cp312-macosx_10_9_universal2.whl", hash = "sha256:f31c4a3a7ab18467ee73a27f3e59158255d1520f3aad74315edde7a940f1be23", size = 93100 }, - { url = "https://files.pythonhosted.org/packages/41/fc/2c2c007d135894971e6814e7c0806936e5bade28f8db4dd7e2a58b50debd/simplejson-3.20.1-cp312-cp312-macosx_10_9_x86_64.whl", hash = "sha256:884e6183d16b725e113b83a6fc0230152ab6627d4d36cb05c89c2c5bccfa7bc6", size = 75464 }, - { url = "https://files.pythonhosted.org/packages/0f/05/2b5ecb33b776c34bb5cace5de5d7669f9b60e3ca13c113037b2ca86edfbd/simplejson-3.20.1-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:03d7a426e416fe0d3337115f04164cd9427eb4256e843a6b8751cacf70abc832", size = 75112 }, - { url = "https://files.pythonhosted.org/packages/fe/36/1f3609a2792f06cd4b71030485f78e91eb09cfd57bebf3116bf2980a8bac/simplejson-3.20.1-cp312-cp312-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:000602141d0bddfcff60ea6a6e97d5e10c9db6b17fd2d6c66199fa481b6214bb", size = 150182 }, - { url = "https://files.pythonhosted.org/packages/2f/b0/053fbda38b8b602a77a4f7829def1b4f316cd8deb5440a6d3ee90790d2a4/simplejson-3.20.1-cp312-cp312-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:af8377a8af78226e82e3a4349efdde59ffa421ae88be67e18cef915e4023a595", size = 158363 }, - { url = "https://files.pythonhosted.org/packages/d1/4b/2eb84ae867539a80822e92f9be4a7200dffba609275faf99b24141839110/simplejson-3.20.1-cp312-cp312-manylinux_2_5_i686.manylinux1_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:15c7de4c88ab2fbcb8781a3b982ef883696736134e20b1210bca43fb42ff1acf", size = 148415 }, - { url = "https://files.pythonhosted.org/packages/e0/bd/400b0bd372a5666addf2540c7358bfc3841b9ce5cdbc5cc4ad2f61627ad8/simplejson-3.20.1-cp312-cp312-manylinux_2_5_x86_64.manylinux1_x86_64.manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:455a882ff3f97d810709f7b620007d4e0aca8da71d06fc5c18ba11daf1c4df49", size = 152213 }, - { url = "https://files.pythonhosted.org/packages/50/12/143f447bf6a827ee9472693768dc1a5eb96154f8feb140a88ce6973a3cfa/simplejson-3.20.1-cp312-cp312-musllinux_1_2_aarch64.whl", hash = "sha256:fc0f523ce923e7f38eb67804bc80e0a028c76d7868500aa3f59225574b5d0453", size = 150048 }, - { url = "https://files.pythonhosted.org/packages/5e/ea/dd9b3e8e8ed710a66f24a22c16a907c9b539b6f5f45fd8586bd5c231444e/simplejson-3.20.1-cp312-cp312-musllinux_1_2_i686.whl", hash = "sha256:76461ec929282dde4a08061071a47281ad939d0202dc4e63cdd135844e162fbc", size = 151668 }, - { url = "https://files.pythonhosted.org/packages/99/af/ee52a8045426a0c5b89d755a5a70cc821815ef3c333b56fbcad33c4435c0/simplejson-3.20.1-cp312-cp312-musllinux_1_2_ppc64le.whl", hash = "sha256:ab19c2da8c043607bde4d4ef3a6b633e668a7d2e3d56f40a476a74c5ea71949f", size = 158840 }, - { url = "https://files.pythonhosted.org/packages/68/db/ab32869acea6b5de7d75fa0dac07a112ded795d41eaa7e66c7813b17be95/simplejson-3.20.1-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:b2578bedaedf6294415197b267d4ef678fea336dd78ee2a6d2f4b028e9d07be3", size = 154212 }, - { url = "https://files.pythonhosted.org/packages/fa/7a/e3132d454977d75a3bf9a6d541d730f76462ebf42a96fea2621498166f41/simplejson-3.20.1-cp312-cp312-win32.whl", hash = "sha256:339f407373325a36b7fd744b688ba5bae0666b5d340ec6d98aebc3014bf3d8ea", size = 74101 }, - { url = "https://files.pythonhosted.org/packages/bc/5d/4e243e937fa3560107c69f6f7c2eed8589163f5ed14324e864871daa2dd9/simplejson-3.20.1-cp312-cp312-win_amd64.whl", hash = "sha256:627d4486a1ea7edf1f66bb044ace1ce6b4c1698acd1b05353c97ba4864ea2e17", size = 75736 }, - { url = "https://files.pythonhosted.org/packages/c4/03/0f453a27877cb5a5fff16a975925f4119102cc8552f52536b9a98ef0431e/simplejson-3.20.1-cp313-cp313-macosx_10_13_universal2.whl", hash = "sha256:71e849e7ceb2178344998cbe5ade101f1b329460243c79c27fbfc51c0447a7c3", size = 93109 }, - { url = "https://files.pythonhosted.org/packages/74/1f/a729f4026850cabeaff23e134646c3f455e86925d2533463420635ae54de/simplejson-3.20.1-cp313-cp313-macosx_10_13_x86_64.whl", hash = "sha256:b63fdbab29dc3868d6f009a59797cefaba315fd43cd32ddd998ee1da28e50e29", size = 75475 }, - { url = "https://files.pythonhosted.org/packages/e2/14/50a2713fee8ff1f8d655b1a14f4a0f1c0c7246768a1b3b3d12964a4ed5aa/simplejson-3.20.1-cp313-cp313-macosx_11_0_arm64.whl", hash = "sha256:1190f9a3ce644fd50ec277ac4a98c0517f532cfebdcc4bd975c0979a9f05e1fb", size = 75112 }, - { url = "https://files.pythonhosted.org/packages/45/86/ea9835abb646755140e2d482edc9bc1e91997ed19a59fd77ae4c6a0facea/simplejson-3.20.1-cp313-cp313-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:c1336ba7bcb722ad487cd265701ff0583c0bb6de638364ca947bb84ecc0015d1", size = 150245 }, - { url = "https://files.pythonhosted.org/packages/12/b4/53084809faede45da829fe571c65fbda8479d2a5b9c633f46b74124d56f5/simplejson-3.20.1-cp313-cp313-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:e975aac6a5acd8b510eba58d5591e10a03e3d16c1cf8a8624ca177491f7230f0", size = 158465 }, - { url = "https://files.pythonhosted.org/packages/a9/7d/d56579468d1660b3841e1f21c14490d103e33cf911886b22652d6e9683ec/simplejson-3.20.1-cp313-cp313-manylinux_2_5_i686.manylinux1_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:6a6dd11ee282937ad749da6f3b8d87952ad585b26e5edfa10da3ae2536c73078", size = 148514 }, - { url = "https://files.pythonhosted.org/packages/19/e3/874b1cca3d3897b486d3afdccc475eb3a09815bf1015b01cf7fcb52a55f0/simplejson-3.20.1-cp313-cp313-manylinux_2_5_x86_64.manylinux1_x86_64.manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:ab980fcc446ab87ea0879edad41a5c28f2d86020014eb035cf5161e8de4474c6", size = 152262 }, - { url = "https://files.pythonhosted.org/packages/32/84/f0fdb3625292d945c2bd13a814584603aebdb38cfbe5fe9be6b46fe598c4/simplejson-3.20.1-cp313-cp313-musllinux_1_2_aarch64.whl", hash = "sha256:f5aee2a4cb6b146bd17333ac623610f069f34e8f31d2f4f0c1a2186e50c594f0", size = 150164 }, - { url = "https://files.pythonhosted.org/packages/95/51/6d625247224f01eaaeabace9aec75ac5603a42f8ebcce02c486fbda8b428/simplejson-3.20.1-cp313-cp313-musllinux_1_2_i686.whl", hash = "sha256:652d8eecbb9a3b6461b21ec7cf11fd0acbab144e45e600c817ecf18e4580b99e", size = 151795 }, - { url = "https://files.pythonhosted.org/packages/7f/d9/bb921df6b35be8412f519e58e86d1060fddf3ad401b783e4862e0a74c4c1/simplejson-3.20.1-cp313-cp313-musllinux_1_2_ppc64le.whl", hash = "sha256:8c09948f1a486a89251ee3a67c9f8c969b379f6ffff1a6064b41fea3bce0a112", size = 159027 }, - { url = "https://files.pythonhosted.org/packages/03/c5/5950605e4ad023a6621cf4c931b29fd3d2a9c1f36be937230bfc83d7271d/simplejson-3.20.1-cp313-cp313-musllinux_1_2_x86_64.whl", hash = "sha256:cbbd7b215ad4fc6f058b5dd4c26ee5c59f72e031dfda3ac183d7968a99e4ca3a", size = 154380 }, - { url = "https://files.pythonhosted.org/packages/66/ad/b74149557c5ec1e4e4d55758bda426f5d2ec0123cd01a53ae63b8de51fa3/simplejson-3.20.1-cp313-cp313-win32.whl", hash = "sha256:ae81e482476eaa088ef9d0120ae5345de924f23962c0c1e20abbdff597631f87", size = 74102 }, - { url = "https://files.pythonhosted.org/packages/db/a9/25282fdd24493e1022f30b7f5cdf804255c007218b2bfaa655bd7ad34b2d/simplejson-3.20.1-cp313-cp313-win_amd64.whl", hash = "sha256:1b9fd15853b90aec3b1739f4471efbf1ac05066a2c7041bf8db821bb73cd2ddc", size = 75736 }, - { url = "https://files.pythonhosted.org/packages/4b/30/00f02a0a921556dd5a6db1ef2926a1bc7a8bbbfb1c49cfed68a275b8ab2b/simplejson-3.20.1-py3-none-any.whl", hash = "sha256:8a6c1bbac39fa4a79f83cbf1df6ccd8ff7069582a9fd8db1e52cea073bc2c697", size = 57121 }, +version = "3.20.2" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/41/f4/a1ac5ed32f7ed9a088d62a59d410d4c204b3b3815722e2ccfb491fa8251b/simplejson-3.20.2.tar.gz", hash = "sha256:5fe7a6ce14d1c300d80d08695b7f7e633de6cd72c80644021874d985b3393649", size = 85784, upload-time = "2025-09-26T16:29:36.64Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/78/09/2bf3761de89ea2d91bdce6cf107dcd858892d0adc22c995684878826cc6b/simplejson-3.20.2-cp310-cp310-macosx_10_9_universal2.whl", hash = "sha256:6d7286dc11af60a2f76eafb0c2acde2d997e87890e37e24590bb513bec9f1bc5", size = 94039, upload-time = "2025-09-26T16:27:29.283Z" }, + { url = "https://files.pythonhosted.org/packages/0f/33/c3277db8931f0ae9e54b9292668863365672d90fb0f632f4cf9829cb7d68/simplejson-3.20.2-cp310-cp310-macosx_10_9_x86_64.whl", hash = "sha256:c01379b4861c3b0aa40cba8d44f2b448f5743999aa68aaa5d3ef7049d4a28a2d", size = 75894, upload-time = "2025-09-26T16:27:30.378Z" }, + { url = "https://files.pythonhosted.org/packages/fa/ea/ae47b04d03c7c8a7b7b1a8b39a6e27c3bd424e52f4988d70aca6293ff5e5/simplejson-3.20.2-cp310-cp310-macosx_11_0_arm64.whl", hash = "sha256:a16b029ca25645b3bc44e84a4f941efa51bf93c180b31bd704ce6349d1fc77c1", size = 76116, upload-time = "2025-09-26T16:27:31.42Z" }, + { url = "https://files.pythonhosted.org/packages/4b/42/6c9af551e5a8d0f171d6dce3d9d1260068927f7b80f1f09834e07887c8c4/simplejson-3.20.2-cp310-cp310-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:3e22a5fb7b1437ffb057e02e1936a3bfb19084ae9d221ec5e9f4cf85f69946b6", size = 138827, upload-time = "2025-09-26T16:27:32.486Z" }, + { url = "https://files.pythonhosted.org/packages/2b/22/5e268bbcbe9f75577491e406ec0a5536f5b2fa91a3b52031fea51cd83e1d/simplejson-3.20.2-cp310-cp310-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:d8b6ff02fc7b8555c906c24735908854819b0d0dc85883d453e23ca4c0445d01", size = 146772, upload-time = "2025-09-26T16:27:34.036Z" }, + { url = "https://files.pythonhosted.org/packages/71/b4/800f14728e2ad666f420dfdb57697ca128aeae7f991b35759c09356b829a/simplejson-3.20.2-cp310-cp310-manylinux_2_5_i686.manylinux1_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:2bfc1c396ad972ba4431130b42307b2321dba14d988580c1ac421ec6a6b7cee3", size = 134497, upload-time = "2025-09-26T16:27:35.211Z" }, + { url = "https://files.pythonhosted.org/packages/c1/b9/c54eef4226c6ac8e9a389bbe5b21fef116768f97a2dc1a683c716ffe66ef/simplejson-3.20.2-cp310-cp310-manylinux_2_5_x86_64.manylinux1_x86_64.manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:3a97249ee1aee005d891b5a211faf58092a309f3d9d440bc269043b08f662eda", size = 138172, upload-time = "2025-09-26T16:27:36.44Z" }, + { url = "https://files.pythonhosted.org/packages/09/36/4e282f5211b34620f1b2e4b51d9ddaab5af82219b9b7b78360a33f7e5387/simplejson-3.20.2-cp310-cp310-musllinux_1_2_aarch64.whl", hash = "sha256:f1036be00b5edaddbddbb89c0f80ed229714a941cfd21e51386dc69c237201c2", size = 140272, upload-time = "2025-09-26T16:27:37.605Z" }, + { url = "https://files.pythonhosted.org/packages/aa/b0/94ad2cf32f477c449e1f63c863d8a513e2408d651c4e58fe4b6a7434e168/simplejson-3.20.2-cp310-cp310-musllinux_1_2_i686.whl", hash = "sha256:5d6f5bacb8cdee64946b45f2680afa3f54cd38e62471ceda89f777693aeca4e4", size = 140468, upload-time = "2025-09-26T16:27:39.015Z" }, + { url = "https://files.pythonhosted.org/packages/e5/46/827731e4163be3f987cb8ee90f5d444161db8f540b5e735355faa098d9bc/simplejson-3.20.2-cp310-cp310-musllinux_1_2_ppc64le.whl", hash = "sha256:8db6841fb796ec5af632f677abf21c6425a1ebea0d9ac3ef1a340b8dc69f52b8", size = 148700, upload-time = "2025-09-26T16:27:40.171Z" }, + { url = "https://files.pythonhosted.org/packages/c7/28/c32121064b1ec2fb7b5d872d9a1abda62df064d35e0160eddfa907118343/simplejson-3.20.2-cp310-cp310-musllinux_1_2_x86_64.whl", hash = "sha256:c0a341f7cc2aae82ee2b31f8a827fd2e51d09626f8b3accc441a6907c88aedb7", size = 141323, upload-time = "2025-09-26T16:27:41.324Z" }, + { url = "https://files.pythonhosted.org/packages/46/b6/c897c54326fe86dd12d101981171a49361949f4728294f418c3b86a1af77/simplejson-3.20.2-cp310-cp310-win32.whl", hash = "sha256:27f9c01a6bc581d32ab026f515226864576da05ef322d7fc141cd8a15a95ce53", size = 74377, upload-time = "2025-09-26T16:27:42.533Z" }, + { url = "https://files.pythonhosted.org/packages/ad/87/a6e03d4d80cca99c1fee4e960f3440e2f21be9470e537970f960ca5547f1/simplejson-3.20.2-cp310-cp310-win_amd64.whl", hash = "sha256:c0a63ec98a4547ff366871bf832a7367ee43d047bcec0b07b66c794e2137b476", size = 76081, upload-time = "2025-09-26T16:27:43.945Z" }, + { url = "https://files.pythonhosted.org/packages/b9/3e/96898c6c66d9dca3f9bd14d7487bf783b4acc77471b42f979babbb68d4ca/simplejson-3.20.2-cp311-cp311-macosx_10_9_universal2.whl", hash = "sha256:06190b33cd7849efc413a5738d3da00b90e4a5382fd3d584c841ac20fb828c6f", size = 92633, upload-time = "2025-09-26T16:27:45.028Z" }, + { url = "https://files.pythonhosted.org/packages/6b/a2/cd2e10b880368305d89dd540685b8bdcc136df2b3c76b5ddd72596254539/simplejson-3.20.2-cp311-cp311-macosx_10_9_x86_64.whl", hash = "sha256:4ad4eac7d858947a30d2c404e61f16b84d16be79eb6fb316341885bdde864fa8", size = 75309, upload-time = "2025-09-26T16:27:46.142Z" }, + { url = "https://files.pythonhosted.org/packages/5d/02/290f7282eaa6ebe945d35c47e6534348af97472446951dce0d144e013f4c/simplejson-3.20.2-cp311-cp311-macosx_11_0_arm64.whl", hash = "sha256:b392e11c6165d4a0fde41754a0e13e1d88a5ad782b245a973dd4b2bdb4e5076a", size = 75308, upload-time = "2025-09-26T16:27:47.542Z" }, + { url = "https://files.pythonhosted.org/packages/43/91/43695f17b69e70c4b0b03247aa47fb3989d338a70c4b726bbdc2da184160/simplejson-3.20.2-cp311-cp311-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:51eccc4e353eed3c50e0ea2326173acdc05e58f0c110405920b989d481287e51", size = 143733, upload-time = "2025-09-26T16:27:48.673Z" }, + { url = "https://files.pythonhosted.org/packages/9b/4b/fdcaf444ac1c3cbf1c52bf00320c499e1cf05d373a58a3731ae627ba5e2d/simplejson-3.20.2-cp311-cp311-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:306e83d7c331ad833d2d43c76a67f476c4b80c4a13334f6e34bb110e6105b3bd", size = 153397, upload-time = "2025-09-26T16:27:49.89Z" }, + { url = "https://files.pythonhosted.org/packages/c4/83/21550f81a50cd03599f048a2d588ffb7f4c4d8064ae091511e8e5848eeaa/simplejson-3.20.2-cp311-cp311-manylinux_2_5_i686.manylinux1_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:f820a6ac2ef0bc338ae4963f4f82ccebdb0824fe9caf6d660670c578abe01013", size = 141654, upload-time = "2025-09-26T16:27:51.168Z" }, + { url = "https://files.pythonhosted.org/packages/cf/54/d76c0e72ad02450a3e723b65b04f49001d0e73218ef6a220b158a64639cb/simplejson-3.20.2-cp311-cp311-manylinux_2_5_x86_64.manylinux1_x86_64.manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:21e7a066528a5451433eb3418184f05682ea0493d14e9aae690499b7e1eb6b81", size = 144913, upload-time = "2025-09-26T16:27:52.331Z" }, + { url = "https://files.pythonhosted.org/packages/3f/49/976f59b42a6956d4aeb075ada16ad64448a985704bc69cd427a2245ce835/simplejson-3.20.2-cp311-cp311-musllinux_1_2_aarch64.whl", hash = "sha256:438680ddde57ea87161a4824e8de04387b328ad51cfdf1eaf723623a3014b7aa", size = 144568, upload-time = "2025-09-26T16:27:53.41Z" }, + { url = "https://files.pythonhosted.org/packages/60/c7/30bae30424ace8cd791ca660fed454ed9479233810fe25c3f3eab3d9dc7b/simplejson-3.20.2-cp311-cp311-musllinux_1_2_i686.whl", hash = "sha256:cac78470ae68b8d8c41b6fca97f5bf8e024ca80d5878c7724e024540f5cdaadb", size = 146239, upload-time = "2025-09-26T16:27:54.502Z" }, + { url = "https://files.pythonhosted.org/packages/79/3e/7f3b7b97351c53746e7b996fcd106986cda1954ab556fd665314756618d2/simplejson-3.20.2-cp311-cp311-musllinux_1_2_ppc64le.whl", hash = "sha256:7524e19c2da5ef281860a3d74668050c6986be15c9dd99966034ba47c68828c2", size = 154497, upload-time = "2025-09-26T16:27:55.885Z" }, + { url = "https://files.pythonhosted.org/packages/1d/48/7241daa91d0bf19126589f6a8dcbe8287f4ed3d734e76fd4a092708947be/simplejson-3.20.2-cp311-cp311-musllinux_1_2_x86_64.whl", hash = "sha256:0e9b6d845a603b2eef3394eb5e21edb8626cd9ae9a8361d14e267eb969dbe413", size = 148069, upload-time = "2025-09-26T16:27:57.039Z" }, + { url = "https://files.pythonhosted.org/packages/e6/f4/ef18d2962fe53e7be5123d3784e623859eec7ed97060c9c8536c69d34836/simplejson-3.20.2-cp311-cp311-win32.whl", hash = "sha256:47d8927e5ac927fdd34c99cc617938abb3624b06ff86e8e219740a86507eb961", size = 74158, upload-time = "2025-09-26T16:27:58.265Z" }, + { url = "https://files.pythonhosted.org/packages/35/fd/3d1158ecdc573fdad81bf3cc78df04522bf3959758bba6597ba4c956c74d/simplejson-3.20.2-cp311-cp311-win_amd64.whl", hash = "sha256:ba4edf3be8e97e4713d06c3d302cba1ff5c49d16e9d24c209884ac1b8455520c", size = 75911, upload-time = "2025-09-26T16:27:59.292Z" }, + { url = "https://files.pythonhosted.org/packages/9d/9e/1a91e7614db0416885eab4136d49b7303de20528860ffdd798ce04d054db/simplejson-3.20.2-cp312-cp312-macosx_10_9_universal2.whl", hash = "sha256:4376d5acae0d1e91e78baeba4ee3cf22fbf6509d81539d01b94e0951d28ec2b6", size = 93523, upload-time = "2025-09-26T16:28:00.356Z" }, + { url = "https://files.pythonhosted.org/packages/5e/2b/d2413f5218fc25608739e3d63fe321dfa85c5f097aa6648dbe72513a5f12/simplejson-3.20.2-cp312-cp312-macosx_10_9_x86_64.whl", hash = "sha256:f8fe6de652fcddae6dec8f281cc1e77e4e8f3575249e1800090aab48f73b4259", size = 75844, upload-time = "2025-09-26T16:28:01.756Z" }, + { url = "https://files.pythonhosted.org/packages/ad/f1/efd09efcc1e26629e120fef59be059ce7841cc6e1f949a4db94f1ae8a918/simplejson-3.20.2-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:25ca2663d99328d51e5a138f22018e54c9162438d831e26cfc3458688616eca8", size = 75655, upload-time = "2025-09-26T16:28:03.037Z" }, + { url = "https://files.pythonhosted.org/packages/97/ec/5c6db08e42f380f005d03944be1af1a6bd501cc641175429a1cbe7fb23b9/simplejson-3.20.2-cp312-cp312-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:12a6b2816b6cab6c3fd273d43b1948bc9acf708272074c8858f579c394f4cbc9", size = 150335, upload-time = "2025-09-26T16:28:05.027Z" }, + { url = "https://files.pythonhosted.org/packages/81/f5/808a907485876a9242ec67054da7cbebefe0ee1522ef1c0be3bfc90f96f6/simplejson-3.20.2-cp312-cp312-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:ac20dc3fcdfc7b8415bfc3d7d51beccd8695c3f4acb7f74e3a3b538e76672868", size = 158519, upload-time = "2025-09-26T16:28:06.5Z" }, + { url = "https://files.pythonhosted.org/packages/66/af/b8a158246834645ea890c36136584b0cc1c0e4b83a73b11ebd9c2a12877c/simplejson-3.20.2-cp312-cp312-manylinux_2_5_i686.manylinux1_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:db0804d04564e70862ef807f3e1ace2cc212ef0e22deb1b3d6f80c45e5882c6b", size = 148571, upload-time = "2025-09-26T16:28:07.715Z" }, + { url = "https://files.pythonhosted.org/packages/20/05/ed9b2571bbf38f1a2425391f18e3ac11cb1e91482c22d644a1640dea9da7/simplejson-3.20.2-cp312-cp312-manylinux_2_5_x86_64.manylinux1_x86_64.manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:979ce23ea663895ae39106946ef3d78527822d918a136dbc77b9e2b7f006237e", size = 152367, upload-time = "2025-09-26T16:28:08.921Z" }, + { url = "https://files.pythonhosted.org/packages/81/2c/bad68b05dd43e93f77994b920505634d31ed239418eb6a88997d06599983/simplejson-3.20.2-cp312-cp312-musllinux_1_2_aarch64.whl", hash = "sha256:a2ba921b047bb029805726800819675249ef25d2f65fd0edb90639c5b1c3033c", size = 150205, upload-time = "2025-09-26T16:28:10.086Z" }, + { url = "https://files.pythonhosted.org/packages/69/46/90c7fc878061adafcf298ce60cecdee17a027486e9dce507e87396d68255/simplejson-3.20.2-cp312-cp312-musllinux_1_2_i686.whl", hash = "sha256:12d3d4dc33770069b780cc8f5abef909fe4a3f071f18f55f6d896a370fd0f970", size = 151823, upload-time = "2025-09-26T16:28:11.329Z" }, + { url = "https://files.pythonhosted.org/packages/ab/27/b85b03349f825ae0f5d4f780cdde0bbccd4f06c3d8433f6a3882df887481/simplejson-3.20.2-cp312-cp312-musllinux_1_2_ppc64le.whl", hash = "sha256:aff032a59a201b3683a34be1169e71ddda683d9c3b43b261599c12055349251e", size = 158997, upload-time = "2025-09-26T16:28:12.917Z" }, + { url = "https://files.pythonhosted.org/packages/71/ad/d7f3c331fb930638420ac6d236db68e9f4c28dab9c03164c3cd0e7967e15/simplejson-3.20.2-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:30e590e133b06773f0dc9c3f82e567463df40598b660b5adf53eb1c488202544", size = 154367, upload-time = "2025-09-26T16:28:14.393Z" }, + { url = "https://files.pythonhosted.org/packages/f0/46/5c67324addd40fa2966f6e886cacbbe0407c03a500db94fb8bb40333fcdf/simplejson-3.20.2-cp312-cp312-win32.whl", hash = "sha256:8d7be7c99939cc58e7c5bcf6bb52a842a58e6c65e1e9cdd2a94b697b24cddb54", size = 74285, upload-time = "2025-09-26T16:28:15.931Z" }, + { url = "https://files.pythonhosted.org/packages/fa/c9/5cc2189f4acd3a6e30ffa9775bf09b354302dbebab713ca914d7134d0f29/simplejson-3.20.2-cp312-cp312-win_amd64.whl", hash = "sha256:2c0b4a67e75b945489052af6590e7dca0ed473ead5d0f3aad61fa584afe814ab", size = 75969, upload-time = "2025-09-26T16:28:17.017Z" }, + { url = "https://files.pythonhosted.org/packages/5e/9e/f326d43f6bf47f4e7704a4426c36e044c6bedfd24e072fb8e27589a373a5/simplejson-3.20.2-cp313-cp313-macosx_10_13_universal2.whl", hash = "sha256:90d311ba8fcd733a3677e0be21804827226a57144130ba01c3c6a325e887dd86", size = 93530, upload-time = "2025-09-26T16:28:18.07Z" }, + { url = "https://files.pythonhosted.org/packages/35/28/5a4b8f3483fbfb68f3f460bc002cef3a5735ef30950e7c4adce9c8da15c7/simplejson-3.20.2-cp313-cp313-macosx_10_13_x86_64.whl", hash = "sha256:feed6806f614bdf7f5cb6d0123cb0c1c5f40407ef103aa935cffaa694e2e0c74", size = 75846, upload-time = "2025-09-26T16:28:19.12Z" }, + { url = "https://files.pythonhosted.org/packages/7a/4d/30dfef83b9ac48afae1cf1ab19c2867e27b8d22b5d9f8ca7ce5a0a157d8c/simplejson-3.20.2-cp313-cp313-macosx_11_0_arm64.whl", hash = "sha256:6b1d8d7c3e1a205c49e1aee6ba907dcb8ccea83651e6c3e2cb2062f1e52b0726", size = 75661, upload-time = "2025-09-26T16:28:20.219Z" }, + { url = "https://files.pythonhosted.org/packages/09/1d/171009bd35c7099d72ef6afd4bb13527bab469965c968a17d69a203d62a6/simplejson-3.20.2-cp313-cp313-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:552f55745044a24c3cb7ec67e54234be56d5d6d0e054f2e4cf4fb3e297429be5", size = 150579, upload-time = "2025-09-26T16:28:21.337Z" }, + { url = "https://files.pythonhosted.org/packages/61/ae/229bbcf90a702adc6bfa476e9f0a37e21d8c58e1059043038797cbe75b8c/simplejson-3.20.2-cp313-cp313-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:c2da97ac65165d66b0570c9e545786f0ac7b5de5854d3711a16cacbcaa8c472d", size = 158797, upload-time = "2025-09-26T16:28:22.53Z" }, + { url = "https://files.pythonhosted.org/packages/90/c5/fefc0ac6b86b9108e302e0af1cf57518f46da0baedd60a12170791d56959/simplejson-3.20.2-cp313-cp313-manylinux_2_5_i686.manylinux1_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:f59a12966daa356bf68927fca5a67bebac0033cd18b96de9c2d426cd11756cd0", size = 148851, upload-time = "2025-09-26T16:28:23.733Z" }, + { url = "https://files.pythonhosted.org/packages/43/f1/b392952200f3393bb06fbc4dd975fc63a6843261705839355560b7264eb2/simplejson-3.20.2-cp313-cp313-manylinux_2_5_x86_64.manylinux1_x86_64.manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:133ae2098a8e162c71da97cdab1f383afdd91373b7ff5fe65169b04167da976b", size = 152598, upload-time = "2025-09-26T16:28:24.962Z" }, + { url = "https://files.pythonhosted.org/packages/f4/b4/d6b7279e52a3e9c0fa8c032ce6164e593e8d9cf390698ee981ed0864291b/simplejson-3.20.2-cp313-cp313-musllinux_1_2_aarch64.whl", hash = "sha256:7977640af7b7d5e6a852d26622057d428706a550f7f5083e7c4dd010a84d941f", size = 150498, upload-time = "2025-09-26T16:28:26.114Z" }, + { url = "https://files.pythonhosted.org/packages/62/22/ec2490dd859224326d10c2fac1353e8ad5c84121be4837a6dd6638ba4345/simplejson-3.20.2-cp313-cp313-musllinux_1_2_i686.whl", hash = "sha256:b530ad6d55e71fa9e93e1109cf8182f427a6355848a4ffa09f69cc44e1512522", size = 152129, upload-time = "2025-09-26T16:28:27.552Z" }, + { url = "https://files.pythonhosted.org/packages/33/ce/b60214d013e93dd9e5a705dcb2b88b6c72bada442a97f79828332217f3eb/simplejson-3.20.2-cp313-cp313-musllinux_1_2_ppc64le.whl", hash = "sha256:bd96a7d981bf64f0e42345584768da4435c05b24fd3c364663f5fbc8fabf82e3", size = 159359, upload-time = "2025-09-26T16:28:28.667Z" }, + { url = "https://files.pythonhosted.org/packages/99/21/603709455827cdf5b9d83abe726343f542491ca8dc6a2528eb08de0cf034/simplejson-3.20.2-cp313-cp313-musllinux_1_2_x86_64.whl", hash = "sha256:f28ee755fadb426ba2e464d6fcf25d3f152a05eb6b38e0b4f790352f5540c769", size = 154717, upload-time = "2025-09-26T16:28:30.288Z" }, + { url = "https://files.pythonhosted.org/packages/3c/f9/dc7f7a4bac16cf7eb55a4df03ad93190e11826d2a8950052949d3dfc11e2/simplejson-3.20.2-cp313-cp313-win32.whl", hash = "sha256:472785b52e48e3eed9b78b95e26a256f59bb1ee38339be3075dad799e2e1e661", size = 74289, upload-time = "2025-09-26T16:28:31.809Z" }, + { url = "https://files.pythonhosted.org/packages/87/10/d42ad61230436735c68af1120622b28a782877146a83d714da7b6a2a1c4e/simplejson-3.20.2-cp313-cp313-win_amd64.whl", hash = "sha256:a1a85013eb33e4820286139540accbe2c98d2da894b2dcefd280209db508e608", size = 75972, upload-time = "2025-09-26T16:28:32.883Z" }, + { url = "https://files.pythonhosted.org/packages/05/5b/83e1ff87eb60ca706972f7e02e15c0b33396e7bdbd080069a5d1b53cf0d8/simplejson-3.20.2-py3-none-any.whl", hash = "sha256:3b6bb7fb96efd673eac2e4235200bfffdc2353ad12c54117e1e4e2fc485ac017", size = 57309, upload-time = "2025-09-26T16:29:35.312Z" }, ] [[package]] name = "six" version = "1.17.0" source = { registry = "https://pypi.org/simple" } -sdist = { url = "https://files.pythonhosted.org/packages/94/e7/b2c673351809dca68a0e064b6af791aa332cf192da575fd474ed7d6f16a2/six-1.17.0.tar.gz", hash = "sha256:ff70335d468e7eb6ec65b95b99d3a2836546063f63acc5171de367e834932a81", size = 34031 } +sdist = { url = "https://files.pythonhosted.org/packages/94/e7/b2c673351809dca68a0e064b6af791aa332cf192da575fd474ed7d6f16a2/six-1.17.0.tar.gz", hash = "sha256:ff70335d468e7eb6ec65b95b99d3a2836546063f63acc5171de367e834932a81", size = 34031, upload-time = "2024-12-04T17:35:28.174Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/b7/ce/149a00dd41f10bc29e5921b496af8b574d8413afcd5e30dfa0ed46c2cc5e/six-1.17.0-py2.py3-none-any.whl", hash = "sha256:4721f391ed90541fddacab5acf947aa0d3dc7d27b2e1e8eda2be8970586c3274", size = 11050 }, + { url = "https://files.pythonhosted.org/packages/b7/ce/149a00dd41f10bc29e5921b496af8b574d8413afcd5e30dfa0ed46c2cc5e/six-1.17.0-py2.py3-none-any.whl", hash = "sha256:4721f391ed90541fddacab5acf947aa0d3dc7d27b2e1e8eda2be8970586c3274", size = 11050, upload-time = "2024-12-04T17:35:26.475Z" }, ] [[package]] name = "super-collections" -version = "0.5.3" +version = "0.6.2" source = { registry = "https://pypi.org/simple" } dependencies = [ { name = "hjson" }, ] -sdist = { url = "https://files.pythonhosted.org/packages/b8/05/d1b50919a0d206d77255217d96dea9ab34bd1eb965a21559380c48f9517e/super_collections-0.5.3.tar.gz", hash = "sha256:94c1ec96c0a0d5e8e7d389ed8cde6882ac246940507c5e6b86e91945c2968d46", size = 10178 } +sdist = { url = "https://files.pythonhosted.org/packages/e0/de/a0c3d1244912c260638f0f925e190e493ccea37ecaea9bbad7c14413b803/super_collections-0.6.2.tar.gz", hash = "sha256:0c8d8abacd9fad2c7c1c715f036c29f5db213f8cac65f24d45ecba12b4da187a", size = 31315, upload-time = "2025-09-30T00:37:08.067Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/07/6d/58de58c521e7fb79bceb4da90d55250070bb4adfa3c870b82519a561c79d/super_collections-0.5.3-py3-none-any.whl", hash = "sha256:907d35b25dc4070910e8254bf2f5c928348af1cf8a1f1e8259e06c666e902cff", size = 8436 }, + { url = "https://files.pythonhosted.org/packages/17/43/47c7cf84b3bd74a8631b02d47db356656bb8dff6f2e61a4c749963814d0d/super_collections-0.6.2-py3-none-any.whl", hash = "sha256:291b74d26299e9051d69ad9d89e61b07b6646f86a57a2f5ab3063d206eee9c56", size = 16173, upload-time = "2025-09-30T00:37:07.104Z" }, ] [[package]] name = "tensorstore" -version = "0.1.76" +version = "0.1.77" source = { registry = "https://pypi.org/simple" } dependencies = [ { name = "ml-dtypes" }, { name = "numpy", version = "2.2.6", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version < '3.11'" }, - { name = "numpy", version = "2.3.1", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version >= '3.11'" }, -] -sdist = { url = "https://files.pythonhosted.org/packages/ff/ae/947a9f232de7319b664ed8d278e9e0363e9294da73fd422c687ac4eb070e/tensorstore-0.1.76.tar.gz", hash = "sha256:ed0d565e7a038a84b1b5b5d9f7397caec200b53941d8889f44b7f63dd6abffe7", size = 6869230 } -wheels = [ - { url = "https://files.pythonhosted.org/packages/ca/66/6da79c349c3576836efec0195851bb71fed307dd9855de0692bf3e4df6cb/tensorstore-0.1.76-cp310-cp310-macosx_10_14_x86_64.whl", hash = "sha256:97e9eeab539369b99828c07e1d7da93062da91b65503dafe06d941208b0869d3", size = 15674263 }, - { url = "https://files.pythonhosted.org/packages/24/e7/014f188a5bd2087cdf0df154ee756ca95bae62ba76765f8f180e9dbc4e78/tensorstore-0.1.76-cp310-cp310-macosx_11_0_arm64.whl", hash = "sha256:a9c6f207a0b5f5138f7844307e5cb96587a73e9ba7b5edb6429524cca985e2c3", size = 13601077 }, - { url = "https://files.pythonhosted.org/packages/48/63/38410a20016c6c0b28d9970bcb63762f4df4b62a53eeddb27044deeb4792/tensorstore-0.1.76-cp310-cp310-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:05aae734cfaf5c1356b6f2c56226526607361c6e9aa6751df395dda53c3783b1", size = 17545411 }, - { url = "https://files.pythonhosted.org/packages/ca/83/17fb39326adfee5d7048093ee248b3aa69c47031e62832825e29da81d0b7/tensorstore-0.1.76-cp310-cp310-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:7574f837d8bfccf374795100be23f155eff3040f8b0f2010b1a0b2e1d4d6f791", size = 18923422 }, - { url = "https://files.pythonhosted.org/packages/7a/a1/8932f2871e1f390e29f587c3295f3f00113d1a32a05b0723ef06f0134630/tensorstore-0.1.76-cp310-cp310-win_amd64.whl", hash = "sha256:9c964c7538805867894f6ba4a03dfa57e434b73d0c563d93fcbf6245eb67cc2c", size = 12609199 }, - { url = "https://files.pythonhosted.org/packages/9b/9e/b3d691d14122064e16a3a47c14ce3b1178d749e59b3afec91a8656125c29/tensorstore-0.1.76-cp311-cp311-macosx_10_14_x86_64.whl", hash = "sha256:1c882dcf30049952cb6b183c70bd1922815cdbceca8d4115a7fbeb3b5513f9e4", size = 15675667 }, - { url = "https://files.pythonhosted.org/packages/0c/bb/16d97d8b31912f27019115eb23b7feb0b83bf520858b97aec64064653329/tensorstore-0.1.76-cp311-cp311-macosx_11_0_arm64.whl", hash = "sha256:262b856b21626688cefd11913737a94800b1ba3061d56d70babc439ef69587bc", size = 13602503 }, - { url = "https://files.pythonhosted.org/packages/f7/5a/4b675941a73bc46959f24b3f5a68c246422278022a0e121f9c3f226a7a2b/tensorstore-0.1.76-cp311-cp311-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:daf1c7fb71cd07bfdf37ae4f297c0a6895b011562f4050f5c8f52f5753cc24cc", size = 17548043 }, - { url = "https://files.pythonhosted.org/packages/96/b9/8e306cbccb12ce4c241ac69fb98a4fc1bad5fc0311112f579bc24bee9c42/tensorstore-0.1.76-cp311-cp311-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:b24f21bbd4830822422e984bc023a37ce7db08be02138c01c96870e62d041e7f", size = 18925296 }, - { url = "https://files.pythonhosted.org/packages/9c/48/b542e9a4fa6f82b00e9a7c41c30003c195178fa78f835ea205b346a45baf/tensorstore-0.1.76-cp311-cp311-win_amd64.whl", hash = "sha256:36ba59d99d8279802793405fb8615803ea0e136ad439e6fe0ab3c3d7df22179d", size = 12609617 }, - { url = "https://files.pythonhosted.org/packages/09/37/f2254b4ae1dabd95e258fa3eb4783ac4db4261bb8c90ff9bfe15549d1238/tensorstore-0.1.76-cp312-cp312-macosx_10_14_x86_64.whl", hash = "sha256:b68450983ccad9e7774e81b2fa37daef1b72c774fd939d9eb4065d6aa70e666a", size = 15712650 }, - { url = "https://files.pythonhosted.org/packages/93/3c/1cae56cbbe9610ff48cb2d7c0921a4d4c333a0540918e3b2db08b521c5f6/tensorstore-0.1.76-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:6b7a3856f884279e40f90bad87d0da70869879e124835e650c6b16c80f64fbc4", size = 13624138 }, - { url = "https://files.pythonhosted.org/packages/ba/d2/b92d34a896f608a59dc76c290d4ec9f7d0264a02e4d74864987a6adbd3c9/tensorstore-0.1.76-cp312-cp312-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:8709a98ae0b453eb23525c07372c2be1f6bbd978bba53319f26a1f2a83a77c2a", size = 17538270 }, - { url = "https://files.pythonhosted.org/packages/21/66/142b803541552b02a2fa033b1f48bcb50e1d2df6ac10131aab1857c5141d/tensorstore-0.1.76-cp312-cp312-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:267edea8f1596f2bd67017ff97b7b350bf3f95ff84947a8babadc5e17ca53663", size = 18910782 }, - { url = "https://files.pythonhosted.org/packages/5a/3e/c264cf1435c04fb998a1f30dd1f066deb370b841412f89e1cb36d37ee4fc/tensorstore-0.1.76-cp312-cp312-win_amd64.whl", hash = "sha256:f66ac63d0c63c3336ac4dc61f1f97b6afe8b512e586ddfdbc91f19175787f321", size = 12611059 }, - { url = "https://files.pythonhosted.org/packages/5f/66/1e3b819e1de98b048dad7843f3a814c5e739ead57f511dafb6aa0748f04a/tensorstore-0.1.76-cp313-cp313-macosx_10_14_x86_64.whl", hash = "sha256:a471994b156daa3cadb0e4968e29202fa2e8c7ddcd28d825499bb5637caa0983", size = 15713110 }, - { url = "https://files.pythonhosted.org/packages/58/d3/226344e8822c5e02af929c89bd61964e08980253cda15286a201850eb3b1/tensorstore-0.1.76-cp313-cp313-macosx_11_0_arm64.whl", hash = "sha256:98175dc64935b49467cb7664a431b9a06e9df9b5cab94f9a1fdb24a30b2d69d3", size = 13624514 }, - { url = "https://files.pythonhosted.org/packages/94/9f/2b267c520dbbcf0a5ebc7a3c0a6cf852a445e22c8ea8b0f7450bf6b98783/tensorstore-0.1.76-cp313-cp313-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:c9e30577f1197ea3573102912482dced95e4c6ff72087ffeb99b5d8b496bf81a", size = 17539304 }, - { url = "https://files.pythonhosted.org/packages/1d/9a/9dcc01c8f87047b09602ea16379233b8a308d1d83d5432bf8bc89163ca3e/tensorstore-0.1.76-cp313-cp313-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:20782f833bfa3c59dd3787f657388054c54ee0ab48dad181b360e3e5e81e4c4b", size = 18911982 }, - { url = "https://files.pythonhosted.org/packages/10/45/43d387027b3eac9f09de8bb736b1b432de287fbd807716877fe5fbaeee56/tensorstore-0.1.76-cp313-cp313-win_amd64.whl", hash = "sha256:e84fc11b36fcd55cfd1c5dfc60de9d54d7d95c3de074f4d854914067e82a6740", size = 12610851 }, + { name = "numpy", version = "2.3.3", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version >= '3.11'" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/48/4c/7db3b759e38e14c5eafeada78705f347f42a9ba132914a2ccad60bce5605/tensorstore-0.1.77.tar.gz", hash = "sha256:5ae62828503cea71e64d808bda959877ed75ea23f1adffca903635b842acc1e8", size = 6880812, upload-time = "2025-09-20T00:19:02.497Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/65/fd/46b2a2d0b9c428eaebaed179f8cf68a9bcffb96e78a9987c9d4a73a5d834/tensorstore-0.1.77-cp310-cp310-macosx_10_14_x86_64.whl", hash = "sha256:985655addf29ee6543fd84cb7c521967c2ed531fd7dbbeb69bd885abacee77f6", size = 15710763, upload-time = "2025-09-20T00:18:09.964Z" }, + { url = "https://files.pythonhosted.org/packages/0d/eb/06d2f59f58d40dd69c100baad15a9f28e884e3515afb68fdc2893a779fb9/tensorstore-0.1.77-cp310-cp310-macosx_11_0_arm64.whl", hash = "sha256:a936b74887be52de98e3bb8d18d46e8768208155e616d615f1237880224c4fd7", size = 13771531, upload-time = "2025-09-20T00:18:12.811Z" }, + { url = "https://files.pythonhosted.org/packages/f5/1a/5fca4445ac760b1341f7ebb6f68d863263ce48e068b63e74d6a05dea9ef2/tensorstore-0.1.77-cp310-cp310-manylinux_2_27_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:8d41a022e7531325ee0d173ce26da17df7dbea5954bd868bb1164712434f057b", size = 17710228, upload-time = "2025-09-20T00:18:15.49Z" }, + { url = "https://files.pythonhosted.org/packages/4f/a0/1ad099b963119c40598b6c8578f331f9c7b70aa7b64331aaf9dd2d9e87a5/tensorstore-0.1.77-cp310-cp310-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:82e11e3981b1946da5bedda2b58d6f45bec2f7265bf64bc4c58d26fd5ee5325a", size = 19548584, upload-time = "2025-09-20T00:18:18.025Z" }, + { url = "https://files.pythonhosted.org/packages/13/72/5784c3346b87422c4c6f3c182ce74ab8735e8a72af11b3510c9fdd825455/tensorstore-0.1.77-cp310-cp310-win_amd64.whl", hash = "sha256:88213e3ab2f0a4a3a5a46edfca6e74dc0162b7e5e76d517a0a5554fe2f6951d7", size = 12705119, upload-time = "2025-09-20T00:18:20.313Z" }, + { url = "https://files.pythonhosted.org/packages/bd/0e/5104cec25693d345e769e14426daff368409b814f7a9a49ceda4edf0976b/tensorstore-0.1.77-cp311-cp311-macosx_10_14_x86_64.whl", hash = "sha256:5c543184acb1282fa905513284d836c62faaaf4919ef6245ddc5f0a4800866f9", size = 15712049, upload-time = "2025-09-20T00:18:22.908Z" }, + { url = "https://files.pythonhosted.org/packages/df/d6/d5342046640ad4ab2e9c4f34654d8fab0f5600cf77c7dca3b1aee2cbd70e/tensorstore-0.1.77-cp311-cp311-macosx_11_0_arm64.whl", hash = "sha256:8c08c03f261bb6fe34e41fedc483f7f8c6935ba02c36ae345d7b45572fbda21e", size = 13773861, upload-time = "2025-09-20T00:18:25.51Z" }, + { url = "https://files.pythonhosted.org/packages/97/85/e33575dca0cb2812aa19ae0e1b564b213ca21356b6c489ab30e71c69b83f/tensorstore-0.1.77-cp311-cp311-manylinux_2_27_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:0848c0a004cb4e8443b3bee4238d51dfadbac55b834e939336bf9b86923d73f5", size = 17709679, upload-time = "2025-09-20T00:18:28.402Z" }, + { url = "https://files.pythonhosted.org/packages/fc/f1/bf93635290aa491cfd5e0e0c1d1088f6050300fd4acd4642d279aa652f72/tensorstore-0.1.77-cp311-cp311-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:9fb217c1f2b03b3dec8d151d4363207cf8ca9d65f7956b777aae6493920e2d48", size = 19549034, upload-time = "2025-09-20T00:18:31.45Z" }, + { url = "https://files.pythonhosted.org/packages/50/b7/0e4a420e3e68497457c36dc6d8e5c4733e8605de792b0a82ad2281f7d905/tensorstore-0.1.77-cp311-cp311-win_amd64.whl", hash = "sha256:16110ba5844f562a98fef5b15698d51a254e76ccc27fa3d4eae4edbe46d9f68d", size = 12705933, upload-time = "2025-09-20T00:18:34.344Z" }, + { url = "https://files.pythonhosted.org/packages/a8/d4/1545f47b496c3eff088e500f3396de6185e33deb4170ac70afd42a98da17/tensorstore-0.1.77-cp312-cp312-macosx_10_14_x86_64.whl", hash = "sha256:90417e8c499d3aac0359bf990abad1b60892cd5c868f288115d546aa5dbe7ace", size = 15727039, upload-time = "2025-09-20T00:18:36.589Z" }, + { url = "https://files.pythonhosted.org/packages/e0/94/cf104fde7ffd1e4726e48ab15a9a587e68b741a9ca366739041f5702c794/tensorstore-0.1.77-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:a654468acb816c0e8cf0a1443eb0956e76f4e1a2a4fe75ab06ea504161190755", size = 13781960, upload-time = "2025-09-20T00:18:39.504Z" }, + { url = "https://files.pythonhosted.org/packages/16/ea/0fd3ec6d9d1e0a00aae5174e9c44ea00bfd06208f820262425c6b120e76f/tensorstore-0.1.77-cp312-cp312-manylinux_2_27_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:b8e68accbcfbc68900367028971066adb927d0b302eba387271957545d0c0ec1", size = 17701149, upload-time = "2025-09-20T00:18:41.94Z" }, + { url = "https://files.pythonhosted.org/packages/19/31/94bb41faf66eaeead8f1930b7836a3d01e72b73f4346f602f31a9324b347/tensorstore-0.1.77-cp312-cp312-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:7ce520277b32397cfd0bc812751cc9c414d12488ecbb33efe9fc50979b73a80f", size = 19536583, upload-time = "2025-09-20T00:18:44.836Z" }, + { url = "https://files.pythonhosted.org/packages/5a/02/1931b4f854ec275361cba62b7af76064153570f732dc0ea02b220077ba57/tensorstore-0.1.77-cp312-cp312-win_amd64.whl", hash = "sha256:e55bd02c0a1163f4565f98c8b41837b72ffd0c27e9f8a4d3dcc7018ce17a2c1a", size = 12710352, upload-time = "2025-09-20T00:18:47.737Z" }, + { url = "https://files.pythonhosted.org/packages/44/c2/e0f185bd75e9881c0c35df57dd89c528ef750f8f4ab7fb639ffd415e7589/tensorstore-0.1.77-cp313-cp313-macosx_10_14_x86_64.whl", hash = "sha256:9b4e21b09acd01bde8660939d1b2f52a9179571e1bdfa1e8d2cc88b1cadf5d78", size = 15726851, upload-time = "2025-09-20T00:18:50.117Z" }, + { url = "https://files.pythonhosted.org/packages/ce/94/42703000135524901a120fc974c1b487309d1e3264071bc117a57f38316d/tensorstore-0.1.77-cp313-cp313-macosx_11_0_arm64.whl", hash = "sha256:f383d8d1f7fd0babd2c03851ab57738782f35f604d29a7cf463f9875e3584613", size = 13782161, upload-time = "2025-09-20T00:18:52.529Z" }, + { url = "https://files.pythonhosted.org/packages/43/c9/36611dcb2e5007d1b7405f44068d1c2839f6233fc0c4bdead56a8ec24c31/tensorstore-0.1.77-cp313-cp313-manylinux_2_27_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:351f0f73ed2b57a561b0ffd32ab9188d65adc0a85916b23f8355a5df50dbac2e", size = 17701404, upload-time = "2025-09-20T00:18:54.929Z" }, + { url = "https://files.pythonhosted.org/packages/c1/42/598560fe23d04c0ae160b8f9754c3887893e401305fd50dd7d70e08c4b0b/tensorstore-0.1.77-cp313-cp313-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:ed487f313af8e07cc3caa372120621f4029778f9e5a1c026efb915dabea555a2", size = 19537201, upload-time = "2025-09-20T00:18:57.504Z" }, + { url = "https://files.pythonhosted.org/packages/22/5d/bf02faa525ed54b37d1f6d4a1463e9986014ccf26da3cef77fe1efb8c18b/tensorstore-0.1.77-cp313-cp313-win_amd64.whl", hash = "sha256:416a5f076260e852afeaf7d30e567b08a28dd3af913d38a27f112f599e53313a", size = 12710186, upload-time = "2025-09-20T00:19:00.199Z" }, ] [[package]] name = "termcolor" version = "3.1.0" source = { registry = "https://pypi.org/simple" } -sdist = { url = "https://files.pythonhosted.org/packages/ca/6c/3d75c196ac07ac8749600b60b03f4f6094d54e132c4d94ebac6ee0e0add0/termcolor-3.1.0.tar.gz", hash = "sha256:6a6dd7fbee581909eeec6a756cff1d7f7c376063b14e4a298dc4980309e55970", size = 14324 } +sdist = { url = "https://files.pythonhosted.org/packages/ca/6c/3d75c196ac07ac8749600b60b03f4f6094d54e132c4d94ebac6ee0e0add0/termcolor-3.1.0.tar.gz", hash = "sha256:6a6dd7fbee581909eeec6a756cff1d7f7c376063b14e4a298dc4980309e55970", size = 14324, upload-time = "2025-04-30T11:37:53.791Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/4f/bd/de8d508070629b6d84a30d01d57e4a65c69aa7f5abe7560b8fad3b50ea59/termcolor-3.1.0-py3-none-any.whl", hash = "sha256:591dd26b5c2ce03b9e43f391264626557873ce1d379019786f99b0c2bee140aa", size = 7684 }, + { url = "https://files.pythonhosted.org/packages/4f/bd/de8d508070629b6d84a30d01d57e4a65c69aa7f5abe7560b8fad3b50ea59/termcolor-3.1.0-py3-none-any.whl", hash = "sha256:591dd26b5c2ce03b9e43f391264626557873ce1d379019786f99b0c2bee140aa", size = 7684, upload-time = "2025-04-30T11:37:52.382Z" }, ] [[package]] name = "tomli" version = "2.2.1" source = { registry = "https://pypi.org/simple" } -sdist = { url = "https://files.pythonhosted.org/packages/18/87/302344fed471e44a87289cf4967697d07e532f2421fdaf868a303cbae4ff/tomli-2.2.1.tar.gz", hash = "sha256:cd45e1dc79c835ce60f7404ec8119f2eb06d38b1deba146f07ced3bbc44505ff", size = 17175 } -wheels = [ - { url = "https://files.pythonhosted.org/packages/43/ca/75707e6efa2b37c77dadb324ae7d9571cb424e61ea73fad7c56c2d14527f/tomli-2.2.1-cp311-cp311-macosx_10_9_x86_64.whl", hash = "sha256:678e4fa69e4575eb77d103de3df8a895e1591b48e740211bd1067378c69e8249", size = 131077 }, - { url = "https://files.pythonhosted.org/packages/c7/16/51ae563a8615d472fdbffc43a3f3d46588c264ac4f024f63f01283becfbb/tomli-2.2.1-cp311-cp311-macosx_11_0_arm64.whl", hash = "sha256:023aa114dd824ade0100497eb2318602af309e5a55595f76b626d6d9f3b7b0a6", size = 123429 }, - { url = "https://files.pythonhosted.org/packages/f1/dd/4f6cd1e7b160041db83c694abc78e100473c15d54620083dbd5aae7b990e/tomli-2.2.1-cp311-cp311-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:ece47d672db52ac607a3d9599a9d48dcb2f2f735c6c2d1f34130085bb12b112a", size = 226067 }, - { url = "https://files.pythonhosted.org/packages/a9/6b/c54ede5dc70d648cc6361eaf429304b02f2871a345bbdd51e993d6cdf550/tomli-2.2.1-cp311-cp311-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:6972ca9c9cc9f0acaa56a8ca1ff51e7af152a9f87fb64623e31d5c83700080ee", size = 236030 }, - { url = "https://files.pythonhosted.org/packages/1f/47/999514fa49cfaf7a92c805a86c3c43f4215621855d151b61c602abb38091/tomli-2.2.1-cp311-cp311-manylinux_2_5_i686.manylinux1_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:c954d2250168d28797dd4e3ac5cf812a406cd5a92674ee4c8f123c889786aa8e", size = 240898 }, - { url = "https://files.pythonhosted.org/packages/73/41/0a01279a7ae09ee1573b423318e7934674ce06eb33f50936655071d81a24/tomli-2.2.1-cp311-cp311-musllinux_1_2_aarch64.whl", hash = "sha256:8dd28b3e155b80f4d54beb40a441d366adcfe740969820caf156c019fb5c7ec4", size = 229894 }, - { url = "https://files.pythonhosted.org/packages/55/18/5d8bc5b0a0362311ce4d18830a5d28943667599a60d20118074ea1b01bb7/tomli-2.2.1-cp311-cp311-musllinux_1_2_i686.whl", hash = "sha256:e59e304978767a54663af13c07b3d1af22ddee3bb2fb0618ca1593e4f593a106", size = 245319 }, - { url = "https://files.pythonhosted.org/packages/92/a3/7ade0576d17f3cdf5ff44d61390d4b3febb8a9fc2b480c75c47ea048c646/tomli-2.2.1-cp311-cp311-musllinux_1_2_x86_64.whl", hash = "sha256:33580bccab0338d00994d7f16f4c4ec25b776af3ffaac1ed74e0b3fc95e885a8", size = 238273 }, - { url = "https://files.pythonhosted.org/packages/72/6f/fa64ef058ac1446a1e51110c375339b3ec6be245af9d14c87c4a6412dd32/tomli-2.2.1-cp311-cp311-win32.whl", hash = "sha256:465af0e0875402f1d226519c9904f37254b3045fc5084697cefb9bdde1ff99ff", size = 98310 }, - { url = "https://files.pythonhosted.org/packages/6a/1c/4a2dcde4a51b81be3530565e92eda625d94dafb46dbeb15069df4caffc34/tomli-2.2.1-cp311-cp311-win_amd64.whl", hash = "sha256:2d0f2fdd22b02c6d81637a3c95f8cd77f995846af7414c5c4b8d0545afa1bc4b", size = 108309 }, - { url = "https://files.pythonhosted.org/packages/52/e1/f8af4c2fcde17500422858155aeb0d7e93477a0d59a98e56cbfe75070fd0/tomli-2.2.1-cp312-cp312-macosx_10_13_x86_64.whl", hash = "sha256:4a8f6e44de52d5e6c657c9fe83b562f5f4256d8ebbfe4ff922c495620a7f6cea", size = 132762 }, - { url = "https://files.pythonhosted.org/packages/03/b8/152c68bb84fc00396b83e7bbddd5ec0bd3dd409db4195e2a9b3e398ad2e3/tomli-2.2.1-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:8d57ca8095a641b8237d5b079147646153d22552f1c637fd3ba7f4b0b29167a8", size = 123453 }, - { url = "https://files.pythonhosted.org/packages/c8/d6/fc9267af9166f79ac528ff7e8c55c8181ded34eb4b0e93daa767b8841573/tomli-2.2.1-cp312-cp312-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:4e340144ad7ae1533cb897d406382b4b6fede8890a03738ff1683af800d54192", size = 233486 }, - { url = "https://files.pythonhosted.org/packages/5c/51/51c3f2884d7bab89af25f678447ea7d297b53b5a3b5730a7cb2ef6069f07/tomli-2.2.1-cp312-cp312-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:db2b95f9de79181805df90bedc5a5ab4c165e6ec3fe99f970d0e302f384ad222", size = 242349 }, - { url = "https://files.pythonhosted.org/packages/ab/df/bfa89627d13a5cc22402e441e8a931ef2108403db390ff3345c05253935e/tomli-2.2.1-cp312-cp312-manylinux_2_5_i686.manylinux1_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:40741994320b232529c802f8bc86da4e1aa9f413db394617b9a256ae0f9a7f77", size = 252159 }, - { url = "https://files.pythonhosted.org/packages/9e/6e/fa2b916dced65763a5168c6ccb91066f7639bdc88b48adda990db10c8c0b/tomli-2.2.1-cp312-cp312-musllinux_1_2_aarch64.whl", hash = "sha256:400e720fe168c0f8521520190686ef8ef033fb19fc493da09779e592861b78c6", size = 237243 }, - { url = "https://files.pythonhosted.org/packages/b4/04/885d3b1f650e1153cbb93a6a9782c58a972b94ea4483ae4ac5cedd5e4a09/tomli-2.2.1-cp312-cp312-musllinux_1_2_i686.whl", hash = "sha256:02abe224de6ae62c19f090f68da4e27b10af2b93213d36cf44e6e1c5abd19fdd", size = 259645 }, - { url = "https://files.pythonhosted.org/packages/9c/de/6b432d66e986e501586da298e28ebeefd3edc2c780f3ad73d22566034239/tomli-2.2.1-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:b82ebccc8c8a36f2094e969560a1b836758481f3dc360ce9a3277c65f374285e", size = 244584 }, - { url = "https://files.pythonhosted.org/packages/1c/9a/47c0449b98e6e7d1be6cbac02f93dd79003234ddc4aaab6ba07a9a7482e2/tomli-2.2.1-cp312-cp312-win32.whl", hash = "sha256:889f80ef92701b9dbb224e49ec87c645ce5df3fa2cc548664eb8a25e03127a98", size = 98875 }, - { url = "https://files.pythonhosted.org/packages/ef/60/9b9638f081c6f1261e2688bd487625cd1e660d0a85bd469e91d8db969734/tomli-2.2.1-cp312-cp312-win_amd64.whl", hash = "sha256:7fc04e92e1d624a4a63c76474610238576942d6b8950a2d7f908a340494e67e4", size = 109418 }, - { url = "https://files.pythonhosted.org/packages/04/90/2ee5f2e0362cb8a0b6499dc44f4d7d48f8fff06d28ba46e6f1eaa61a1388/tomli-2.2.1-cp313-cp313-macosx_10_13_x86_64.whl", hash = "sha256:f4039b9cbc3048b2416cc57ab3bda989a6fcf9b36cf8937f01a6e731b64f80d7", size = 132708 }, - { url = "https://files.pythonhosted.org/packages/c0/ec/46b4108816de6b385141f082ba99e315501ccd0a2ea23db4a100dd3990ea/tomli-2.2.1-cp313-cp313-macosx_11_0_arm64.whl", hash = "sha256:286f0ca2ffeeb5b9bd4fcc8d6c330534323ec51b2f52da063b11c502da16f30c", size = 123582 }, - { url = "https://files.pythonhosted.org/packages/a0/bd/b470466d0137b37b68d24556c38a0cc819e8febe392d5b199dcd7f578365/tomli-2.2.1-cp313-cp313-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:a92ef1a44547e894e2a17d24e7557a5e85a9e1d0048b0b5e7541f76c5032cb13", size = 232543 }, - { url = "https://files.pythonhosted.org/packages/d9/e5/82e80ff3b751373f7cead2815bcbe2d51c895b3c990686741a8e56ec42ab/tomli-2.2.1-cp313-cp313-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:9316dc65bed1684c9a98ee68759ceaed29d229e985297003e494aa825ebb0281", size = 241691 }, - { url = "https://files.pythonhosted.org/packages/05/7e/2a110bc2713557d6a1bfb06af23dd01e7dde52b6ee7dadc589868f9abfac/tomli-2.2.1-cp313-cp313-manylinux_2_5_i686.manylinux1_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:e85e99945e688e32d5a35c1ff38ed0b3f41f43fad8df0bdf79f72b2ba7bc5272", size = 251170 }, - { url = "https://files.pythonhosted.org/packages/64/7b/22d713946efe00e0adbcdfd6d1aa119ae03fd0b60ebed51ebb3fa9f5a2e5/tomli-2.2.1-cp313-cp313-musllinux_1_2_aarch64.whl", hash = "sha256:ac065718db92ca818f8d6141b5f66369833d4a80a9d74435a268c52bdfa73140", size = 236530 }, - { url = "https://files.pythonhosted.org/packages/38/31/3a76f67da4b0cf37b742ca76beaf819dca0ebef26d78fc794a576e08accf/tomli-2.2.1-cp313-cp313-musllinux_1_2_i686.whl", hash = "sha256:d920f33822747519673ee656a4b6ac33e382eca9d331c87770faa3eef562aeb2", size = 258666 }, - { url = "https://files.pythonhosted.org/packages/07/10/5af1293da642aded87e8a988753945d0cf7e00a9452d3911dd3bb354c9e2/tomli-2.2.1-cp313-cp313-musllinux_1_2_x86_64.whl", hash = "sha256:a198f10c4d1b1375d7687bc25294306e551bf1abfa4eace6650070a5c1ae2744", size = 243954 }, - { url = "https://files.pythonhosted.org/packages/5b/b9/1ed31d167be802da0fc95020d04cd27b7d7065cc6fbefdd2f9186f60d7bd/tomli-2.2.1-cp313-cp313-win32.whl", hash = "sha256:d3f5614314d758649ab2ab3a62d4f2004c825922f9e370b29416484086b264ec", size = 98724 }, - { url = "https://files.pythonhosted.org/packages/c7/32/b0963458706accd9afcfeb867c0f9175a741bf7b19cd424230714d722198/tomli-2.2.1-cp313-cp313-win_amd64.whl", hash = "sha256:a38aa0308e754b0e3c67e344754dff64999ff9b513e691d0e786265c93583c69", size = 109383 }, - { url = "https://files.pythonhosted.org/packages/6e/c2/61d3e0f47e2b74ef40a68b9e6ad5984f6241a942f7cd3bbfbdbd03861ea9/tomli-2.2.1-py3-none-any.whl", hash = "sha256:cb55c73c5f4408779d0cf3eef9f762b9c9f147a77de7b258bef0a5628adc85cc", size = 14257 }, +sdist = { url = "https://files.pythonhosted.org/packages/18/87/302344fed471e44a87289cf4967697d07e532f2421fdaf868a303cbae4ff/tomli-2.2.1.tar.gz", hash = "sha256:cd45e1dc79c835ce60f7404ec8119f2eb06d38b1deba146f07ced3bbc44505ff", size = 17175, upload-time = "2024-11-27T22:38:36.873Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/43/ca/75707e6efa2b37c77dadb324ae7d9571cb424e61ea73fad7c56c2d14527f/tomli-2.2.1-cp311-cp311-macosx_10_9_x86_64.whl", hash = "sha256:678e4fa69e4575eb77d103de3df8a895e1591b48e740211bd1067378c69e8249", size = 131077, upload-time = "2024-11-27T22:37:54.956Z" }, + { url = "https://files.pythonhosted.org/packages/c7/16/51ae563a8615d472fdbffc43a3f3d46588c264ac4f024f63f01283becfbb/tomli-2.2.1-cp311-cp311-macosx_11_0_arm64.whl", hash = "sha256:023aa114dd824ade0100497eb2318602af309e5a55595f76b626d6d9f3b7b0a6", size = 123429, upload-time = "2024-11-27T22:37:56.698Z" }, + { url = "https://files.pythonhosted.org/packages/f1/dd/4f6cd1e7b160041db83c694abc78e100473c15d54620083dbd5aae7b990e/tomli-2.2.1-cp311-cp311-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:ece47d672db52ac607a3d9599a9d48dcb2f2f735c6c2d1f34130085bb12b112a", size = 226067, upload-time = "2024-11-27T22:37:57.63Z" }, + { url = "https://files.pythonhosted.org/packages/a9/6b/c54ede5dc70d648cc6361eaf429304b02f2871a345bbdd51e993d6cdf550/tomli-2.2.1-cp311-cp311-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:6972ca9c9cc9f0acaa56a8ca1ff51e7af152a9f87fb64623e31d5c83700080ee", size = 236030, upload-time = "2024-11-27T22:37:59.344Z" }, + { url = "https://files.pythonhosted.org/packages/1f/47/999514fa49cfaf7a92c805a86c3c43f4215621855d151b61c602abb38091/tomli-2.2.1-cp311-cp311-manylinux_2_5_i686.manylinux1_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:c954d2250168d28797dd4e3ac5cf812a406cd5a92674ee4c8f123c889786aa8e", size = 240898, upload-time = "2024-11-27T22:38:00.429Z" }, + { url = "https://files.pythonhosted.org/packages/73/41/0a01279a7ae09ee1573b423318e7934674ce06eb33f50936655071d81a24/tomli-2.2.1-cp311-cp311-musllinux_1_2_aarch64.whl", hash = "sha256:8dd28b3e155b80f4d54beb40a441d366adcfe740969820caf156c019fb5c7ec4", size = 229894, upload-time = "2024-11-27T22:38:02.094Z" }, + { url = "https://files.pythonhosted.org/packages/55/18/5d8bc5b0a0362311ce4d18830a5d28943667599a60d20118074ea1b01bb7/tomli-2.2.1-cp311-cp311-musllinux_1_2_i686.whl", hash = "sha256:e59e304978767a54663af13c07b3d1af22ddee3bb2fb0618ca1593e4f593a106", size = 245319, upload-time = "2024-11-27T22:38:03.206Z" }, + { url = "https://files.pythonhosted.org/packages/92/a3/7ade0576d17f3cdf5ff44d61390d4b3febb8a9fc2b480c75c47ea048c646/tomli-2.2.1-cp311-cp311-musllinux_1_2_x86_64.whl", hash = "sha256:33580bccab0338d00994d7f16f4c4ec25b776af3ffaac1ed74e0b3fc95e885a8", size = 238273, upload-time = "2024-11-27T22:38:04.217Z" }, + { url = "https://files.pythonhosted.org/packages/72/6f/fa64ef058ac1446a1e51110c375339b3ec6be245af9d14c87c4a6412dd32/tomli-2.2.1-cp311-cp311-win32.whl", hash = "sha256:465af0e0875402f1d226519c9904f37254b3045fc5084697cefb9bdde1ff99ff", size = 98310, upload-time = "2024-11-27T22:38:05.908Z" }, + { url = "https://files.pythonhosted.org/packages/6a/1c/4a2dcde4a51b81be3530565e92eda625d94dafb46dbeb15069df4caffc34/tomli-2.2.1-cp311-cp311-win_amd64.whl", hash = "sha256:2d0f2fdd22b02c6d81637a3c95f8cd77f995846af7414c5c4b8d0545afa1bc4b", size = 108309, upload-time = "2024-11-27T22:38:06.812Z" }, + { url = "https://files.pythonhosted.org/packages/52/e1/f8af4c2fcde17500422858155aeb0d7e93477a0d59a98e56cbfe75070fd0/tomli-2.2.1-cp312-cp312-macosx_10_13_x86_64.whl", hash = "sha256:4a8f6e44de52d5e6c657c9fe83b562f5f4256d8ebbfe4ff922c495620a7f6cea", size = 132762, upload-time = "2024-11-27T22:38:07.731Z" }, + { url = "https://files.pythonhosted.org/packages/03/b8/152c68bb84fc00396b83e7bbddd5ec0bd3dd409db4195e2a9b3e398ad2e3/tomli-2.2.1-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:8d57ca8095a641b8237d5b079147646153d22552f1c637fd3ba7f4b0b29167a8", size = 123453, upload-time = "2024-11-27T22:38:09.384Z" }, + { url = "https://files.pythonhosted.org/packages/c8/d6/fc9267af9166f79ac528ff7e8c55c8181ded34eb4b0e93daa767b8841573/tomli-2.2.1-cp312-cp312-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:4e340144ad7ae1533cb897d406382b4b6fede8890a03738ff1683af800d54192", size = 233486, upload-time = "2024-11-27T22:38:10.329Z" }, + { url = "https://files.pythonhosted.org/packages/5c/51/51c3f2884d7bab89af25f678447ea7d297b53b5a3b5730a7cb2ef6069f07/tomli-2.2.1-cp312-cp312-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:db2b95f9de79181805df90bedc5a5ab4c165e6ec3fe99f970d0e302f384ad222", size = 242349, upload-time = "2024-11-27T22:38:11.443Z" }, + { url = "https://files.pythonhosted.org/packages/ab/df/bfa89627d13a5cc22402e441e8a931ef2108403db390ff3345c05253935e/tomli-2.2.1-cp312-cp312-manylinux_2_5_i686.manylinux1_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:40741994320b232529c802f8bc86da4e1aa9f413db394617b9a256ae0f9a7f77", size = 252159, upload-time = "2024-11-27T22:38:13.099Z" }, + { url = "https://files.pythonhosted.org/packages/9e/6e/fa2b916dced65763a5168c6ccb91066f7639bdc88b48adda990db10c8c0b/tomli-2.2.1-cp312-cp312-musllinux_1_2_aarch64.whl", hash = "sha256:400e720fe168c0f8521520190686ef8ef033fb19fc493da09779e592861b78c6", size = 237243, upload-time = "2024-11-27T22:38:14.766Z" }, + { url = "https://files.pythonhosted.org/packages/b4/04/885d3b1f650e1153cbb93a6a9782c58a972b94ea4483ae4ac5cedd5e4a09/tomli-2.2.1-cp312-cp312-musllinux_1_2_i686.whl", hash = "sha256:02abe224de6ae62c19f090f68da4e27b10af2b93213d36cf44e6e1c5abd19fdd", size = 259645, upload-time = "2024-11-27T22:38:15.843Z" }, + { url = "https://files.pythonhosted.org/packages/9c/de/6b432d66e986e501586da298e28ebeefd3edc2c780f3ad73d22566034239/tomli-2.2.1-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:b82ebccc8c8a36f2094e969560a1b836758481f3dc360ce9a3277c65f374285e", size = 244584, upload-time = "2024-11-27T22:38:17.645Z" }, + { url = "https://files.pythonhosted.org/packages/1c/9a/47c0449b98e6e7d1be6cbac02f93dd79003234ddc4aaab6ba07a9a7482e2/tomli-2.2.1-cp312-cp312-win32.whl", hash = "sha256:889f80ef92701b9dbb224e49ec87c645ce5df3fa2cc548664eb8a25e03127a98", size = 98875, upload-time = "2024-11-27T22:38:19.159Z" }, + { url = "https://files.pythonhosted.org/packages/ef/60/9b9638f081c6f1261e2688bd487625cd1e660d0a85bd469e91d8db969734/tomli-2.2.1-cp312-cp312-win_amd64.whl", hash = "sha256:7fc04e92e1d624a4a63c76474610238576942d6b8950a2d7f908a340494e67e4", size = 109418, upload-time = "2024-11-27T22:38:20.064Z" }, + { url = "https://files.pythonhosted.org/packages/04/90/2ee5f2e0362cb8a0b6499dc44f4d7d48f8fff06d28ba46e6f1eaa61a1388/tomli-2.2.1-cp313-cp313-macosx_10_13_x86_64.whl", hash = "sha256:f4039b9cbc3048b2416cc57ab3bda989a6fcf9b36cf8937f01a6e731b64f80d7", size = 132708, upload-time = "2024-11-27T22:38:21.659Z" }, + { url = "https://files.pythonhosted.org/packages/c0/ec/46b4108816de6b385141f082ba99e315501ccd0a2ea23db4a100dd3990ea/tomli-2.2.1-cp313-cp313-macosx_11_0_arm64.whl", hash = "sha256:286f0ca2ffeeb5b9bd4fcc8d6c330534323ec51b2f52da063b11c502da16f30c", size = 123582, upload-time = "2024-11-27T22:38:22.693Z" }, + { url = "https://files.pythonhosted.org/packages/a0/bd/b470466d0137b37b68d24556c38a0cc819e8febe392d5b199dcd7f578365/tomli-2.2.1-cp313-cp313-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:a92ef1a44547e894e2a17d24e7557a5e85a9e1d0048b0b5e7541f76c5032cb13", size = 232543, upload-time = "2024-11-27T22:38:24.367Z" }, + { url = "https://files.pythonhosted.org/packages/d9/e5/82e80ff3b751373f7cead2815bcbe2d51c895b3c990686741a8e56ec42ab/tomli-2.2.1-cp313-cp313-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:9316dc65bed1684c9a98ee68759ceaed29d229e985297003e494aa825ebb0281", size = 241691, upload-time = "2024-11-27T22:38:26.081Z" }, + { url = "https://files.pythonhosted.org/packages/05/7e/2a110bc2713557d6a1bfb06af23dd01e7dde52b6ee7dadc589868f9abfac/tomli-2.2.1-cp313-cp313-manylinux_2_5_i686.manylinux1_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:e85e99945e688e32d5a35c1ff38ed0b3f41f43fad8df0bdf79f72b2ba7bc5272", size = 251170, upload-time = "2024-11-27T22:38:27.921Z" }, + { url = "https://files.pythonhosted.org/packages/64/7b/22d713946efe00e0adbcdfd6d1aa119ae03fd0b60ebed51ebb3fa9f5a2e5/tomli-2.2.1-cp313-cp313-musllinux_1_2_aarch64.whl", hash = "sha256:ac065718db92ca818f8d6141b5f66369833d4a80a9d74435a268c52bdfa73140", size = 236530, upload-time = "2024-11-27T22:38:29.591Z" }, + { url = "https://files.pythonhosted.org/packages/38/31/3a76f67da4b0cf37b742ca76beaf819dca0ebef26d78fc794a576e08accf/tomli-2.2.1-cp313-cp313-musllinux_1_2_i686.whl", hash = "sha256:d920f33822747519673ee656a4b6ac33e382eca9d331c87770faa3eef562aeb2", size = 258666, upload-time = "2024-11-27T22:38:30.639Z" }, + { url = "https://files.pythonhosted.org/packages/07/10/5af1293da642aded87e8a988753945d0cf7e00a9452d3911dd3bb354c9e2/tomli-2.2.1-cp313-cp313-musllinux_1_2_x86_64.whl", hash = "sha256:a198f10c4d1b1375d7687bc25294306e551bf1abfa4eace6650070a5c1ae2744", size = 243954, upload-time = "2024-11-27T22:38:31.702Z" }, + { url = "https://files.pythonhosted.org/packages/5b/b9/1ed31d167be802da0fc95020d04cd27b7d7065cc6fbefdd2f9186f60d7bd/tomli-2.2.1-cp313-cp313-win32.whl", hash = "sha256:d3f5614314d758649ab2ab3a62d4f2004c825922f9e370b29416484086b264ec", size = 98724, upload-time = "2024-11-27T22:38:32.837Z" }, + { url = "https://files.pythonhosted.org/packages/c7/32/b0963458706accd9afcfeb867c0f9175a741bf7b19cd424230714d722198/tomli-2.2.1-cp313-cp313-win_amd64.whl", hash = "sha256:a38aa0308e754b0e3c67e344754dff64999ff9b513e691d0e786265c93583c69", size = 109383, upload-time = "2024-11-27T22:38:34.455Z" }, + { url = "https://files.pythonhosted.org/packages/6e/c2/61d3e0f47e2b74ef40a68b9e6ad5984f6241a942f7cd3bbfbdbd03861ea9/tomli-2.2.1-py3-none-any.whl", hash = "sha256:cb55c73c5f4408779d0cf3eef9f762b9c9f147a77de7b258bef0a5628adc85cc", size = 14257, upload-time = "2024-11-27T22:38:35.385Z" }, ] [[package]] name = "toolz" version = "1.0.0" source = { registry = "https://pypi.org/simple" } -sdist = { url = "https://files.pythonhosted.org/packages/8a/0b/d80dfa675bf592f636d1ea0b835eab4ec8df6e9415d8cfd766df54456123/toolz-1.0.0.tar.gz", hash = "sha256:2c86e3d9a04798ac556793bced838816296a2f085017664e4995cb40a1047a02", size = 66790 } +sdist = { url = "https://files.pythonhosted.org/packages/8a/0b/d80dfa675bf592f636d1ea0b835eab4ec8df6e9415d8cfd766df54456123/toolz-1.0.0.tar.gz", hash = "sha256:2c86e3d9a04798ac556793bced838816296a2f085017664e4995cb40a1047a02", size = 66790, upload-time = "2024-10-04T16:17:04.001Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/03/98/eb27cc78ad3af8e302c9d8ff4977f5026676e130d28dd7578132a457170c/toolz-1.0.0-py3-none-any.whl", hash = "sha256:292c8f1c4e7516bf9086f8850935c799a874039c8bcf959d47b600e4c44a6236", size = 56383 }, + { url = "https://files.pythonhosted.org/packages/03/98/eb27cc78ad3af8e302c9d8ff4977f5026676e130d28dd7578132a457170c/toolz-1.0.0-py3-none-any.whl", hash = "sha256:292c8f1c4e7516bf9086f8850935c799a874039c8bcf959d47b600e4c44a6236", size = 56383, upload-time = "2024-10-04T16:17:01.533Z" }, ] [[package]] name = "treescope" -version = "0.1.9" +version = "0.1.10" source = { registry = "https://pypi.org/simple" } dependencies = [ { name = "numpy", version = "2.2.6", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version < '3.11'" }, - { name = "numpy", version = "2.3.1", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version >= '3.11'" }, + { name = "numpy", version = "2.3.3", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version >= '3.11'" }, ] -sdist = { url = "https://files.pythonhosted.org/packages/26/27/80ad254da167e0055d5679aefd224ab08844a4cd55aeee7ef72c999d5fc6/treescope-0.1.9.tar.gz", hash = "sha256:ba6cdbdc9c5b52691d5f3bb4c5d5c7daa5627119acac8640b46d37e6aabe63a6", size = 544385 } +sdist = { url = "https://files.pythonhosted.org/packages/f0/2a/d13d3c38862632742d2fe2f7ae307c431db06538fd05ca03020d207b5dcc/treescope-0.1.10.tar.gz", hash = "sha256:20f74656f34ab2d8716715013e8163a0da79bdc2554c16d5023172c50d27ea95", size = 138870, upload-time = "2025-08-08T05:43:48.048Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/e4/09/b7e7bc5f21313d227e4fb98d2037646457ec06746327c5dd8ffed75e41e1/treescope-0.1.9-py3-none-any.whl", hash = "sha256:68677013a9f0228212fccf835f3fb037be07ae8b4c5f6f58eefab11198f83cf7", size = 182162 }, + { url = "https://files.pythonhosted.org/packages/43/2b/36e984399089c026a6499ac8f7401d38487cf0183839a4aa78140d373771/treescope-0.1.10-py3-none-any.whl", hash = "sha256:dde52f5314f4c29d22157a6fe4d3bd103f9cae02791c9e672eefa32c9aa1da51", size = 182255, upload-time = "2025-08-08T05:43:46.673Z" }, ] [[package]] name = "typing-extensions" -version = "4.14.1" +version = "4.15.0" source = { registry = "https://pypi.org/simple" } -sdist = { url = "https://files.pythonhosted.org/packages/98/5a/da40306b885cc8c09109dc2e1abd358d5684b1425678151cdaed4731c822/typing_extensions-4.14.1.tar.gz", hash = "sha256:38b39f4aeeab64884ce9f74c94263ef78f3c22467c8724005483154c26648d36", size = 107673 } +sdist = { url = "https://files.pythonhosted.org/packages/72/94/1a15dd82efb362ac84269196e94cf00f187f7ed21c242792a923cdb1c61f/typing_extensions-4.15.0.tar.gz", hash = "sha256:0cea48d173cc12fa28ecabc3b837ea3cf6f38c6d1136f85cbaaf598984861466", size = 109391, upload-time = "2025-08-25T13:49:26.313Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/b5/00/d631e67a838026495268c2f6884f3711a15a9a2a96cd244fdaea53b823fb/typing_extensions-4.14.1-py3-none-any.whl", hash = "sha256:d1e1e3b58374dc93031d6eda2420a48ea44a36c2b4766a4fdeb3710755731d76", size = 43906 }, + { url = "https://files.pythonhosted.org/packages/18/67/36e9267722cc04a6b9f15c7f3441c2363321a3ea07da7ae0c0707beb2a9c/typing_extensions-4.15.0-py3-none-any.whl", hash = "sha256:f0fa19c6845758ab08074a0cfa8b7aecb71c999ca73d62883bc25cc018c4e548", size = 44614, upload-time = "2025-08-25T13:49:24.86Z" }, ] [[package]] name = "urllib3" version = "2.5.0" source = { registry = "https://pypi.org/simple" } -sdist = { url = "https://files.pythonhosted.org/packages/15/22/9ee70a2574a4f4599c47dd506532914ce044817c7752a79b6a51286319bc/urllib3-2.5.0.tar.gz", hash = "sha256:3fc47733c7e419d4bc3f6b3dc2b4f890bb743906a30d56ba4a5bfa4bbff92760", size = 393185 } +sdist = { url = "https://files.pythonhosted.org/packages/15/22/9ee70a2574a4f4599c47dd506532914ce044817c7752a79b6a51286319bc/urllib3-2.5.0.tar.gz", hash = "sha256:3fc47733c7e419d4bc3f6b3dc2b4f890bb743906a30d56ba4a5bfa4bbff92760", size = 393185, upload-time = "2025-06-18T14:07:41.644Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/a7/c2/fe1e52489ae3122415c51f387e221dd0773709bad6c6cdaa599e8a2c5185/urllib3-2.5.0-py3-none-any.whl", hash = "sha256:e6b01673c0fa6a13e374b50871808eb3bf7046c4b125b216f6bf1cc604cff0dc", size = 129795 }, + { url = "https://files.pythonhosted.org/packages/a7/c2/fe1e52489ae3122415c51f387e221dd0773709bad6c6cdaa599e8a2c5185/urllib3-2.5.0-py3-none-any.whl", hash = "sha256:e6b01673c0fa6a13e374b50871808eb3bf7046c4b125b216f6bf1cc604cff0dc", size = 129795, upload-time = "2025-06-18T14:07:40.39Z" }, ] [[package]] name = "virtualenv" -version = "20.31.2" +version = "20.34.0" source = { registry = "https://pypi.org/simple" } dependencies = [ { name = "distlib" }, { name = "filelock" }, { name = "platformdirs" }, + { name = "typing-extensions", marker = "python_full_version < '3.11'" }, ] -sdist = { url = "https://files.pythonhosted.org/packages/56/2c/444f465fb2c65f40c3a104fd0c495184c4f2336d65baf398e3c75d72ea94/virtualenv-20.31.2.tar.gz", hash = "sha256:e10c0a9d02835e592521be48b332b6caee6887f332c111aa79a09b9e79efc2af", size = 6076316 } +sdist = { url = "https://files.pythonhosted.org/packages/1c/14/37fcdba2808a6c615681cd216fecae00413c9dab44fb2e57805ecf3eaee3/virtualenv-20.34.0.tar.gz", hash = "sha256:44815b2c9dee7ed86e387b842a84f20b93f7f417f95886ca1996a72a4138eb1a", size = 6003808, upload-time = "2025-08-13T14:24:07.464Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/f3/40/b1c265d4b2b62b58576588510fc4d1fe60a86319c8de99fd8e9fec617d2c/virtualenv-20.31.2-py3-none-any.whl", hash = "sha256:36efd0d9650ee985f0cad72065001e66d49a6f24eb44d98980f630686243cf11", size = 6057982 }, + { url = "https://files.pythonhosted.org/packages/76/06/04c8e804f813cf972e3262f3f8584c232de64f0cde9f703b46cf53a45090/virtualenv-20.34.0-py3-none-any.whl", hash = "sha256:341f5afa7eee943e4984a9207c025feedd768baff6753cd660c857ceb3e36026", size = 5983279, upload-time = "2025-08-13T14:24:05.111Z" }, ] [[package]] name = "wadler-lindig" version = "0.1.7" source = { registry = "https://pypi.org/simple" } -sdist = { url = "https://files.pythonhosted.org/packages/1e/67/cbae4bf7683a64755c2c1778c418fea96d00e34395bb91743f08bd951571/wadler_lindig-0.1.7.tar.gz", hash = "sha256:81d14d3fe77d441acf3ebd7f4aefac20c74128bf460e84b512806dccf7b2cd55", size = 15842 } +sdist = { url = "https://files.pythonhosted.org/packages/1e/67/cbae4bf7683a64755c2c1778c418fea96d00e34395bb91743f08bd951571/wadler_lindig-0.1.7.tar.gz", hash = "sha256:81d14d3fe77d441acf3ebd7f4aefac20c74128bf460e84b512806dccf7b2cd55", size = 15842, upload-time = "2025-06-18T07:00:42.843Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/8d/96/04e7b441807b26b794da5b11e59ed7f83b2cf8af202bd7eba8ad2fa6046e/wadler_lindig-0.1.7-py3-none-any.whl", hash = "sha256:e3ec83835570fd0a9509f969162aeb9c65618f998b1f42918cfc8d45122fe953", size = 20516 }, + { url = "https://files.pythonhosted.org/packages/8d/96/04e7b441807b26b794da5b11e59ed7f83b2cf8af202bd7eba8ad2fa6046e/wadler_lindig-0.1.7-py3-none-any.whl", hash = "sha256:e3ec83835570fd0a9509f969162aeb9c65618f998b1f42918cfc8d45122fe953", size = 20516, upload-time = "2025-06-18T07:00:41.684Z" }, ] [[package]] name = "watchdog" version = "6.0.0" source = { registry = "https://pypi.org/simple" } -sdist = { url = "https://files.pythonhosted.org/packages/db/7d/7f3d619e951c88ed75c6037b246ddcf2d322812ee8ea189be89511721d54/watchdog-6.0.0.tar.gz", hash = "sha256:9ddf7c82fda3ae8e24decda1338ede66e1c99883db93711d8fb941eaa2d8c282", size = 131220 } -wheels = [ - { url = "https://files.pythonhosted.org/packages/0c/56/90994d789c61df619bfc5ce2ecdabd5eeff564e1eb47512bd01b5e019569/watchdog-6.0.0-cp310-cp310-macosx_10_9_universal2.whl", hash = "sha256:d1cdb490583ebd691c012b3d6dae011000fe42edb7a82ece80965b42abd61f26", size = 96390 }, - { url = "https://files.pythonhosted.org/packages/55/46/9a67ee697342ddf3c6daa97e3a587a56d6c4052f881ed926a849fcf7371c/watchdog-6.0.0-cp310-cp310-macosx_10_9_x86_64.whl", hash = "sha256:bc64ab3bdb6a04d69d4023b29422170b74681784ffb9463ed4870cf2f3e66112", size = 88389 }, - { url = "https://files.pythonhosted.org/packages/44/65/91b0985747c52064d8701e1075eb96f8c40a79df889e59a399453adfb882/watchdog-6.0.0-cp310-cp310-macosx_11_0_arm64.whl", hash = "sha256:c897ac1b55c5a1461e16dae288d22bb2e412ba9807df8397a635d88f671d36c3", size = 89020 }, - { url = "https://files.pythonhosted.org/packages/e0/24/d9be5cd6642a6aa68352ded4b4b10fb0d7889cb7f45814fb92cecd35f101/watchdog-6.0.0-cp311-cp311-macosx_10_9_universal2.whl", hash = "sha256:6eb11feb5a0d452ee41f824e271ca311a09e250441c262ca2fd7ebcf2461a06c", size = 96393 }, - { url = "https://files.pythonhosted.org/packages/63/7a/6013b0d8dbc56adca7fdd4f0beed381c59f6752341b12fa0886fa7afc78b/watchdog-6.0.0-cp311-cp311-macosx_10_9_x86_64.whl", hash = "sha256:ef810fbf7b781a5a593894e4f439773830bdecb885e6880d957d5b9382a960d2", size = 88392 }, - { url = "https://files.pythonhosted.org/packages/d1/40/b75381494851556de56281e053700e46bff5b37bf4c7267e858640af5a7f/watchdog-6.0.0-cp311-cp311-macosx_11_0_arm64.whl", hash = "sha256:afd0fe1b2270917c5e23c2a65ce50c2a4abb63daafb0d419fde368e272a76b7c", size = 89019 }, - { url = "https://files.pythonhosted.org/packages/39/ea/3930d07dafc9e286ed356a679aa02d777c06e9bfd1164fa7c19c288a5483/watchdog-6.0.0-cp312-cp312-macosx_10_13_universal2.whl", hash = "sha256:bdd4e6f14b8b18c334febb9c4425a878a2ac20efd1e0b231978e7b150f92a948", size = 96471 }, - { url = "https://files.pythonhosted.org/packages/12/87/48361531f70b1f87928b045df868a9fd4e253d9ae087fa4cf3f7113be363/watchdog-6.0.0-cp312-cp312-macosx_10_13_x86_64.whl", hash = "sha256:c7c15dda13c4eb00d6fb6fc508b3c0ed88b9d5d374056b239c4ad1611125c860", size = 88449 }, - { url = "https://files.pythonhosted.org/packages/5b/7e/8f322f5e600812e6f9a31b75d242631068ca8f4ef0582dd3ae6e72daecc8/watchdog-6.0.0-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:6f10cb2d5902447c7d0da897e2c6768bca89174d0c6e1e30abec5421af97a5b0", size = 89054 }, - { url = "https://files.pythonhosted.org/packages/68/98/b0345cabdce2041a01293ba483333582891a3bd5769b08eceb0d406056ef/watchdog-6.0.0-cp313-cp313-macosx_10_13_universal2.whl", hash = "sha256:490ab2ef84f11129844c23fb14ecf30ef3d8a6abafd3754a6f75ca1e6654136c", size = 96480 }, - { url = "https://files.pythonhosted.org/packages/85/83/cdf13902c626b28eedef7ec4f10745c52aad8a8fe7eb04ed7b1f111ca20e/watchdog-6.0.0-cp313-cp313-macosx_10_13_x86_64.whl", hash = "sha256:76aae96b00ae814b181bb25b1b98076d5fc84e8a53cd8885a318b42b6d3a5134", size = 88451 }, - { url = "https://files.pythonhosted.org/packages/fe/c4/225c87bae08c8b9ec99030cd48ae9c4eca050a59bf5c2255853e18c87b50/watchdog-6.0.0-cp313-cp313-macosx_11_0_arm64.whl", hash = "sha256:a175f755fc2279e0b7312c0035d52e27211a5bc39719dd529625b1930917345b", size = 89057 }, - { url = "https://files.pythonhosted.org/packages/30/ad/d17b5d42e28a8b91f8ed01cb949da092827afb9995d4559fd448d0472763/watchdog-6.0.0-pp310-pypy310_pp73-macosx_10_15_x86_64.whl", hash = "sha256:c7ac31a19f4545dd92fc25d200694098f42c9a8e391bc00bdd362c5736dbf881", size = 87902 }, - { url = "https://files.pythonhosted.org/packages/5c/ca/c3649991d140ff6ab67bfc85ab42b165ead119c9e12211e08089d763ece5/watchdog-6.0.0-pp310-pypy310_pp73-macosx_11_0_arm64.whl", hash = "sha256:9513f27a1a582d9808cf21a07dae516f0fab1cf2d7683a742c498b93eedabb11", size = 88380 }, - { url = "https://files.pythonhosted.org/packages/a9/c7/ca4bf3e518cb57a686b2feb4f55a1892fd9a3dd13f470fca14e00f80ea36/watchdog-6.0.0-py3-none-manylinux2014_aarch64.whl", hash = "sha256:7607498efa04a3542ae3e05e64da8202e58159aa1fa4acddf7678d34a35d4f13", size = 79079 }, - { url = "https://files.pythonhosted.org/packages/5c/51/d46dc9332f9a647593c947b4b88e2381c8dfc0942d15b8edc0310fa4abb1/watchdog-6.0.0-py3-none-manylinux2014_armv7l.whl", hash = "sha256:9041567ee8953024c83343288ccc458fd0a2d811d6a0fd68c4c22609e3490379", size = 79078 }, - { url = "https://files.pythonhosted.org/packages/d4/57/04edbf5e169cd318d5f07b4766fee38e825d64b6913ca157ca32d1a42267/watchdog-6.0.0-py3-none-manylinux2014_i686.whl", hash = "sha256:82dc3e3143c7e38ec49d61af98d6558288c415eac98486a5c581726e0737c00e", size = 79076 }, - { url = "https://files.pythonhosted.org/packages/ab/cc/da8422b300e13cb187d2203f20b9253e91058aaf7db65b74142013478e66/watchdog-6.0.0-py3-none-manylinux2014_ppc64.whl", hash = "sha256:212ac9b8bf1161dc91bd09c048048a95ca3a4c4f5e5d4a7d1b1a7d5752a7f96f", size = 79077 }, - { url = "https://files.pythonhosted.org/packages/2c/3b/b8964e04ae1a025c44ba8e4291f86e97fac443bca31de8bd98d3263d2fcf/watchdog-6.0.0-py3-none-manylinux2014_ppc64le.whl", hash = "sha256:e3df4cbb9a450c6d49318f6d14f4bbc80d763fa587ba46ec86f99f9e6876bb26", size = 79078 }, - { url = "https://files.pythonhosted.org/packages/62/ae/a696eb424bedff7407801c257d4b1afda455fe40821a2be430e173660e81/watchdog-6.0.0-py3-none-manylinux2014_s390x.whl", hash = "sha256:2cce7cfc2008eb51feb6aab51251fd79b85d9894e98ba847408f662b3395ca3c", size = 79077 }, - { url = "https://files.pythonhosted.org/packages/b5/e8/dbf020b4d98251a9860752a094d09a65e1b436ad181faf929983f697048f/watchdog-6.0.0-py3-none-manylinux2014_x86_64.whl", hash = "sha256:20ffe5b202af80ab4266dcd3e91aae72bf2da48c0d33bdb15c66658e685e94e2", size = 79078 }, - { url = "https://files.pythonhosted.org/packages/07/f6/d0e5b343768e8bcb4cda79f0f2f55051bf26177ecd5651f84c07567461cf/watchdog-6.0.0-py3-none-win32.whl", hash = "sha256:07df1fdd701c5d4c8e55ef6cf55b8f0120fe1aef7ef39a1c6fc6bc2e606d517a", size = 79065 }, - { url = "https://files.pythonhosted.org/packages/db/d9/c495884c6e548fce18a8f40568ff120bc3a4b7b99813081c8ac0c936fa64/watchdog-6.0.0-py3-none-win_amd64.whl", hash = "sha256:cbafb470cf848d93b5d013e2ecb245d4aa1c8fd0504e863ccefa32445359d680", size = 79070 }, - { url = "https://files.pythonhosted.org/packages/33/e8/e40370e6d74ddba47f002a32919d91310d6074130fe4e17dabcafc15cbf1/watchdog-6.0.0-py3-none-win_ia64.whl", hash = "sha256:a1914259fa9e1454315171103c6a30961236f508b9b623eae470268bbcc6a22f", size = 79067 }, +sdist = { url = "https://files.pythonhosted.org/packages/db/7d/7f3d619e951c88ed75c6037b246ddcf2d322812ee8ea189be89511721d54/watchdog-6.0.0.tar.gz", hash = "sha256:9ddf7c82fda3ae8e24decda1338ede66e1c99883db93711d8fb941eaa2d8c282", size = 131220, upload-time = "2024-11-01T14:07:13.037Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/0c/56/90994d789c61df619bfc5ce2ecdabd5eeff564e1eb47512bd01b5e019569/watchdog-6.0.0-cp310-cp310-macosx_10_9_universal2.whl", hash = "sha256:d1cdb490583ebd691c012b3d6dae011000fe42edb7a82ece80965b42abd61f26", size = 96390, upload-time = "2024-11-01T14:06:24.793Z" }, + { url = "https://files.pythonhosted.org/packages/55/46/9a67ee697342ddf3c6daa97e3a587a56d6c4052f881ed926a849fcf7371c/watchdog-6.0.0-cp310-cp310-macosx_10_9_x86_64.whl", hash = "sha256:bc64ab3bdb6a04d69d4023b29422170b74681784ffb9463ed4870cf2f3e66112", size = 88389, upload-time = "2024-11-01T14:06:27.112Z" }, + { url = "https://files.pythonhosted.org/packages/44/65/91b0985747c52064d8701e1075eb96f8c40a79df889e59a399453adfb882/watchdog-6.0.0-cp310-cp310-macosx_11_0_arm64.whl", hash = "sha256:c897ac1b55c5a1461e16dae288d22bb2e412ba9807df8397a635d88f671d36c3", size = 89020, upload-time = "2024-11-01T14:06:29.876Z" }, + { url = "https://files.pythonhosted.org/packages/e0/24/d9be5cd6642a6aa68352ded4b4b10fb0d7889cb7f45814fb92cecd35f101/watchdog-6.0.0-cp311-cp311-macosx_10_9_universal2.whl", hash = "sha256:6eb11feb5a0d452ee41f824e271ca311a09e250441c262ca2fd7ebcf2461a06c", size = 96393, upload-time = "2024-11-01T14:06:31.756Z" }, + { url = "https://files.pythonhosted.org/packages/63/7a/6013b0d8dbc56adca7fdd4f0beed381c59f6752341b12fa0886fa7afc78b/watchdog-6.0.0-cp311-cp311-macosx_10_9_x86_64.whl", hash = "sha256:ef810fbf7b781a5a593894e4f439773830bdecb885e6880d957d5b9382a960d2", size = 88392, upload-time = "2024-11-01T14:06:32.99Z" }, + { url = "https://files.pythonhosted.org/packages/d1/40/b75381494851556de56281e053700e46bff5b37bf4c7267e858640af5a7f/watchdog-6.0.0-cp311-cp311-macosx_11_0_arm64.whl", hash = "sha256:afd0fe1b2270917c5e23c2a65ce50c2a4abb63daafb0d419fde368e272a76b7c", size = 89019, upload-time = "2024-11-01T14:06:34.963Z" }, + { url = "https://files.pythonhosted.org/packages/39/ea/3930d07dafc9e286ed356a679aa02d777c06e9bfd1164fa7c19c288a5483/watchdog-6.0.0-cp312-cp312-macosx_10_13_universal2.whl", hash = "sha256:bdd4e6f14b8b18c334febb9c4425a878a2ac20efd1e0b231978e7b150f92a948", size = 96471, upload-time = "2024-11-01T14:06:37.745Z" }, + { url = "https://files.pythonhosted.org/packages/12/87/48361531f70b1f87928b045df868a9fd4e253d9ae087fa4cf3f7113be363/watchdog-6.0.0-cp312-cp312-macosx_10_13_x86_64.whl", hash = "sha256:c7c15dda13c4eb00d6fb6fc508b3c0ed88b9d5d374056b239c4ad1611125c860", size = 88449, upload-time = "2024-11-01T14:06:39.748Z" }, + { url = "https://files.pythonhosted.org/packages/5b/7e/8f322f5e600812e6f9a31b75d242631068ca8f4ef0582dd3ae6e72daecc8/watchdog-6.0.0-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:6f10cb2d5902447c7d0da897e2c6768bca89174d0c6e1e30abec5421af97a5b0", size = 89054, upload-time = "2024-11-01T14:06:41.009Z" }, + { url = "https://files.pythonhosted.org/packages/68/98/b0345cabdce2041a01293ba483333582891a3bd5769b08eceb0d406056ef/watchdog-6.0.0-cp313-cp313-macosx_10_13_universal2.whl", hash = "sha256:490ab2ef84f11129844c23fb14ecf30ef3d8a6abafd3754a6f75ca1e6654136c", size = 96480, upload-time = "2024-11-01T14:06:42.952Z" }, + { url = "https://files.pythonhosted.org/packages/85/83/cdf13902c626b28eedef7ec4f10745c52aad8a8fe7eb04ed7b1f111ca20e/watchdog-6.0.0-cp313-cp313-macosx_10_13_x86_64.whl", hash = "sha256:76aae96b00ae814b181bb25b1b98076d5fc84e8a53cd8885a318b42b6d3a5134", size = 88451, upload-time = "2024-11-01T14:06:45.084Z" }, + { url = "https://files.pythonhosted.org/packages/fe/c4/225c87bae08c8b9ec99030cd48ae9c4eca050a59bf5c2255853e18c87b50/watchdog-6.0.0-cp313-cp313-macosx_11_0_arm64.whl", hash = "sha256:a175f755fc2279e0b7312c0035d52e27211a5bc39719dd529625b1930917345b", size = 89057, upload-time = "2024-11-01T14:06:47.324Z" }, + { url = "https://files.pythonhosted.org/packages/30/ad/d17b5d42e28a8b91f8ed01cb949da092827afb9995d4559fd448d0472763/watchdog-6.0.0-pp310-pypy310_pp73-macosx_10_15_x86_64.whl", hash = "sha256:c7ac31a19f4545dd92fc25d200694098f42c9a8e391bc00bdd362c5736dbf881", size = 87902, upload-time = "2024-11-01T14:06:53.119Z" }, + { url = "https://files.pythonhosted.org/packages/5c/ca/c3649991d140ff6ab67bfc85ab42b165ead119c9e12211e08089d763ece5/watchdog-6.0.0-pp310-pypy310_pp73-macosx_11_0_arm64.whl", hash = "sha256:9513f27a1a582d9808cf21a07dae516f0fab1cf2d7683a742c498b93eedabb11", size = 88380, upload-time = "2024-11-01T14:06:55.19Z" }, + { url = "https://files.pythonhosted.org/packages/a9/c7/ca4bf3e518cb57a686b2feb4f55a1892fd9a3dd13f470fca14e00f80ea36/watchdog-6.0.0-py3-none-manylinux2014_aarch64.whl", hash = "sha256:7607498efa04a3542ae3e05e64da8202e58159aa1fa4acddf7678d34a35d4f13", size = 79079, upload-time = "2024-11-01T14:06:59.472Z" }, + { url = "https://files.pythonhosted.org/packages/5c/51/d46dc9332f9a647593c947b4b88e2381c8dfc0942d15b8edc0310fa4abb1/watchdog-6.0.0-py3-none-manylinux2014_armv7l.whl", hash = "sha256:9041567ee8953024c83343288ccc458fd0a2d811d6a0fd68c4c22609e3490379", size = 79078, upload-time = "2024-11-01T14:07:01.431Z" }, + { url = "https://files.pythonhosted.org/packages/d4/57/04edbf5e169cd318d5f07b4766fee38e825d64b6913ca157ca32d1a42267/watchdog-6.0.0-py3-none-manylinux2014_i686.whl", hash = "sha256:82dc3e3143c7e38ec49d61af98d6558288c415eac98486a5c581726e0737c00e", size = 79076, upload-time = "2024-11-01T14:07:02.568Z" }, + { url = "https://files.pythonhosted.org/packages/ab/cc/da8422b300e13cb187d2203f20b9253e91058aaf7db65b74142013478e66/watchdog-6.0.0-py3-none-manylinux2014_ppc64.whl", hash = "sha256:212ac9b8bf1161dc91bd09c048048a95ca3a4c4f5e5d4a7d1b1a7d5752a7f96f", size = 79077, upload-time = "2024-11-01T14:07:03.893Z" }, + { url = "https://files.pythonhosted.org/packages/2c/3b/b8964e04ae1a025c44ba8e4291f86e97fac443bca31de8bd98d3263d2fcf/watchdog-6.0.0-py3-none-manylinux2014_ppc64le.whl", hash = "sha256:e3df4cbb9a450c6d49318f6d14f4bbc80d763fa587ba46ec86f99f9e6876bb26", size = 79078, upload-time = "2024-11-01T14:07:05.189Z" }, + { url = "https://files.pythonhosted.org/packages/62/ae/a696eb424bedff7407801c257d4b1afda455fe40821a2be430e173660e81/watchdog-6.0.0-py3-none-manylinux2014_s390x.whl", hash = "sha256:2cce7cfc2008eb51feb6aab51251fd79b85d9894e98ba847408f662b3395ca3c", size = 79077, upload-time = "2024-11-01T14:07:06.376Z" }, + { url = "https://files.pythonhosted.org/packages/b5/e8/dbf020b4d98251a9860752a094d09a65e1b436ad181faf929983f697048f/watchdog-6.0.0-py3-none-manylinux2014_x86_64.whl", hash = "sha256:20ffe5b202af80ab4266dcd3e91aae72bf2da48c0d33bdb15c66658e685e94e2", size = 79078, upload-time = "2024-11-01T14:07:07.547Z" }, + { url = "https://files.pythonhosted.org/packages/07/f6/d0e5b343768e8bcb4cda79f0f2f55051bf26177ecd5651f84c07567461cf/watchdog-6.0.0-py3-none-win32.whl", hash = "sha256:07df1fdd701c5d4c8e55ef6cf55b8f0120fe1aef7ef39a1c6fc6bc2e606d517a", size = 79065, upload-time = "2024-11-01T14:07:09.525Z" }, + { url = "https://files.pythonhosted.org/packages/db/d9/c495884c6e548fce18a8f40568ff120bc3a4b7b99813081c8ac0c936fa64/watchdog-6.0.0-py3-none-win_amd64.whl", hash = "sha256:cbafb470cf848d93b5d013e2ecb245d4aa1c8fd0504e863ccefa32445359d680", size = 79070, upload-time = "2024-11-01T14:07:10.686Z" }, + { url = "https://files.pythonhosted.org/packages/33/e8/e40370e6d74ddba47f002a32919d91310d6074130fe4e17dabcafc15cbf1/watchdog-6.0.0-py3-none-win_ia64.whl", hash = "sha256:a1914259fa9e1454315171103c6a30961236f508b9b623eae470268bbcc6a22f", size = 79067, upload-time = "2024-11-01T14:07:11.845Z" }, ] [[package]] @@ -1696,16 +1936,16 @@ source = { registry = "https://pypi.org/simple" } dependencies = [ { name = "bracex" }, ] -sdist = { url = "https://files.pythonhosted.org/packages/79/3e/c0bdc27cf06f4e47680bd5803a07cb3dfd17de84cde92dd217dcb9e05253/wcmatch-10.1.tar.gz", hash = "sha256:f11f94208c8c8484a16f4f48638a85d771d9513f4ab3f37595978801cb9465af", size = 117421 } +sdist = { url = "https://files.pythonhosted.org/packages/79/3e/c0bdc27cf06f4e47680bd5803a07cb3dfd17de84cde92dd217dcb9e05253/wcmatch-10.1.tar.gz", hash = "sha256:f11f94208c8c8484a16f4f48638a85d771d9513f4ab3f37595978801cb9465af", size = 117421, upload-time = "2025-06-22T19:14:02.49Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/eb/d8/0d1d2e9d3fabcf5d6840362adcf05f8cf3cd06a73358140c3a97189238ae/wcmatch-10.1-py3-none-any.whl", hash = "sha256:5848ace7dbb0476e5e55ab63c6bbd529745089343427caa5537f230cc01beb8a", size = 39854 }, + { url = "https://files.pythonhosted.org/packages/eb/d8/0d1d2e9d3fabcf5d6840362adcf05f8cf3cd06a73358140c3a97189238ae/wcmatch-10.1-py3-none-any.whl", hash = "sha256:5848ace7dbb0476e5e55ab63c6bbd529745089343427caa5537f230cc01beb8a", size = 39854, upload-time = "2025-06-22T19:14:00.978Z" }, ] [[package]] name = "zipp" version = "3.23.0" source = { registry = "https://pypi.org/simple" } -sdist = { url = "https://files.pythonhosted.org/packages/e3/02/0f2892c661036d50ede074e376733dca2ae7c6eb617489437771209d4180/zipp-3.23.0.tar.gz", hash = "sha256:a07157588a12518c9d4034df3fbbee09c814741a33ff63c05fa29d26a2404166", size = 25547 } +sdist = { url = "https://files.pythonhosted.org/packages/e3/02/0f2892c661036d50ede074e376733dca2ae7c6eb617489437771209d4180/zipp-3.23.0.tar.gz", hash = "sha256:a07157588a12518c9d4034df3fbbee09c814741a33ff63c05fa29d26a2404166", size = 25547, upload-time = "2025-06-08T17:06:39.4Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/2e/54/647ade08bf0db230bfea292f893923872fd20be6ac6f53b2b936ba839d75/zipp-3.23.0-py3-none-any.whl", hash = "sha256:071652d6115ed432f5ce1d34c336c0adfd6a884660d1e9712a256d3d3bd4b14e", size = 10276 }, + { url = "https://files.pythonhosted.org/packages/2e/54/647ade08bf0db230bfea292f893923872fd20be6ac6f53b2b936ba839d75/zipp-3.23.0-py3-none-any.whl", hash = "sha256:071652d6115ed432f5ce1d34c336c0adfd6a884660d1e9712a256d3d3bd4b14e", size = 10276, upload-time = "2025-06-08T17:06:38.034Z" }, ] commit 8b06755ebe023e52db5e6325d62c03f45e3b3c28 Date: 2025-10-02T08:45:40-07:00 update to 3.11 conventions (#195) * update to 3.11 conventions * update yamls * Sweep: adopt Python 3.11 typing (PEP 604, built-in generics), add __future__ annotations to _src/scan.py; fix type aliases and mypy; keep runtime-safe aliases in core.py * deprecate _get_mesh * deprecate _get_mesh * precommit * precommit * wip * support jax 0.6.2 and 0.7.2 * cleanup * pre-commit * sigh * better diff --git a/.github/workflows/publish_dev.yaml b/.github/workflows/publish_dev.yaml index 9899637..c2e7ea6 100644 --- a/.github/workflows/publish_dev.yaml +++ b/.github/workflows/publish_dev.yaml @@ -20,7 +20,7 @@ jobs: - name: Set up Python uses: actions/setup-python@v2 with: - python-version: '3.x' + python-version: '3.11' - name: Calculate Version and Build Number run: | diff --git a/.github/workflows/run_pre_commit.yaml b/.github/workflows/run_pre_commit.yaml index 88b59fb..b321346 100644 --- a/.github/workflows/run_pre_commit.yaml +++ b/.github/workflows/run_pre_commit.yaml @@ -8,7 +8,7 @@ jobs: runs-on: ubuntu-latest strategy: matrix: - python-version: ["3.10.11"] + python-version: ["3.11"] steps: - uses: actions/checkout@v3 diff --git a/.github/workflows/run_quick_levanter_tests.yaml b/.github/workflows/run_quick_levanter_tests.yaml index a235ff1..694fe9a 100644 --- a/.github/workflows/run_quick_levanter_tests.yaml +++ b/.github/workflows/run_quick_levanter_tests.yaml @@ -9,7 +9,7 @@ jobs: runs-on: ubuntu-latest strategy: matrix: - python-version: ["3.10", "3.11"] + python-version: ["3.11"] steps: - name: Checkout repository uses: actions/checkout@v3 diff --git a/.github/workflows/run_tests.yaml b/.github/workflows/run_tests.yaml index 9d805f1..e8e556a 100644 --- a/.github/workflows/run_tests.yaml +++ b/.github/workflows/run_tests.yaml @@ -9,10 +9,10 @@ jobs: steps: - uses: actions/checkout@v3 - - name: Set up Python 3.10.11 + - name: Set up Python 3.11 uses: actions/setup-python@v4 with: - python-version: 3.10.11 + python-version: 3.11 - name: Install dependencies run: | python -m pip install uv diff --git a/pyproject.toml b/pyproject.toml index 1b829ec..d0b694e 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -11,7 +11,7 @@ authors = [ ] description = "Named Tensors for Legible Deep Learning in JAX" readme = "README.md" -requires-python = ">=3.10" +requires-python = ">=3.11" classifiers = [ "Programming Language :: Python :: 3", "License :: OSI Approved :: Apache Software License", @@ -60,7 +60,7 @@ haliax = ["src/haliax/*"] [tool.black] line-length = 119 -target-version = ["py310"] +target-version = ["py311"] preview = true [tool.isort] diff --git a/src/haliax/__init__.py b/src/haliax/__init__.py index 8a11c44..ebab498 100644 --- a/src/haliax/__init__.py +++ b/src/haliax/__init__.py @@ -4,7 +4,7 @@ import typing as t -from typing import Optional, Sequence +from typing import Sequence import jax import jax.numpy as jnp @@ -139,21 +139,21 @@ A = t.TypeVar("A", Scalar, NamedArray, jnp.ndarray) # creation routines -def zeros(shape: AxisSpec, dtype: Optional[DTypeLike] = None) -> NamedArray: +def zeros(shape: AxisSpec, dtype: DTypeLike | None = None) -> NamedArray: """Creates a NamedArray with all elements set to 0""" if dtype is None: dtype = jnp.float32 return full(shape, 0, dtype) -def ones(shape: AxisSpec, dtype: Optional[DTypeLike] = None) -> NamedArray: +def ones(shape: AxisSpec, dtype: DTypeLike | None = None) -> NamedArray: """Creates a NamedArray with all elements set to 1""" if dtype is None: dtype = jnp.float32 return full(shape, 1, dtype) -def full(shape: AxisSpec, fill_value: T, dtype: Optional[DTypeLike] = None) -> NamedArray: +def full(shape: AxisSpec, fill_value: T, dtype: DTypeLike | None = None) -> NamedArray: """Creates a NamedArray with all elements set to `fill_value`""" if isinstance(shape, Axis): return NamedArray(jnp.full(shape=shape.size, fill_value=fill_value, dtype=dtype), (shape,)) @@ -172,12 +172,12 @@ def ones_like(a: NamedArray, dtype=None) -> NamedArray: return NamedArray(jnp.ones_like(a.array, dtype=dtype), a.axes) -def full_like(a: NamedArray, fill_value: T, dtype: Optional[DTypeLike] = None) -> NamedArray: +def full_like(a: NamedArray, fill_value: T, dtype: DTypeLike | None = None) -> NamedArray: """Creates a NamedArray with all elements set to `fill_value`""" return NamedArray(jnp.full_like(a.array, fill_value, dtype=dtype), a.axes) -def arange(axis: AxisSpec, *, start=0, step=1, dtype: Optional[DTypeLike] = None) -> NamedArray: +def arange(axis: AxisSpec, *, start=0, step=1, dtype: DTypeLike | None = None) -> NamedArray: """ Version of jnp.arange that returns a NamedArray. @@ -208,7 +208,7 @@ def arange(axis: AxisSpec, *, start=0, step=1, dtype: Optional[DTypeLike] = None # TODO: add overrides for arraylike start/stop to linspace, logspace, geomspace def linspace( - axis: AxisSelector, *, start: float, stop: float, endpoint: bool = True, dtype: Optional[DTypeLike] = None + axis: AxisSelector, *, start: float, stop: float, endpoint: bool = True, dtype: DTypeLike | None = None ) -> NamedArray: """ Version of jnp.linspace that returns a NamedArray. @@ -226,7 +226,7 @@ def logspace( stop: float, endpoint: bool = True, base: float = 10.0, - dtype: Optional[DTypeLike] = None, + dtype: DTypeLike | None = None, ) -> NamedArray: """ Version of jnp.logspace that returns a NamedArray. @@ -238,7 +238,7 @@ def logspace( def geomspace( - axis: AxisSelector, *, start: float, stop: float, endpoint: bool = True, dtype: Optional[DTypeLike] = None + axis: AxisSelector, *, start: float, stop: float, endpoint: bool = True, dtype: DTypeLike | None = None ) -> NamedArray: """ Version of jnp.geomspace that returns a NamedArray. @@ -260,7 +260,7 @@ def stack(axis: AxisSelector, arrays: Sequence[NamedArray]) -> NamedArray: def repeat( - a: NamedArray, repeats: int | jnp.ndarray, axis: AxisSelector, total_repeat_length: Optional[int] = None + a: NamedArray, repeats: int | jnp.ndarray, axis: AxisSelector, total_repeat_length: int | None = None ) -> NamedArray: """Version of [jax.numpy.repeat][] that returns a NamedArray""" index = a.axis_indices(axis) @@ -587,91 +587,91 @@ def trunc(a: A) -> A: # Reduction functions -def all(array: NamedArray, axis: Optional[AxisSelection] = None, *, where: Optional[NamedArray] = None) -> NamedArray: +def all(array: NamedArray, axis: AxisSelection | None = None, *, where: NamedArray | None = None) -> NamedArray: """ Named version of [jax.numpy.all](https://jax.readthedocs.io/en/latest/_autosummary/jax.numpy.all.html#jax.numpy.all). """ return wrap_reduction_call(jnp.all, array, axis, where, single_axis_only=False, supports_where=True) -def amax(array: NamedArray, axis: Optional[AxisSelection] = None, *, where: Optional[NamedArray] = None) -> NamedArray: +def amax(array: NamedArray, axis: AxisSelection | None = None, *, where: NamedArray | None = None) -> NamedArray: """ Aliax for max. See max for details. """ return wrap_reduction_call(jnp.amax, array, axis, where, single_axis_only=False, supports_where=True) -def amin(array: NamedArray, axis: Optional[AxisSelection] = None, *, where: Optional[NamedArray] = None) -> NamedArray: +def amin(array: NamedArray, axis: AxisSelection | None = None, *, where: NamedArray | None = None) -> NamedArray: """ Aliax for min. See min for details. """ return wrap_reduction_call(jnp.amin, array, axis, where, single_axis_only=False, supports_where=True) -def any(array: NamedArray, axis: Optional[AxisSelection] = None, *, where: Optional[NamedArray] = None) -> NamedArray: +def any(array: NamedArray, axis: AxisSelection | None = None, *, where: NamedArray | None = None) -> NamedArray: """True if any elements along a given axis or axes are True. If axis is None, any elements are True.""" return wrap_reduction_call(jnp.any, array, axis, where, single_axis_only=False, supports_where=True) -def argmax(array: NamedArray, axis: Optional[AxisSelector]) -> NamedArray: +def argmax(array: NamedArray, axis: AxisSelector | None) -> NamedArray: return wrap_reduction_call(jnp.argmax, array, axis, None, single_axis_only=True, supports_where=False) -def argmin(array: NamedArray, axis: Optional[AxisSelector]) -> NamedArray: +def argmin(array: NamedArray, axis: AxisSelector | None) -> NamedArray: return wrap_reduction_call(jnp.argmin, array, axis, None, single_axis_only=True, supports_where=False) -def max(array: NamedArray, axis: Optional[AxisSelection] = None, *, where: Optional[NamedArray] = None) -> NamedArray: +def max(array: NamedArray, axis: AxisSelection | None = None, *, where: NamedArray | None = None) -> NamedArray: return wrap_reduction_call(jnp.max, array, axis, where, single_axis_only=False, supports_where=True) def mean( array: NamedArray, - axis: Optional[AxisSelection] = None, + axis: AxisSelection | None = None, *, - where: Optional[NamedArray] = None, - dtype: Optional[DTypeLike] = None, + where: NamedArray | None = None, + dtype: DTypeLike | None = None, ) -> NamedArray: return wrap_reduction_call(jnp.mean, array, axis, where, single_axis_only=False, supports_where=True, dtype=dtype) -def min(array: NamedArray, axis: Optional[AxisSelection] = None, *, where: Optional[NamedArray] = None) -> NamedArray: +def min(array: NamedArray, axis: AxisSelection | None = None, *, where: NamedArray | None = None) -> NamedArray: return wrap_reduction_call(jnp.min, array, axis, where, single_axis_only=False, supports_where=True) def prod( array: NamedArray, - axis: Optional[AxisSelection] = None, + axis: AxisSelection | None = None, *, - where: Optional[NamedArray] = None, - dtype: Optional[DTypeLike] = None, + where: NamedArray | None = None, + dtype: DTypeLike | None = None, ) -> NamedArray: return wrap_reduction_call(jnp.prod, array, axis, where, single_axis_only=False, supports_where=True, dtype=dtype) def std( array: NamedArray, - axis: Optional[AxisSelection] = None, + axis: AxisSelection | None = None, *, - where: Optional[NamedArray] = None, + where: NamedArray | None = None, ddof: int = 0, - dtype: Optional[DTypeLike] = None, + dtype: DTypeLike | None = None, ) -> NamedArray: return wrap_reduction_call( jnp.std, array, axis, where, single_axis_only=False, supports_where=True, dtype=dtype, ddof=ddof ) -def ptp(array: NamedArray, axis: Optional[AxisSelection] = None, *, where: Optional[NamedArray] = None) -> NamedArray: +def ptp(array: NamedArray, axis: AxisSelection | None = None, *, where: NamedArray | None = None) -> NamedArray: return wrap_reduction_call(jnp.ptp, array, axis, where, single_axis_only=False, supports_where=True) def product( array: NamedArray, - axis: Optional[AxisSelection] = None, + axis: AxisSelection | None = None, *, - where: Optional[NamedArray] = None, - dtype: Optional[DTypeLike] = None, + where: NamedArray | None = None, + dtype: DTypeLike | None = None, ) -> NamedArray: return wrap_reduction_call( jnp.product, array, axis, where, single_axis_only=False, supports_where=True, dtype=dtype @@ -683,50 +683,50 @@ _sum = sum def sum( array: NamedArray, - axis: Optional[AxisSelection] = None, + axis: AxisSelection | None = None, *, - where: Optional[NamedArray] = None, - dtype: Optional[DTypeLike] = None, + where: NamedArray | None = None, + dtype: DTypeLike | None = None, ) -> NamedArray: return wrap_reduction_call(jnp.sum, array, axis, where, single_axis_only=False, supports_where=True, dtype=dtype) def var( array: NamedArray, - axis: Optional[AxisSelection] = None, + axis: AxisSelection | None = None, *, - where: Optional[NamedArray] = None, + where: NamedArray | None = None, ddof: int = 0, - dtype: Optional[DTypeLike] = None, + dtype: DTypeLike | None = None, ) -> NamedArray: return wrap_reduction_call( jnp.var, array, axis, where, single_axis_only=False, supports_where=True, dtype=dtype, ddof=ddof ) -def nanargmax(array: NamedArray, axis: Optional[AxisSelector] = None) -> NamedArray: +def nanargmax(array: NamedArray, axis: AxisSelector | None = None) -> NamedArray: return wrap_reduction_call(jnp.nanargmax, array, axis, None, single_axis_only=True, supports_where=False) -def nanargmin(array: NamedArray, axis: Optional[AxisSelector] = None) -> NamedArray: +def nanargmin(array: NamedArray, axis: AxisSelector | None = None) -> NamedArray: return wrap_reduction_call(jnp.nanargmin, array, axis, None, single_axis_only=True, supports_where=False) def nanmax( array: NamedArray, - axis: Optional[AxisSelection] = None, + axis: AxisSelection | None = None, *, - where: Optional[NamedArray] = None, + where: NamedArray | None = None, ) -> NamedArray: return wrap_reduction_call(jnp.nanmax, array, axis, where, single_axis_only=False, supports_where=True) def nanmean( array: NamedArray, - axis: Optional[AxisSelection] = None, + axis: AxisSelection | None = None, *, - where: Optional[NamedArray] = None, - dtype: Optional[DTypeLike] = None, + where: NamedArray | None = None, + dtype: DTypeLike | None = None, ) -> NamedArray: return wrap_reduction_call( jnp.nanmean, array, axis, where, single_axis_only=False, supports_where=True, dtype=dtype @@ -735,19 +735,19 @@ def nanmean( def nanmin( array: NamedArray, - axis: Optional[AxisSelection] = None, + axis: AxisSelection | None = None, *, - where: Optional[NamedArray] = None, + where: NamedArray | None = None, ) -> NamedArray: return wrap_reduction_call(jnp.nanmin, array, axis, where, single_axis_only=False, supports_where=True) def nanprod( array: NamedArray, - axis: Optional[AxisSelection] = None, + axis: AxisSelection | None = None, *, - where: Optional[NamedArray] = None, - dtype: Optional[DTypeLike] = None, + where: NamedArray | None = None, + dtype: DTypeLike | None = None, ) -> NamedArray: return wrap_reduction_call( jnp.nanprod, array, axis, where, single_axis_only=False, supports_where=True, dtype=dtype @@ -756,11 +756,11 @@ def nanprod( def nanstd( array: NamedArray, - axis: Optional[AxisSelection] = None, + axis: AxisSelection | None = None, *, - where: Optional[NamedArray] = None, + where: NamedArray | None = None, ddof: int = 0, - dtype: Optional[DTypeLike] = None, + dtype: DTypeLike | None = None, ) -> NamedArray: return wrap_reduction_call( jnp.nanstd, array, axis, where, single_axis_only=False, supports_where=True, dtype=dtype, ddof=ddof @@ -769,10 +769,10 @@ def nanstd( def nansum( array: NamedArray, - axis: Optional[AxisSelection] = None, + axis: AxisSelection | None = None, *, - where: Optional[NamedArray] = None, - dtype: Optional[DTypeLike] = None, + where: NamedArray | None = None, + dtype: DTypeLike | None = None, ) -> NamedArray: return wrap_reduction_call( jnp.nansum, array, axis, where, single_axis_only=False, supports_where=True, dtype=dtype @@ -781,11 +781,11 @@ def nansum( def nanvar( array: NamedArray, - axis: Optional[AxisSelection] = None, + axis: AxisSelection | None = None, *, - where: Optional[NamedArray] = None, + where: NamedArray | None = None, ddof: int = 0, - dtype: Optional[DTypeLike] = None, + dtype: DTypeLike | None = None, ) -> NamedArray: return wrap_reduction_call( jnp.nanvar, array, axis, where, single_axis_only=False, supports_where=True, dtype=dtype, ddof=ddof @@ -795,28 +795,28 @@ def nanvar( # "Normalization" functions that use an axis but don't change the shape -def cumsum(a: NamedArray, axis: AxisSelector, *, dtype: Optional[DTypeLike] = None) -> NamedArray: +def cumsum(a: NamedArray, axis: AxisSelector, *, dtype: DTypeLike | None = None) -> NamedArray: """ Named version of [jax.numpy.cumsum](https://jax.readthedocs.io/en/latest/_autosummary/jax.numpy.cumsum.html) """ return wrap_axiswise_call(jnp.cumsum, a, axis, dtype=dtype, single_axis_only=True) -def cumprod(a: NamedArray, axis: AxisSelector, dtype: Optional[DTypeLike] = None) -> NamedArray: +def cumprod(a: NamedArray, axis: AxisSelector, dtype: DTypeLike | None = None) -> NamedArray: """ Named version of [jax.numpy.cumprod](https://jax.readthedocs.io/en/latest/_autosummary/jax.numpy.cumprod.html) """ return wrap_axiswise_call(jnp.cumprod, a, axis, dtype=dtype, single_axis_only=True) -def nancumsum(a: NamedArray, axis: AxisSelector, *, dtype: Optional[DTypeLike] = None) -> NamedArray: +def nancumsum(a: NamedArray, axis: AxisSelector, *, dtype: DTypeLike | None = None) -> NamedArray: """ Named version of [jax.numpy.nancumsum](https://jax.readthedocs.io/en/latest/_autosummary/jax.numpy.nancumsum.html) """ return wrap_axiswise_call(jnp.nancumsum, a, axis, dtype=dtype, single_axis_only=True) -def nancumprod(a: NamedArray, axis: AxisSelector, dtype: Optional[DTypeLike] = None) -> NamedArray: +def nancumprod(a: NamedArray, axis: AxisSelector, dtype: DTypeLike | None = None) -> NamedArray: """ Named version of [jax.numpy.nancumprod](https://jax.readthedocs.io/en/latest/_autosummary/jax.numpy.nancumprod.html) """ diff --git a/src/haliax/_src/dot.py b/src/haliax/_src/dot.py index fab72c8..777b499 100644 --- a/src/haliax/_src/dot.py +++ b/src/haliax/_src/dot.py @@ -6,7 +6,6 @@ import functools as ft import typing import warnings -from typing import Dict, Optional, Tuple import jax @@ -29,11 +28,11 @@ from haliax.types import DTypeLike, PrecisionLike # deprecated overload @typing.overload def dot( - axis: Optional[AxisSelection], + axis: AxisSelection | None, *arrays: NamedArray, precision: PrecisionLike = None, - preferred_element_type: Optional[DTypeLike] = None, - out_axes: Optional[PartialAxisSpec] = ..., + preferred_element_type: DTypeLike | None = None, + out_axes: PartialAxisSpec | None = ..., dot_general=jax.lax.dot_general, ) -> NamedArray: ... @@ -41,10 +40,10 @@ def dot( @typing.overload def dot( *arrays: NamedArray, - axis: Optional[AxisSelection], + axis: AxisSelection | None, precision: PrecisionLike = None, - preferred_element_type: Optional[DTypeLike] = None, - out_axes: Optional[PartialAxisSpec] = ..., + preferred_element_type: DTypeLike | None = None, + out_axes: PartialAxisSpec | None = ..., dot_general=jax.lax.dot_general, ) -> NamedArray: ... @@ -52,8 +51,8 @@ def dot( def dot( *arrays, precision: PrecisionLike = None, - preferred_element_type: Optional[DTypeLike] = None, - out_axes: Optional[PartialAxisSpec] = None, + preferred_element_type: DTypeLike | None = None, + out_axes: PartialAxisSpec | None = None, dot_general=jax.lax.dot_general, **kwargs, ) -> NamedArray: @@ -82,7 +81,7 @@ def dot( which in turn passes it to jax.lax.dot_general. preferred_element_type (DTypeLike, optional): The preferred element type of the result. Defaults to None. This argument is passed to `jax.numpy.einsum`. - out_axes (Optional[PartialAxisSpec], optional): a potentially partial specification of the output axes. + out_axes (PartialAxisSpec | None, optional): a potentially partial specification of the output axes. If provided, the output will be transposed to match the provided axes. Defaults to None. @@ -107,8 +106,8 @@ def dot( # to call dot_general we need two things: # list of contractions and list of arrays - all_axes: Tuple[Axis, ...] = ft.reduce(union_axes, (a.axes for a in arrays), ()) # type: ignore - output_axes: Tuple[Axis, ...] + all_axes: tuple[Axis, ...] = ft.reduce(union_axes, (a.axes for a in arrays), ()) # type: ignore + output_axes: tuple[Axis, ...] if axis is None: # we want to contract over all the axes output_axes = () @@ -121,7 +120,7 @@ def dot( array_specs = [] next_index = 0 - axis_mappings: Dict[str, int] = {} + axis_mappings: dict[str, int] = {} for a in arrays: spec = "" diff --git a/src/haliax/_src/einsum.py b/src/haliax/_src/einsum.py index 27fe15a..2269a52 100644 --- a/src/haliax/_src/einsum.py +++ b/src/haliax/_src/einsum.py @@ -5,7 +5,6 @@ import functools from types import EllipsisType -from typing import Optional, Tuple import jax.lax @@ -24,7 +23,7 @@ def einsum( equation: str, *arrays: NamedArray, precision: PrecisionLike = None, - preferred_element_type: Optional[DTypeLike] = None, + preferred_element_type: DTypeLike | None = None, _dot_general: DotGeneralOp = jax.lax.dot_general, **axis_aliases: AxisSelector, ) -> NamedArray: @@ -306,7 +305,7 @@ def _all_input_axes(arrays): return ensure_tuple(functools.reduce(union_axes, (a.axes for a in arrays), ())) # type: ignore -def _captures_to_axis_names(equation, lhs, aliases) -> Tuple[list[str | EllipsisType], bool, set[str]]: +def _captures_to_axis_names(equation, lhs, aliases) -> tuple[list[str | EllipsisType], bool, set[str]]: covered_aliases = set() candidate_axes: list[str | EllipsisType] = [] has_ellipsis = False diff --git a/src/haliax/_src/parsing.py b/src/haliax/_src/parsing.py index a369e60..5628601 100644 --- a/src/haliax/_src/parsing.py +++ b/src/haliax/_src/parsing.py @@ -5,16 +5,16 @@ import dataclasses from types import EllipsisType -from typing import Mapping, NoReturn, Optional, Sequence +from typing import Mapping, NoReturn, Sequence from haliax.axis import Axis, AxisSelector @dataclasses.dataclass(frozen=True) class _AxisCapture: - binding: Optional[str] = None + binding: str | None = None axes: tuple[str, ...] = () - char_range: Optional[tuple[int, int]] = None + char_range: tuple[int, int] | None = None def __post_init__(self): if len(self.axes) == 0: @@ -27,7 +27,7 @@ class Expression: is_ordered: bool -def raise_parse_error(message: str, expression: str, pos: Optional[int | tuple[int, int]]) -> NoReturn: +def raise_parse_error(message: str, expression: str, pos: int | tuple[int, int] | None) -> NoReturn: """Raise a ValueError with a message and the position in the expression.""" fmt = f"Error while parsing:\n {expression}" if pos is not None: @@ -234,7 +234,7 @@ class AliasTable: else: self.bindings = {**bindings} - def dealias_binding(self, binding: str) -> Optional[AxisSelector]: + def dealias_binding(self, binding: str) -> AxisSelector | None: return self.bindings.get(binding, None) def bind_alias(self, alias: str, axis: Axis, expr, char_range): diff --git a/src/haliax/_src/rearrange.py b/src/haliax/_src/rearrange.py index 351ac96..9f2bae6 100644 --- a/src/haliax/_src/rearrange.py +++ b/src/haliax/_src/rearrange.py @@ -7,7 +7,7 @@ import dataclasses import typing from types import EllipsisType -from typing import Mapping, Optional, Sequence +from typing import Mapping, Sequence import jax.lax import jax.numpy as jnp @@ -157,7 +157,7 @@ def einops_rearrange(array: NamedArray, expression: str, **bindings: AxisSelecto @dataclasses.dataclass(frozen=True) class _Plan: intermediate_axes: tuple[Axis, ...] - transpose: Optional[tuple[int, ...]] + transpose: tuple[int, ...] | None needs_final_reshape: bool final_axes: tuple[Axis, ...] @@ -170,7 +170,7 @@ def _plan_rearrange( grouped_new_shapes = _determine_initial_reshape(original_str, lhs, array, aliases) intermediate_axes = tuple(ax for split_axes in grouped_new_shapes for ax in split_axes) - transpose: Optional[tuple[int, ...]] + transpose: tuple[int, ...] | None transpose, final_axes = _determine_final_transpose_and_reshape(original_str, rhs, aliases, intermediate_axes) transposed_intermediate_axes = tuple(intermediate_axes[i] for i in transpose) @@ -289,7 +289,7 @@ def _determine_initial_reshape( # the lhs all need to be bound to axes in the array, or synthesized as parts of axes. # In the lhs, bindings look like either a name, or a name and a list of (new) axes. # bindings can either be done by name, or by position, depending on if lhs.is_ordered - new_shapes: list[Optional[list[Axis]]] = [None] * len(array.axes) + new_shapes: list[list[Axis] | None] = [None] * len(array.axes) used_new_names: set[str] = set() # names can only be used once on a side # one subtle difference between the lhs and the rhs is the handling of binding in expressions like (a: b c) @@ -301,7 +301,7 @@ def _determine_initial_reshape( # if we start with an ellipsis, we bind from the right # if we end with an ellipsis, we bind from the left ellipsis_pos = None - axis_index_for_capture: list[Optional[int]] = [None] * len(lhs.captures) + axis_index_for_capture: list[int | None] = [None] * len(lhs.captures) covered_axes = set() # bind from the left axis_pos = 0 @@ -414,8 +414,8 @@ def _solve_split_axes(axis, capture, aliases, used_new_names, expression): """ Given an axis and a capture of the form (a: b c) or (b c) on the lhs, solve for the new axes. """ - new_axes: list[Optional[Axis]] = [] - unsolved_axis_index: Optional[int] = None + new_axes: list[Axis | None] = [] + unsolved_axis_index: int | None = None # easy case: 1 axis in capture if len(capture.axes) == 1: diff --git a/src/haliax/_src/scan.py b/src/haliax/_src/scan.py index 6cd8005..30a5cb4 100644 --- a/src/haliax/_src/scan.py +++ b/src/haliax/_src/scan.py @@ -2,11 +2,12 @@ # # SPDX-License-Identifier: Apache-2.0 +from __future__ import annotations import dataclasses import functools as ft import inspect -from typing import Any, Callable, Literal, ParamSpec, Protocol, Sequence, Tuple, TypeVar, Union, overload +from typing import Any, Callable, Literal, ParamSpec, Protocol, Sequence, TypeVar, overload import equinox as eqx import jax @@ -21,7 +22,7 @@ from haliax.core import NamedArray from haliax.jax_utils import is_jax_array_like, multilevel_scan, tree_checkpoint_name from haliax.util import is_jax_or_hax_array_like, is_named_array -BoolAxisSpec = Union[bool, Callable[[Any], bool]] +BoolAxisSpec = bool | Callable[[Any], bool] Carry = TypeVar("Carry") X = TypeVar("X", contravariant=True) Y = TypeVar("Y", covariant=True) @@ -170,7 +171,7 @@ class ScanCheckpointPolicy: raise ValueError(f"Invalid checkpoint policy {remat_policy}") @staticmethod - def _mk(remat_policy: Union[bool, str, "ScanCheckpointPolicy"]) -> "ScanCheckpointPolicy": + def _mk(remat_policy: bool | str | "ScanCheckpointPolicy") -> "ScanCheckpointPolicy": if isinstance(remat_policy, ScanCheckpointPolicy): return remat_policy else: @@ -253,7 +254,7 @@ class ScanCheckpointPolicy: return None -ScanCheckpointSpec = Union[ScanCheckpointPolicy, bool, Literal["offload", "recompute", "full", "save_all", "nested"]] +ScanCheckpointSpec = ScanCheckpointPolicy | bool | Literal["offload", "recompute", "full", "save_all", "nested"] @overload @@ -540,8 +541,8 @@ def map( return scanned_f -ResolvedUnnamedAxisSpec = Union[int, None] -UnnamedAxisSpec = Union[ResolvedUnnamedAxisSpec, Callable[[Any], ResolvedUnnamedAxisSpec]] +ResolvedUnnamedAxisSpec = int | None +UnnamedAxisSpec = ResolvedUnnamedAxisSpec | Callable[[Any], ResolvedUnnamedAxisSpec] def _zero_if_array_else_none(x: Any) -> ResolvedUnnamedAxisSpec: @@ -606,7 +607,7 @@ class _PassiveNamedArray: """ array: jax.numpy.ndarray - main_axes: Tuple[Axis, ...] + main_axes: tuple[Axis, ...] def as_scanned_result(self, scan_axis: Axis): return NamedArray(self.array, (scan_axis,) + self.main_axes) diff --git a/src/haliax/_src/state_dict.py b/src/haliax/_src/state_dict.py index 740b903..8eeffd1 100644 --- a/src/haliax/_src/state_dict.py +++ b/src/haliax/_src/state_dict.py @@ -6,7 +6,7 @@ # Module to support torch-style "state dict" serialization via safetensors import dataclasses import typing -from typing import Any, Optional, Sequence, TypeVar +from typing import Any, Sequence, TypeVar import equinox as eqx import jax @@ -36,7 +36,7 @@ T = TypeVar("T") def from_torch_compatible_state_dict( - t: T, state_dict: StateDict, *, unflatten: bool = True, prefix: Optional[str] = None + t: T, state_dict: StateDict, *, unflatten: bool = True, prefix: str | None = None ) -> T: """ Convert a state dict to a tree that is compatible with the structure of `t`. @@ -120,10 +120,10 @@ def with_prefix(prefix: str, leaf: None) -> str: ... @typing.overload -def with_prefix(prefix: Optional[str], leaf: Optional[str]) -> Optional[str]: ... +def with_prefix(prefix: str | None, leaf: str | None) -> str | None: ... -def with_prefix(prefix: Optional[str], leaf: Optional[str]) -> Optional[str]: +def with_prefix(prefix: str | None, leaf: str | None) -> str | None: """Joins two optional path strings in a way compatible with pytorch state dict serialization""" if prefix is None: return leaf @@ -136,13 +136,13 @@ def with_prefix(prefix: Optional[str], leaf: Optional[str]) -> Optional[str]: class ModuleWithStateDictSerialization(eqx.Module): """An eqx.Module that can be serialized to a torch-style state dict.""" - def to_state_dict(self, prefix: Optional[str] = None) -> StateDict: + def to_state_dict(self, prefix: str | None = None) -> StateDict: return default_eqx_module_to_state_dict(self, prefix) - def from_state_dict(self: Mod, state_dict: StateDict, prefix: Optional[str] = None) -> Mod: + def from_state_dict(self: Mod, state_dict: StateDict, prefix: str | None = None) -> Mod: return default_eqx_module_from_state_dict(self, state_dict, prefix) - def _state_dict_key_map(self) -> dict[str, Optional[str]]: + def _state_dict_key_map(self) -> dict[str, str | None]: """Returns a dict mapping eqx.Module keys to torch keys that need to be renamed for serialization""" return {} @@ -166,7 +166,7 @@ class ModuleWithStateDictSerialization(eqx.Module): return self -def from_state_dict(tree: T, state_dict: StateDict, prefix: Optional[str] = None) -> T: +def from_state_dict(tree: T, state_dict: StateDict, prefix: str | None = None) -> T: """ Given a (template) tree and a state dict, return a new tree with the same structure as the input tree, but with the values from the state dict. @@ -224,7 +224,7 @@ def from_state_dict(tree: T, state_dict: StateDict, prefix: Optional[str] = None return state_dict.get(prefix, tree) -def to_state_dict(tree: PyTree, prefix: Optional[str] = None) -> StateDict: +def to_state_dict(tree: PyTree, prefix: str | None = None) -> StateDict: """ Convert a PyTree to a state dict. @@ -276,8 +276,8 @@ def to_state_dict(tree: PyTree, prefix: Optional[str] = None) -> StateDict: return state_dict -def default_eqx_module_from_state_dict(mod: Mod, state_dict: StateDict, prefix: Optional[str] = None) -> Mod: - key_map: Dict[str, Optional[str]] = getattr(mod, "_state_dict_key_map", lambda: {})() # type: ignore +def default_eqx_module_from_state_dict(mod: Mod, state_dict: StateDict, prefix: str | None = None) -> Mod: + key_map: dict[str, str | None] = getattr(mod, "_state_dict_key_map", lambda: {})() # type: ignore names = [] values = [] for field in dataclasses.fields(mod): @@ -296,7 +296,7 @@ def default_eqx_module_from_state_dict(mod: Mod, state_dict: StateDict, prefix: return eqx.tree_at(lambda m: [getattr(m, name) for name in names], mod, values) -def default_eqx_module_to_state_dict(mod: eqx.Module, prefix: Optional[str] = None) -> StateDict: +def default_eqx_module_to_state_dict(mod: eqx.Module, prefix: str | None = None) -> StateDict: """ Convert an eqx.Module to a state dict. This is the default implementation of the to_state_dict method for eqx.Modules. It works by iterating over the fields of the module and calling to_state_dict on each field. @@ -308,7 +308,7 @@ def default_eqx_module_to_state_dict(mod: eqx.Module, prefix: Optional[str] = No """ state_dict: StateDict = {} - key_map: Dict[str, Optional[str]] = getattr(mod, "_state_dict_key_map", lambda: {})() # type: ignore + key_map: dict[str, str | None] = getattr(mod, "_state_dict_key_map", lambda: {})() # type: ignore for field in dataclasses.fields(mod): if field.metadata.get("static", False): continue @@ -320,7 +320,7 @@ def default_eqx_module_to_state_dict(mod: eqx.Module, prefix: Optional[str] = No return state_dict -def format_path_for_state_dict(prefix: Optional[str], path: Sequence) -> str: +def format_path_for_state_dict(prefix: str | None, path: Sequence) -> str: res = "".join(_format_key_path_element(path_elem) for path_elem in path) # res will have a . if prefix is not None: @@ -352,7 +352,7 @@ def _format_key_path_element(path_elem) -> str: return f".{path_elem}" -def to_numpy_state_dict(model, prefix: Optional[str] = None) -> StateDict: +def to_numpy_state_dict(model, prefix: str | None = None) -> StateDict: """ Convert a model to a state dict by first creating desharded copies of all parameters that reside in CPU memory. diff --git a/src/haliax/axis.py b/src/haliax/axis.py index b47a19a..a60429b 100644 --- a/src/haliax/axis.py +++ b/src/haliax/axis.py @@ -7,7 +7,7 @@ import typing from dataclasses import dataclass from math import prod from types import EllipsisType -from typing import List, Mapping, Optional, Sequence, Union, overload +from typing import Mapping, Sequence, overload import equinox as eqx @@ -46,17 +46,17 @@ def make_axes(**kwargs: int) -> tuple[Axis, ...]: return tuple(Axis(name, size) for name, size in kwargs.items()) -AxisSelector = Union[Axis, str] +AxisSelector = Axis | str """AxisSelector is a type that can be used to select a single axis from an array. str or Axis""" ShapeDict = Mapping[str, int] """ShapeDict is a type that can be used to specify the axes of an array, usually for creation or adding a new axis""" -PartialShapeDict = Mapping[str, Optional[int]] +PartialShapeDict = Mapping[str, int | None] """Similar to a AxisSelection, in dict form.""" -AxisSelection = Union[AxisSelector, Sequence[AxisSelector], PartialShapeDict] +AxisSelection = AxisSelector | Sequence[AxisSelector] | PartialShapeDict """AxisSelection is a type that can be used to select multiple axes from an array. str, Axis, or sequence of mixed str and Axis""" -AxisSpec = Union[Axis, Sequence[Axis], ShapeDict] +AxisSpec = Axis | Sequence[Axis] | ShapeDict """AxisSpec is a type that can be used to specify the axes of an array, usually for creation or adding a new axis whose size can't be determined another way. Axis or sequence of Axis""" @@ -115,11 +115,11 @@ def axis_spec_to_shape_dict(axis_spec: AxisSpec) -> dict[str, int]: # type: ign @overload -def axis_spec_to_shape_dict(axis_spec: AxisSelection) -> dict[str, Optional[int]]: # type: ignore +def axis_spec_to_shape_dict(axis_spec: AxisSelection) -> dict[str, int | None]: # type: ignore ... -def axis_spec_to_shape_dict(axis_spec: AxisSelection) -> dict[str, Optional[int]]: # type: ignore +def axis_spec_to_shape_dict(axis_spec: AxisSelection) -> dict[str, int | None]: # type: ignore if isinstance(axis_spec, Axis): return {axis_name(axis_spec): axis_spec.size} @@ -131,7 +131,7 @@ def axis_spec_to_shape_dict(axis_spec: AxisSelection) -> dict[str, Optional[int] spec = ensure_tuple(axis_spec) # type: ignore - shape_dict: dict[str, Optional[int]] = {} + shape_dict: dict[str, int | None] = {} for ax in spec: if isinstance(ax, Axis): shape_dict[ax.name] = ax.size @@ -383,7 +383,7 @@ def unsize_axes(axis_spec: PartialShapeDict) -> PartialShapeDict: ... def unsize_axes(axis_spec: AxisSelection) -> AxisSelection: ... -def unsize_axes(axis_spec: AxisSelection, to_unsize: Optional[AxisSelection] = None) -> AxisSelection: +def unsize_axes(axis_spec: AxisSelection, to_unsize: AxisSelection | None = None) -> AxisSelection: """ This function is used to remove the sizes of axes in an axis spec. There are two overloads: @@ -402,7 +402,7 @@ def unsize_axes(axis_spec: AxisSelection, to_unsize: Optional[AxisSelection] = N was_dict = isinstance(axis_spec, Mapping) to_unsize = axis_spec_to_shape_dict(to_unsize) - axis_spec_dict: dict[str, Optional[int]] = axis_spec_to_shape_dict(axis_spec) # type: ignore + axis_spec_dict: dict[str, int | None] = axis_spec_to_shape_dict(axis_spec) # type: ignore for ax in to_unsize: name = axis_name(ax) if name not in axis_spec_dict: @@ -478,7 +478,7 @@ def intersect_axes(ax1: AxisSelection, ax2: AxisSelection) -> AxisSelection: The returned order is the same as ax1. """ ax2_dict = axis_spec_to_shape_dict(ax2) - out: List[AxisSelector] = [] + out: list[AxisSelector] = [] was_dict = isinstance(ax1, Mapping) ax1_dict = axis_spec_to_shape_dict(ax1) @@ -507,7 +507,7 @@ def axis_name(ax: Sequence[AxisSelector]) -> tuple[str, ...]: # type: ignore ... -def axis_name(ax: AxisSelection) -> Union[str, tuple[str, ...]]: +def axis_name(ax: AxisSelection) -> str | tuple[str, ...]: """ Returns the name of the axis. If ax is a string, returns ax. If ax is an Axis, returns ax.name """ @@ -605,7 +605,7 @@ class dslice(eqx.Module): def to_slice(self) -> slice: return slice(self.start, self.start + self.size) - def __init__(self, start: int, length: Union[int, Axis]): + def __init__(self, start: int, length: int | Axis): """ As a convenience, if length is an Axis, it will be converted to `length.size` Args: @@ -722,7 +722,7 @@ def replace_missing_with_ellipsis(ax1: AxisSelection, ax2: AxisSelection) -> Par Raises if ax1 and ax2 have any axes with the same name but different sizes """ ax2_dict = axis_spec_to_shape_dict(ax2) - out: List[AxisSelector | EllipsisType] = [] + out: list[AxisSelector | EllipsisType] = [] ax1_dict = axis_spec_to_shape_dict(ax1) for ax, size in ax1_dict.items(): diff --git a/src/haliax/core.py b/src/haliax/core.py index 4bccd34..dc282f1 100644 --- a/src/haliax/core.py +++ b/src/haliax/core.py @@ -12,7 +12,7 @@ import warnings from dataclasses import dataclass from math import prod from types import EllipsisType -from typing import Any, Callable, Dict, List, Mapping, Optional, Sequence, Tuple, Union, overload +from typing import Any, Callable, Mapping, Sequence, TypeAlias, overload import jax import jax.numpy as jnp @@ -41,16 +41,20 @@ from .axis import ( ) from .types import GatherScatterModeStr, IntScalar, PrecisionLike, Scalar -NamedOrNumeric = Union[Scalar, "NamedArray"] -NamedIndex = Union[int, slice_t, "NamedArray", dslice, list[int], jnp.ndarray] - -SliceSpec = Union[ - tuple[AxisSelector, NamedIndex], - tuple[AxisSelector, NamedIndex, AxisSelector, NamedIndex], - tuple[AxisSelector, NamedIndex, AxisSelector, NamedIndex, AxisSelector, NamedIndex], - tuple[AxisSelector | NamedOrNumeric, ...], - Mapping[AxisSelector, NamedIndex], -] +if typing.TYPE_CHECKING: + NamedOrNumeric: TypeAlias = Scalar | "NamedArray" + NamedIndex: TypeAlias = int | slice_t | "NamedArray" | dslice | list[int] | jnp.ndarray +else: # pragma: no cover - runtime fallback to avoid evaluating forward refs + NamedOrNumeric = typing.Any # type: ignore[assignment] + NamedIndex = typing.Any # type: ignore[assignment] + +SliceSpec = ( + tuple[AxisSelector, NamedIndex] + | tuple[AxisSelector, NamedIndex, AxisSelector, NamedIndex] + | tuple[AxisSelector, NamedIndex, AxisSelector, NamedIndex, AxisSelector, NamedIndex] + | tuple[AxisSelector | NamedOrNumeric, ...] + | Mapping[AxisSelector, NamedIndex] +) _ENABLE_SHAPE_CHECKS = True @@ -82,10 +86,10 @@ def are_shape_checks_enabled(): class NamedArrayAxes: """Representation of a :class:`NamedArray`'s axes for type annotations.""" - before: Tuple[str, ...] + before: tuple[str, ...] """Names that must appear before any optional ellipsis.""" - after: Tuple[str, ...] = () + after: tuple[str, ...] = () """Names that must appear after any optional ellipsis.""" ordered: bool = True @@ -125,12 +129,7 @@ class NamedArrayAxes: # a specification for NamedArray axes used in type annotations -NamedArrayAxesSpec = Union[ - NamedArrayAxes, - str, - Sequence[str | EllipsisType], - set[str | EllipsisType], -] +NamedArrayAxesSpec = NamedArrayAxes | str | Sequence[str | EllipsisType] | set[str | EllipsisType] def _parse_namedarray_axes( @@ -156,7 +155,7 @@ def _parse_namedarray_axes( return NamedArrayAxes(tuple(parts), (), ordered=True, subset=False) if isinstance(item, set) or isinstance(item, frozenset): subset = False - names_list: List[str] = [] + names_list: list[str] = [] for part in item: if part is Ellipsis: if subset: @@ -169,8 +168,8 @@ def _parse_namedarray_axes( return NamedArrayAxes(tuple(names_list), (), ordered=False, subset=subset) if isinstance(item, (tuple, list)): subset = False - before_list: List[str] = [] - after_list: List[str] = [] + before_list: list[str] = [] + after_list: list[str] = [] cur_list = before_list for part in item: if part is Ellipsis: @@ -258,7 +257,7 @@ class NamedArray(metaclass=NamedArrayMeta): # ) @ft.cached_property - def shape(self) -> Dict[str, int]: + def shape(self) -> dict[str, int]: return {axis.name: axis.size for axis in self.axes} dtype = property(lambda self: self.array.dtype) @@ -329,10 +328,10 @@ class NamedArray(metaclass=NamedArrayMeta): ... @overload - def axis_size(self, axis: Sequence[AxisSelector]) -> Tuple[int, ...]: # type: ignore + def axis_size(self, axis: Sequence[AxisSelector]) -> tuple[int, ...]: # type: ignore ... - def axis_size(self, axis: AxisSelection) -> Union[int, Tuple[int, ...]]: + def axis_size(self, axis: AxisSelection) -> int | tuple[int, ...]: """ Returns the size of the given axis, or a tuple of sizes if given multiple axes. """ @@ -414,13 +413,13 @@ class NamedArray(metaclass=NamedArrayMeta): return pp.text(str(self)) @overload - def _lookup_indices(self, axis: AxisSelector) -> Optional[int]: # type: ignore + def _lookup_indices(self, axis: AxisSelector) -> int | None: # type: ignore ... @overload - def _lookup_indices(self, axis: AxisSelection) -> Tuple[Optional[int], ...]: ... + def _lookup_indices(self, axis: AxisSelection) -> tuple[int | None, ...]: ... - def _lookup_indices(self, axis: AxisSelection) -> Union[Optional[int], Tuple[Optional[int], ...]]: + def _lookup_indices(self, axis: AxisSelection) -> int | None | tuple[int | None, ...]: """ For a single axis, returns an int corresponding to the index of the axis. For multiple axes, returns a tuple of ints corresponding to the indices of the axes. @@ -434,16 +433,16 @@ class NamedArray(metaclass=NamedArrayMeta): return self.axis_indices(axis) @overload - def axis_indices(self, axis: AxisSelector) -> Optional[int]: # type: ignore + def axis_indices(self, axis: AxisSelector) -> int | None: # type: ignore ... @overload - def axis_indices(self, axis: Sequence[AxisSelector]) -> Tuple[Optional[int], ...]: ... + def axis_indices(self, axis: Sequence[AxisSelector]) -> tuple[int | None, ...]: ... @overload - def axis_indices(self, axis: AxisSelection) -> Tuple[Optional[int], ...]: ... + def axis_indices(self, axis: AxisSelection) -> tuple[int | None, ...]: ... - def axis_indices(self, axis: AxisSelection) -> Union[Optional[int], Tuple[Optional[int], ...]]: + def axis_indices(self, axis: AxisSelection) -> int | None | tuple[int | None, ...]: """ For a single axis, returns an int corresponding to the index of the axis. For multiple axes, returns a tuple of ints corresponding to the indices of the axes. @@ -517,23 +516,21 @@ class NamedArray(metaclass=NamedArrayMeta): # slicing @typing.overload def slice( - self, axis: AxisSelector, new_axis: Optional[AxisSelector] = None, start: int = 0, length: Optional[int] = None + self, axis: AxisSelector, new_axis: AxisSelector | None = None, start: int = 0, length: int | None = None ) -> "NamedArray": ... @typing.overload - def slice( - self, start: Mapping[AxisSelector, int], length: Mapping[AxisSelector, Union[int, Axis]] - ) -> "NamedArray": ... + def slice(self, start: Mapping[AxisSelector, int], length: Mapping[AxisSelector, int | Axis]) -> "NamedArray": ... def slice(self, *args, **kwargs) -> "NamedArray": # pragma: no cover return haliax.slice(self, *args, **kwargs) def updated_slice( - self, start: Mapping[AxisSelector, Union[int, "NamedArray"]], update: "NamedArray" + self, start: Mapping[AxisSelector, int | "NamedArray"], update: "NamedArray" ) -> "NamedArray": # pragma: no cover return haliax.updated_slice(self, start=start, update=update) - def take(self, axis: AxisSelector, index: Union[int, "NamedArray"]) -> "NamedArray": # pragma: no cover + def take(self, axis: AxisSelector, index: int | "NamedArray") -> "NamedArray": # pragma: no cover return haliax.take(self, axis=axis, index=index) @property @@ -608,19 +605,19 @@ class NamedArray(metaclass=NamedArrayMeta): # np.ndarray methods: def all( - self, axis: Optional[AxisSelection] = None, *, where: Optional["NamedArray"] = None + self, axis: AxisSelection | None = None, *, where: "NamedArray" | None = None ) -> "NamedArray": # pragma: no cover return haliax.all(self, axis=axis, where=where) def any( - self, axis: Optional[AxisSelection] = None, *, where: Optional["NamedArray"] = None + self, axis: AxisSelection | None = None, *, where: "NamedArray" | None = None ) -> "NamedArray": # pragma: no cover return haliax.any(self, axis=axis, where=where) - def argmax(self, axis: Optional[AxisSelector] = None) -> "NamedArray": # pragma: no cover + def argmax(self, axis: AxisSelector | None = None) -> "NamedArray": # pragma: no cover return haliax.argmax(self, axis=axis) - def argmin(self, axis: Optional[AxisSelector]) -> "NamedArray": # pragma: no cover + def argmin(self, axis: AxisSelector | None) -> "NamedArray": # pragma: no cover return haliax.argmin(self, axis=axis) def argsort(self, axis: AxisSelector | None, *, stable: bool = False) -> "NamedArray": # pragma: no cover @@ -650,14 +647,14 @@ class NamedArray(metaclass=NamedArrayMeta): # Deprecated overload @typing.overload def dot( - self, axis: Optional[AxisSelection], *b, precision: PrecisionLike = None, dot_general=jax.lax.dot_general + self, axis: AxisSelection | None, *b, precision: PrecisionLike = None, dot_general=jax.lax.dot_general ) -> "NamedArray": ... @typing.overload def dot( self, *args: "NamedArray", - axis: Optional[AxisSelection], + axis: AxisSelection | None, precision: PrecisionLike = None, dot_general=jax.lax.dot_general, ) -> "NamedArray": ... @@ -675,30 +672,30 @@ class NamedArray(metaclass=NamedArrayMeta): def imag(self) -> "NamedArray": # pragma: no cover return NamedArray(self.array.imag, self.axes) - def max(self, axis: Optional[AxisSelection] = None, *, where=None) -> "NamedArray": # pragma: no cover + def max(self, axis: AxisSelection | None = None, *, where=None) -> "NamedArray": # pragma: no cover return haliax.max(self, axis=axis, where=where) def mean( - self, axis: Optional[AxisSelection] = None, *, dtype=None, where: Optional["NamedArray"] = None + self, axis: AxisSelection | None = None, *, dtype=None, where: "NamedArray" | None = None ) -> "NamedArray": # pragma: no cover return haliax.mean(self, axis=axis, dtype=dtype, where=where) def min( - self, axis: Optional[AxisSelection] = None, *, where: Optional["NamedArray"] = None + self, axis: AxisSelection | None = None, *, where: "NamedArray" | None = None ) -> "NamedArray": # pragma: no cover return haliax.min(self, axis=axis, where=where) def prod( - self, axis: Optional[AxisSelection] = None, *, dtype=None, where: Optional["NamedArray"] = None + self, axis: AxisSelection | None = None, *, dtype=None, where: "NamedArray" | None = None ) -> "NamedArray": # pragma: no cover return haliax.prod(self, axis=axis, dtype=dtype, where=where) def product( - self, axis: Optional[AxisSelection] = None, *, dtype=None, where: Optional["NamedArray"] = None + self, axis: AxisSelection | None = None, *, dtype=None, where: "NamedArray" | None = None ) -> "NamedArray": # pragma: no cover return haliax.product(self, axis=axis, dtype=dtype, where=where) - def ptp(self, axis: Optional[AxisSelection] = None) -> "NamedArray": # pragma: no cover + def ptp(self, axis: AxisSelection | None = None) -> "NamedArray": # pragma: no cover return haliax.ptp(self, axis=axis) @property @@ -712,12 +709,12 @@ class NamedArray(metaclass=NamedArrayMeta): return haliax.sort(self, axis=axis) def std( - self, axis: Optional[AxisSelection] = None, *, dtype=None, ddof=0, where: Optional["NamedArray"] = None + self, axis: AxisSelection | None = None, *, dtype=None, ddof=0, where: "NamedArray" | None = None ) -> "NamedArray": # pragma: no cover return haliax.std(self, axis=axis, dtype=dtype, ddof=ddof, where=where) def sum( - self, axis: Optional[AxisSelection] = None, *, dtype=None, where: Optional["NamedArray"] = None + self, axis: AxisSelection | None = None, *, dtype=None, where: "NamedArray" | None = None ) -> "NamedArray": # pragma: no cover return haliax.sum( self, @@ -738,7 +735,7 @@ class NamedArray(metaclass=NamedArrayMeta): return haliax.trace(self, offset=offset, axis1=axis1, axis2=axis2, dtype=dtype) def var( - self, axis: Optional[AxisSelection] = None, dtype=None, ddof=0, *, where: Optional["NamedArray"] = None + self, axis: AxisSelection | None = None, dtype=None, ddof=0, *, where: "NamedArray" | None = None ) -> "NamedArray": # pragma: no cover return haliax.var(self, axis=axis, dtype=dtype, ddof=ddof, where=where) @@ -884,7 +881,7 @@ class NamedArray(metaclass=NamedArrayMeta): return float(self.array) -def take(array: NamedArray, axis: AxisSelector, index: Union[int, NamedArray]) -> NamedArray: +def take(array: NamedArray, axis: AxisSelector, index: int | NamedArray) -> NamedArray: """ Selects elements from an array along an axis, by an index or by another named array @@ -939,9 +936,9 @@ def take(array: NamedArray, axis: AxisSelector, index: Union[int, NamedArray]) - def slice( array: NamedArray, axis: AxisSelector, - new_axis: Optional[AxisSelector] = None, + new_axis: AxisSelector | None = None, start: int = 0, - length: Optional[int] = None, + length: int | None = None, ) -> NamedArray: pass @@ -950,13 +947,13 @@ def slice( def slice( array: NamedArray, start: Mapping[AxisSelector, IntScalar], - length: Optional[Mapping[AxisSelector, int]] = None, + length: Mapping[AxisSelector, int] | None = None, ) -> NamedArray: """ Slices the array along the specified axes, replacing them with new axes (or a shortened version of the old one) Args: - start (Mapping[AxisSelector, Union[int, jnp.ndarray]]): the start index of each axis to slice. If an int, the axis will be sliced at that index. If a NamedArray, the axis will be sliced at the indices in the NamedArray + start (Mapping[AxisSelector, int | jnp.ndarray]): the start index of each axis to slice. If an int, the axis will be sliced at that index. If a NamedArray, the axis will be sliced at the indices in the NamedArray length (Mapping[AxisSelector, int]): the length of the dimension for that slice. """ pass @@ -988,9 +985,9 @@ def slice(array: NamedArray, *args, **kwargs) -> NamedArray: def _slice_old( array: NamedArray, axis: AxisSelector, - new_axis: Optional[AxisSelector] = None, + new_axis: AxisSelector | None = None, start: int = 0, - length: Optional[int] = None, + length: int | None = None, ) -> NamedArray: """ Selects elements from an array along an axis, either by an index or by another named array. @@ -1031,8 +1028,8 @@ def _slice_old( def _slice_new( array: NamedArray, - start: Mapping[AxisSelector, Union[int, jnp.ndarray]], - length: Mapping[AxisSelector, Union[int, Axis]], + start: Mapping[AxisSelector, int | jnp.ndarray], + length: Mapping[AxisSelector, int | Axis], ) -> NamedArray: array_slice_indices = [0] * len(array.axes) new_axes = list(array.axes) @@ -1070,14 +1067,14 @@ def _slice_new( def updated_slice( - array: NamedArray, start: Mapping[AxisSelector, Union[int, jnp.ndarray, NamedArray]], update: NamedArray + array: NamedArray, start: Mapping[AxisSelector, int | jnp.ndarray | NamedArray], update: NamedArray ) -> NamedArray: """ Updates a slice of an array with another array. Args: array (NamedArray): The array to update. - start (Mapping[AxisSelector, Union[int, jnp.ndarray]]): The starting index of each axis to update. + start (Mapping[AxisSelector, int | jnp.ndarray]): The starting index of each axis to update. update (NamedArray): The array to update with. Returns: @@ -1354,7 +1351,7 @@ def split(a: NamedArray, axis: AxisSelector, new_axes: Sequence[Axis]) -> Sequen return [NamedArray(x, ax) for x, ax in zip(new_arrays, ret_axes)] -def unbind(array: NamedArray, axis: AxisSelector) -> List[NamedArray]: +def unbind(array: NamedArray, axis: AxisSelector) -> list[NamedArray]: """ Unbind an array along an axis, returning a list of NamedArrays, one for each position on that axis. Analogous to torch.unbind or np.rollaxis @@ -1374,13 +1371,13 @@ def unbind(array: NamedArray, axis: AxisSelector) -> List[NamedArray]: def roll( array: NamedArray, - shift: Union[IntScalar, Tuple[int, ...], "NamedArray"], + shift: IntScalar | tuple[int, ...] | "NamedArray", axis: AxisSelection, ) -> NamedArray: """Roll an array along an axis or axes. ``shift`` may be a scalar ``NamedArray`` in addition to an ``int`` or tuple of - integers. + integers. Analogous to np.roll """ axis_indices = array.axis_indices(axis) @@ -1504,8 +1501,8 @@ def _full_flatten( # ensure that the old_axes are contiguous # we basically ensure that the old_axes occur after the index of the first old_axis - intermediate_axes: List[Axis] = [] - new_axes: List[Axis] = [] + intermediate_axes: list[Axis] = [] + new_axes: list[Axis] = [] index_of_first_old_axis = None for i, ax in enumerate(array.axes): if ax in old_axes: @@ -1542,8 +1539,8 @@ def _flatten_axis_spec(axes: AxisSpec, old_axes: AxisSelection, new_axis: AxisSe # ensure that the old_axes are contiguous # we basically ensure that the old_axes occur after the index of the first old_axis - intermediate_axes: List[Axis] = [] - new_axes: List[Axis] = [] + intermediate_axes: list[Axis] = [] + new_axes: list[Axis] = [] index_of_first_old_axis = None for i, ax in enumerate(axes): if ax in old_axes: # type: ignore @@ -1614,7 +1611,7 @@ def named(a, axis: AxisSelection) -> NamedArray: # Broadcasting Support -def _broadcast_order(a: NamedArray, b: NamedArray, require_subset: bool = True) -> Tuple[Axis, ...]: +def _broadcast_order(a: NamedArray, b: NamedArray, require_subset: bool = True) -> tuple[Axis, ...]: """ Returns an ordering of axes for broadcasting a and b. @@ -1634,8 +1631,8 @@ def _broadcast_order(a: NamedArray, b: NamedArray, require_subset: bool = True) def _broadcast_axes( - a_axes: Tuple[Axis, ...], b_axes: Tuple[Axis, ...], require_subset: bool = True -) -> Optional[Tuple[Axis, ...]]: + a_axes: tuple[Axis, ...], b_axes: tuple[Axis, ...], require_subset: bool = True +) -> tuple[Axis, ...] | None: if a_axes == b_axes: return a_axes if len(a_axes) == 0: @@ -1743,20 +1740,20 @@ def _is_subsequence(needle, haystack): @overload def broadcast_arrays( *arrays: NamedArray, require_subset: bool = True, ensure_order: bool = True -) -> Tuple[NamedArray, ...]: ... +) -> tuple[NamedArray, ...]: ... @overload def broadcast_arrays( - *arrays: Optional[NamedOrNumeric], require_subset: bool = True, ensure_order: bool = True -) -> Tuple[Optional[NamedOrNumeric], ...]: ... + *arrays: NamedOrNumeric | None, require_subset: bool = True, ensure_order: bool = True +) -> tuple[NamedOrNumeric | None, ...]: ... def broadcast_arrays( - *arrays: Optional[NamedOrNumeric], + *arrays: NamedOrNumeric | None, require_subset: bool = True, ensure_order: bool = True, -) -> Tuple[Optional[NamedOrNumeric], ...]: +) -> tuple[NamedOrNumeric | None, ...]: """ Broadcasts a sequence of arrays to a common set of axes. Args: @@ -1777,26 +1774,26 @@ def broadcast_arrays( @overload def broadcast_arrays_and_return_axes( *arrays: NamedArray, require_subset: bool = True, ensure_order: bool = True -) -> Tuple[Tuple[NamedArray, ...], Tuple[Axis, ...]]: ... +) -> tuple[tuple[NamedArray, ...], tuple[Axis, ...]]: ... @overload def broadcast_arrays_and_return_axes( *arrays: NamedOrNumeric, require_subset: bool = True, ensure_order: bool = True -) -> Tuple[Tuple[NamedOrNumeric, ...], Tuple[Axis, ...]]: ... +) -> tuple[tuple[NamedOrNumeric, ...], tuple[Axis, ...]]: ... @overload def broadcast_arrays_and_return_axes( - *arrays: Optional[NamedOrNumeric], require_subset: bool = True, ensure_order: bool = True -) -> Tuple[Tuple[Optional[NamedOrNumeric], ...], Tuple[Axis, ...]]: ... + *arrays: NamedOrNumeric | None, require_subset: bool = True, ensure_order: bool = True +) -> tuple[tuple[NamedOrNumeric | None, ...], tuple[Axis, ...]]: ... def broadcast_arrays_and_return_axes( - *arrays: Optional[NamedOrNumeric], + *arrays: NamedOrNumeric | None, require_subset: bool = True, ensure_order: bool = True, -) -> Tuple[Tuple[Optional[NamedOrNumeric], ...], Tuple[Axis, ...]]: +) -> tuple[tuple[NamedOrNumeric | None, ...], tuple[Axis, ...]]: """ Broadcasts a sequence of arrays to a common set of axes. @@ -1855,12 +1852,12 @@ def broadcast_axis(a: NamedArray, axis: AxisSpec) -> NamedArray: return broadcast_to(a, axis, enforce_no_extra_axes=False, ensure_order=True) -def check_shape(jnp_shape: Sequence[int], hax_axes: AxisSelection) -> Tuple[Axis, ...]: +def check_shape(jnp_shape: Sequence[int], hax_axes: AxisSelection) -> tuple[Axis, ...]: """Check that the shape of a jax array matches the axes of a NamedArray""" axes = axis_spec_to_tuple(hax_axes) if len(jnp_shape) != len(axes): raise ValueError(f"Shape mismatch: jnp_shape={jnp_shape} hax_axes={hax_axes}") - result_axes: List[Axis] = [] + result_axes: list[Axis] = [] for i in range(len(axes)): ax = axes[i] if isinstance(ax, Axis): @@ -1935,8 +1932,8 @@ class _NamedIndexUpdateRef: *, indices_are_sorted: bool = False, unique_indices: bool = False, - mode: Optional[GatherScatterModeStr] = None, - fill_value: Optional[Scalar] = None, + mode: GatherScatterModeStr | None = None, + fill_value: Scalar | None = None, ) -> NamedArray: slices, sliced_axes = _raw_indices_for_at(self._array, self._slices) new_array = self._array.array.at[tuple(slices)].get( @@ -1950,7 +1947,7 @@ class _NamedIndexUpdateRef: *, indices_are_sorted: bool = False, unique_indices: bool = False, - mode: Optional[GatherScatterModeStr] = None, + mode: GatherScatterModeStr | None = None, ) -> NamedArray: slices, sliced_axes = _raw_indices_for_at(self._array, self._slices) update = haliax.broadcast_to(update, sliced_axes, enforce_no_extra_axes=True) @@ -1965,7 +1962,7 @@ class _NamedIndexUpdateRef: *, indices_are_sorted: bool = False, unique_indices: bool = False, - mode: Optional[GatherScatterModeStr] = None, + mode: GatherScatterModeStr | None = None, ) -> NamedArray: slices, sliced_axes = _raw_indices_for_at(self._array, self._slices) update = haliax.broadcast_to(update, sliced_axes, enforce_no_extra_axes=True) @@ -1980,7 +1977,7 @@ class _NamedIndexUpdateRef: *, indices_are_sorted: bool = False, unique_indices: bool = False, - mode: Optional[GatherScatterModeStr] = None, + mode: GatherScatterModeStr | None = None, ) -> NamedArray: slices, sliced_axes = _raw_indices_for_at(self._array, self._slices) @@ -1996,7 +1993,7 @@ class _NamedIndexUpdateRef: *, indices_are_sorted: bool = False, unique_indices: bool = False, - mode: Optional[GatherScatterModeStr] = None, + mode: GatherScatterModeStr | None = None, ) -> NamedArray: slices, sliced_axes = _raw_indices_for_at(self._array, self._slices) update = haliax.broadcast_to(update, sliced_axes, enforce_no_extra_axes=True) @@ -2011,7 +2008,7 @@ class _NamedIndexUpdateRef: *, indices_are_sorted: bool = False, unique_indices: bool = False, - mode: Optional[GatherScatterModeStr] = None, + mode: GatherScatterModeStr | None = None, ) -> NamedArray: slices, sliced_axes = _raw_indices_for_at(self._array, self._slices) update = haliax.broadcast_to(update, sliced_axes, enforce_no_extra_axes=True) @@ -2026,7 +2023,7 @@ class _NamedIndexUpdateRef: *, indices_are_sorted: bool = False, unique_indices: bool = False, - mode: Optional[GatherScatterModeStr] = None, + mode: GatherScatterModeStr | None = None, ) -> NamedArray: slices, sliced_axes = _raw_indices_for_at(self._array, self._slices) update = haliax.broadcast_to(update, sliced_axes, enforce_no_extra_axes=True) @@ -2041,7 +2038,7 @@ class _NamedIndexUpdateRef: *, indices_are_sorted: bool = False, unique_indices: bool = False, - mode: Optional[GatherScatterModeStr] = None, + mode: GatherScatterModeStr | None = None, ) -> NamedArray: slices, sliced_axes = _raw_indices_for_at(self._array, self._slices) update = haliax.broadcast_to(update, sliced_axes, enforce_no_extra_axes=True) @@ -2056,7 +2053,7 @@ class _NamedIndexUpdateRef: *, indices_are_sorted: bool = False, unique_indices: bool = False, - mode: Optional[GatherScatterModeStr] = None, + mode: GatherScatterModeStr | None = None, ) -> NamedArray: slices, sliced_axes = _raw_indices_for_at(self._array, self._slices) update = haliax.broadcast_to(update, sliced_axes, enforce_no_extra_axes=True) @@ -2071,7 +2068,7 @@ class _NamedIndexUpdateRef: *, indices_are_sorted: bool = False, unique_indices: bool = False, - mode: Optional[GatherScatterModeStr] = None, + mode: GatherScatterModeStr | None = None, ) -> NamedArray: # It's not really documented, but func can be any callable that takes a scalar array and returns a scalar array slices, sliced_axes = _raw_indices_for_at(self._array, self._slices) diff --git a/src/haliax/debug.py b/src/haliax/debug.py index b3ed1a6..6430331 100644 --- a/src/haliax/debug.py +++ b/src/haliax/debug.py @@ -4,7 +4,7 @@ import dataclasses -from typing import List, Tuple, Union, Sequence +from typing import Sequence, TypeAlias import equinox as eqx import jax @@ -18,7 +18,7 @@ from haliax.util import is_jax_or_hax_array_like from ._src.util import IdentityMap -ArrayLike = Union[jnp.ndarray, NamedArray] +ArrayLike: TypeAlias = jnp.ndarray | NamedArray def describe_array(arr): @@ -30,8 +30,8 @@ def describe_array(arr): class ModuleProblems(Exception): def __init__(self): - self.reused_arrays: List[Tuple[ArrayLike, List]] = [] - self.static_arrays: List[str] = [] + self.reused_arrays: list[tuple[ArrayLike, list[str]]] = [] + self.static_arrays: list[str] = [] def __bool__(self): return bool(self.reused_arrays or self.static_arrays) @@ -86,7 +86,7 @@ def diagnose_common_issues(module: eqx.Module): def _check_for_reused_arrays(problems, module): - used_arrays = IdentityMap[ArrayLike, List[str]]() + used_arrays = IdentityMap[ArrayLike, list[str]]() path_leaves, _ = jtu.tree_flatten_with_path(module, is_leaf=is_jax_or_hax_array_like) diff --git a/src/haliax/jax_utils.py b/src/haliax/jax_utils.py index d7a1caa..6334b3f 100644 --- a/src/haliax/jax_utils.py +++ b/src/haliax/jax_utils.py @@ -6,7 +6,7 @@ import functools as ft import typing import warnings -from typing import Any, Callable, Optional, Sequence, Union +from typing import Any, Callable, Sequence import equinox as eqx import jax @@ -39,7 +39,7 @@ class Static(eqx.Module): value: Any = eqx.field(static=True) -def shaped_rng_split(key, split_shape: Union[int, Sequence[int]] = 2) -> PRNGKeyArray: +def shaped_rng_split(key, split_shape: int | Sequence[int] = 2) -> PRNGKeyArray: if isinstance(split_shape, int): num_splits = split_shape split_shape = (num_splits,) + key.shape @@ -54,7 +54,7 @@ def shaped_rng_split(key, split_shape: Union[int, Sequence[int]] = 2) -> PRNGKey return jnp.reshape(unshaped, split_shape) -def maybe_rng_split(key: Optional[PRNGKeyArray], num: int = 2): +def maybe_rng_split(key: PRNGKeyArray | None, num: int = 2): """Splits a random key into multiple random keys. If the key is None, then it replicates the None. Also handles num == 1 case""" if key is None: @@ -73,7 +73,7 @@ def filter_eval_shape(*args, **kwargs): return eqx.filter_eval_shape(*args, **kwargs) -def filter_checkpoint(fun: Callable, *, prevent_cse: bool = True, policy: Optional[Callable[..., bool]] = None): +def filter_checkpoint(fun: Callable, *, prevent_cse: bool = True, policy: Callable[..., bool] | None = None): """As `jax.checkpoint`, but allows any Python object as inputs and outputs""" warnings.warn("filter_checkpoint is deprecated, use eqx.filter_checkpoint instead", DeprecationWarning) @@ -86,7 +86,7 @@ def is_jax_array_like(x): # adapted from jax but exposed so i can use it -def broadcast_prefix(prefix_tree: Any, full_tree: Any, is_leaf: Optional[Callable[[Any], bool]] = None): +def broadcast_prefix(prefix_tree: Any, full_tree: Any, is_leaf: Callable[[Any], bool] | None = None): """Broadcast a prefix tree to match the structure of a full tree.""" result = [] num_leaves = lambda t: jax.tree_util.tree_structure(t).num_leaves # noqa: E731 @@ -110,14 +110,14 @@ def _UNSPECIFIED(): @typing.overload -def named_call(f: F, name: Optional[str] = None) -> F: ... +def named_call(f: F, name: str | None = None) -> F: ... @typing.overload -def named_call(*, name: Optional[str] = None) -> Callable[[F], F]: ... +def named_call(*, name: str | None = None) -> Callable[[F], F]: ... -def named_call(f=_UNSPECIFIED, name: Optional[str] = None): +def named_call(f=_UNSPECIFIED, name: str | None = None): if f is _UNSPECIFIED: return lambda f: named_call(f, name) # type: ignore else: diff --git a/src/haliax/nn/attention.py b/src/haliax/nn/attention.py index 8f780ca..bab0fb7 100644 --- a/src/haliax/nn/attention.py +++ b/src/haliax/nn/attention.py @@ -4,7 +4,6 @@ import math -from typing import List, Optional import jax import jax.numpy as jnp @@ -32,11 +31,11 @@ def dot_product_attention_weights( KPos: AxisSelection, query: NamedArray, key: NamedArray, - mask: Optional[NamedArray] = None, - bias: Optional[NamedArray] = None, - attention_dtype: Optional[jnp.dtype] = None, + mask: NamedArray | None = None, + bias: NamedArray | None = None, + attention_dtype: jnp.dtype | None = None, precision: PrecisionLike = None, - scaling_factor: Optional[float] = None, + scaling_factor: float | None = None, ) -> NamedArray: """ NamedArray version of dot product attention. Computes the logits for the attention weights. Note that the @@ -46,8 +45,8 @@ def dot_product_attention_weights( :param KPos: Axis or axes that are attended to :param query: NamedArray of shape (QPos, KeySize) :param key: NamedArray of shape (KPos, KeySize) - :param mask: Optional[NamedArray] broadcast compatible with (KeySize, QPos, KPos). Should be boolean - :param bias: Optional[NamedArray] broadcast compatible with (KeySize, QPos, KPos). Should be float + :param mask: NamedArray | None broadcast compatible with (KeySize, QPos, KPos). Should be boolean + :param bias: NamedArray | None broadcast compatible with (KeySize, QPos, KPos). Should be float :param attention_dtype: Optional dtype to use for attention :param precision: PrecisionLike for dot product. See precision argument to jax.lax.dot_general :param scaling_factor: Optional float as scaling factor for attention score. Default to 1/sqrt(D) @@ -83,9 +82,9 @@ def dot_product_attention( query: NamedArray, key: NamedArray, value: NamedArray, - mask: Optional[NamedArray] = None, - bias: Optional[NamedArray] = None, - attention_dtype: Optional[jnp.dtype] = None, + mask: NamedArray | None = None, + bias: NamedArray | None = None, + attention_dtype: jnp.dtype | None = None, precision: PrecisionLike = None, ) -> NamedArray: """ @@ -96,8 +95,8 @@ def dot_product_attention( :param query: NamedArray of shape {..., QPos, KeySize} :param key: NamedArray of shape {..., KPos, KeySize} :param value: NamedArray of shape {..., KPos, KeySize} - :param mask: Optional[NamedArray] broadcast compatible with (KeySize, QPos, KPos). Should be boolean - :param bias: Optional[NamedArray] broadcast compatible with (KeySize, QPos, KPos). Should be float + :param mask: NamedArray | None broadcast compatible with (KeySize, QPos, KPos). Should be boolean + :param bias: NamedArray | None broadcast compatible with (KeySize, QPos, KPos). Should be float :param attention_dtype: Optional dtype to use for attention :param precision: PrecisionLike for dot product. See precision argument to jax.lax.dot_general :return: NamedArray of shape (QPos, KeySize) @@ -143,7 +142,7 @@ def mask_to_bias(mask: NamedArray, mask_value: float = -1e9) -> NamedArray: return mask * mask_value -def combine_masks_and(mask1: Optional[NamedArray], mask2: Optional[NamedArray]) -> Optional[NamedArray]: +def combine_masks_and(mask1: NamedArray | None, mask2: NamedArray | None) -> NamedArray | None: if mask1 is None: return mask2 if mask2 is None: @@ -151,7 +150,7 @@ def combine_masks_and(mask1: Optional[NamedArray], mask2: Optional[NamedArray]) return mask1 & mask2.broadcast_axis(mask1.axes) -def combine_masks_or(mask1: Optional[NamedArray], mask2: Optional[NamedArray]) -> Optional[NamedArray]: +def combine_masks_or(mask1: NamedArray | None, mask2: NamedArray | None) -> NamedArray | None: if mask1 is None: return mask2 if mask2 is None: @@ -225,7 +224,7 @@ def forgetful_causal_mask(KPos: Axis, mask_prob: float, sample_prob: bool = True return base | zeroth_on -def _get_alibi_slopes(heads: int, bias_max: float) -> List[float]: +def _get_alibi_slopes(heads: int, bias_max: float) -> list[float]: # Mosaic supports "bias_max" log_bias_max = math.log2(bias_max) # from https://github.com/ofirpress/attention_with_linear_biases/blob/a35aaca144e0eb6b789dfcb46784c4b8e31b7983/fairseq/models/transformer.py#L742 diff --git a/src/haliax/nn/conv.py b/src/haliax/nn/conv.py index 31876fb..1143c40 100644 --- a/src/haliax/nn/conv.py +++ b/src/haliax/nn/conv.py @@ -5,7 +5,7 @@ import string from functools import cached_property -from typing import Optional, Sequence, TypeVar +from typing import Sequence, TypeVar import equinox as eqx import jax @@ -41,7 +41,7 @@ class _ConvBase(eqx.Module): In: Axis = eqx.field(static=True) Out: Axis = eqx.field(static=True) weight: NamedArray = eqx.field() - bias: Optional[NamedArray] = eqx.field() + bias: NamedArray | None = eqx.field() def _lhs_dim_spec(self, batch_index, inputs): # the dim spec are single letters, for things like NCHW @@ -165,7 +165,7 @@ class Conv(_ConvBase): return Conv(Spatial, In, Out, weight, bias, kernel_size, stride, padding, dilation, groups) @named_call - def __call__(self, inputs, *, key: Optional[PRNGKeyArray] = None): + def __call__(self, inputs, *, key: PRNGKeyArray | None = None): """ Args: inputs (NamedArray): Input array @@ -321,7 +321,7 @@ class ConvTranspose(_ConvBase): ) @named_call - def __call__(self, inputs, *, key: Optional[PRNGKeyArray] = None): + def __call__(self, inputs, *, key: PRNGKeyArray | None = None): """ Args: inputs (NamedArray): Input array diff --git a/src/haliax/nn/dropout.py b/src/haliax/nn/dropout.py index b04f4ed..1dab519 100644 --- a/src/haliax/nn/dropout.py +++ b/src/haliax/nn/dropout.py @@ -3,8 +3,6 @@ # SPDX-License-Identifier: Apache-2.0 -from typing import Optional - import equinox as eqx import jax from jaxtyping import PRNGKeyArray @@ -67,13 +65,13 @@ class Dropout(eqx.Module): # key difference from equinox: these are static fields pdrop: float = eqx.field(static=True) - broadcast_axes: Optional[AxisSpec] = eqx.field(static=True) + broadcast_axes: AxisSpec | None = eqx.field(static=True) inference: bool = False # note: not static def __init__( self, pdrop: float = 0.5, - broadcast_axes: Optional[AxisSpec] = None, + broadcast_axes: AxisSpec | None = None, inference: bool = False, ): self.pdrop = pdrop @@ -89,8 +87,8 @@ class Dropout(eqx.Module): self, x: NamedArray, *, - inference: Optional[bool] = None, - key: Optional[PRNGKeyArray] = None, + inference: bool | None = None, + key: PRNGKeyArray | None = None, ) -> NamedArray: """**Arguments:** diff --git a/src/haliax/nn/embedding.py b/src/haliax/nn/embedding.py index 2141a9a..3f4d899 100644 --- a/src/haliax/nn/embedding.py +++ b/src/haliax/nn/embedding.py @@ -5,7 +5,6 @@ import dataclasses import warnings -from typing import Optional import equinox as eqx from jaxtyping import PRNGKeyArray @@ -26,7 +25,7 @@ class Embedding(eqx.Module): Embed: AxisSpec = eqx.field(static=True) @staticmethod - def init(Vocab: Axis, Embed: AxisSpec, *, init_scale: float = 1, key, initializer_range: Optional[float] = None): + def init(Vocab: Axis, Embed: AxisSpec, *, init_scale: float = 1, key, initializer_range: float | None = None): """ Initialize an Embedding module. @@ -50,7 +49,7 @@ class Embedding(eqx.Module): weight = hax.random.truncated_normal(key, all_axes, -3, 3) * (init_scale / output_size) return Embedding(weight=weight, Vocab=Vocab, Embed=Embed) - def __call__(self, input_ids: NamedArray, *, key: Optional[PRNGKeyArray] = None): + def __call__(self, input_ids: NamedArray, *, key: PRNGKeyArray | None = None): """Alias for `embed`. key is ignored.""" return self.embed(input_ids) @@ -71,7 +70,7 @@ class Embedding(eqx.Module): """ return input_embeds.dot(self.weight, axis=self.Embed) - def resize_embeddings(self, new_size: int, key: Optional[PRNGKeyArray] = None): + def resize_embeddings(self, new_size: int, key: PRNGKeyArray | None = None): """ Resize the embedding layer to a new size. Args: diff --git a/src/haliax/nn/linear.py b/src/haliax/nn/linear.py index 3c23f87..ddba493 100644 --- a/src/haliax/nn/linear.py +++ b/src/haliax/nn/linear.py @@ -6,7 +6,6 @@ import dataclasses import math from functools import partial -from typing import Optional import equinox as eqx import jax @@ -14,6 +13,7 @@ import jax.numpy as jnp from jax.experimental.pallas.ops.tpu.megablox import gmm from jax.experimental.shard_map import shard_map from jax.random import PRNGKey +from jaxtyping import PRNGKeyArray import haliax as hax @@ -31,7 +31,7 @@ class Linear(ModuleWithStateDictSerialization): and output, which is occasionally useful.""" weight: NamedArray - bias: Optional[NamedArray] + bias: NamedArray | None In: AxisSpec = eqx.field(static=True) Out: AxisSpec = eqx.field(static=True) @@ -45,7 +45,7 @@ class Linear(ModuleWithStateDictSerialization): key: PRNGKey, use_bias: bool = True, out_first: bool = True, - dot_general: Optional[DotGeneralOp] = None, + dot_general: DotGeneralOp | None = None, init_scale: float = 1.0, ) -> "Linear": """ @@ -69,7 +69,7 @@ class Linear(ModuleWithStateDictSerialization): return Linear(weight, bias, In, Out, dot_general=dot_general) @named_call - def __call__(self, inputs, *, key: Optional[PRNGKey] = None): + def __call__(self, inputs, *, key: PRNGKeyArray | None = None): """ Args: inputs (NamedArray): Input array @@ -143,7 +143,7 @@ class MoELinear(eqx.Module): and output, which is occasionally useful.""" weight: NamedArray - bias: Optional[NamedArray] + bias: NamedArray | None Experts: AxisSpec = eqx.field(static=True) In: Axis = eqx.field(static=True) @@ -185,7 +185,7 @@ class MoELinear(eqx.Module): return MoELinear(weight, bias, Experts, In, Out, use_gmm=use_gmm) @named_call - def __call__(self, inputs, group_sizes, *, key: Optional[PRNGKey] = None): + def __call__(self, inputs, group_sizes, *, key: PRNGKeyArray | None = None): """ Args: inputs (NamedArray): Input array (Batch, In) diff --git a/src/haliax/nn/loss.py b/src/haliax/nn/loss.py index 3bd9433..9d99de5 100644 --- a/src/haliax/nn/loss.py +++ b/src/haliax/nn/loss.py @@ -5,7 +5,6 @@ import typing import warnings -from typing import Optional from jax import numpy as jnp @@ -21,8 +20,8 @@ def cross_entropy_loss( logits: NamedArray, Label: AxisSelector, targets: NamedArray, - reduction: Optional[ReductionFunction] | Unspecified = UNSPECIFIED, - where: Optional[NamedArray] = None, + reduction: ReductionFunction | None | Unspecified = UNSPECIFIED, + where: NamedArray | None = None, reduction_axis: None = None, ) -> jnp.ndarray | NamedArray: ... @@ -32,8 +31,8 @@ def cross_entropy_loss( logits: NamedArray, Label: AxisSelector, targets: NamedArray, - reduction: Optional[ReductionFunction] | Unspecified = UNSPECIFIED, - where: Optional[NamedArray] = None, + reduction: ReductionFunction | None | Unspecified = UNSPECIFIED, + where: NamedArray | None = None, reduction_axis: AxisSelection = ..., ) -> NamedArray: ... @@ -42,9 +41,9 @@ def cross_entropy_loss( logits: NamedArray, Label: AxisSelector, targets: NamedArray, - reduction: Optional[ReductionFunction] | Unspecified = UNSPECIFIED, - where: Optional[NamedArray] = None, - reduction_axis: Optional[AxisSelection] = None, + reduction: ReductionFunction | None | Unspecified = UNSPECIFIED, + where: NamedArray | None = None, + reduction_axis: AxisSelection | None = None, ) -> jnp.ndarray | NamedArray: loss, _ = cross_entropy_loss_and_log_normalizers(logits, Label, targets) @@ -63,8 +62,8 @@ def cross_entropy_loss( def binary_cross_entropy_loss( logits: NamedArray, targets: NamedArray, - reduction: Optional[ReductionFunction] | Unspecified = UNSPECIFIED, - where: Optional[NamedArray] = None, + reduction: ReductionFunction | None | Unspecified = UNSPECIFIED, + where: NamedArray | None = None, reduction_axis: None = None, ) -> jnp.ndarray | NamedArray: ... @@ -73,8 +72,8 @@ def binary_cross_entropy_loss( def binary_cross_entropy_loss( logits: NamedArray, targets: NamedArray, - reduction: Optional[ReductionFunction] | Unspecified = UNSPECIFIED, - where: Optional[NamedArray] = None, + reduction: ReductionFunction | None | Unspecified = UNSPECIFIED, + where: NamedArray | None = None, reduction_axis: AxisSelection = ..., ) -> NamedArray: ... @@ -82,9 +81,9 @@ def binary_cross_entropy_loss( def binary_cross_entropy_loss( logits: NamedArray, targets: NamedArray, - reduction: Optional[ReductionFunction] | Unspecified = UNSPECIFIED, - where: Optional[NamedArray] = None, - reduction_axis: Optional[AxisSelection] = None, + reduction: ReductionFunction | None | Unspecified = UNSPECIFIED, + where: NamedArray | None = None, + reduction_axis: AxisSelection | None = None, ) -> jnp.ndarray | NamedArray: log_p = hax.nn.log_sigmoid(logits) log_not_p = hax.nn.log_sigmoid(-logits) # == log(1-sigmoid(x)) @@ -97,9 +96,9 @@ def binary_cross_entropy_loss( def reduce_loss( arr, - reduction: Optional[ReductionFunction] | Unspecified = UNSPECIFIED, - reduction_axis: Optional[AxisSelection] = None, - where: Optional[NamedArray] = None, + reduction: ReductionFunction | None | Unspecified = UNSPECIFIED, + reduction_axis: AxisSelection | None = None, + where: NamedArray | None = None, ): """ Reduce a loss array according to the given reduction and reduction axis. @@ -112,9 +111,9 @@ def reduce_loss( def maybe_reduce_loss( arr, - reduction: Optional[ReductionFunction] | Unspecified, - reduction_axis: Optional[AxisSelection], - where: Optional[NamedArray], + reduction: ReductionFunction | None | Unspecified, + reduction_axis: AxisSelection | None, + where: NamedArray | None, ): if reduction is not None and reduction_axis != (): if reduction is UNSPECIFIED: diff --git a/src/haliax/nn/mlp.py b/src/haliax/nn/mlp.py index f158154..a88bc1b 100644 --- a/src/haliax/nn/mlp.py +++ b/src/haliax/nn/mlp.py @@ -3,7 +3,7 @@ # SPDX-License-Identifier: Apache-2.0 -from typing import Callable, Optional, Sequence +from typing import Callable, Sequence import equinox as eqx import jax @@ -52,7 +52,7 @@ class MLP(eqx.Module): use_bias: bool = True, use_final_bias: bool = True, key: PRNGKeyArray, - dot_general: Optional[DotGeneralOp] = None, + dot_general: DotGeneralOp | None = None, init_scale: float = 1.0, ): Width = _get_width(width) diff --git a/src/haliax/nn/normalization.py b/src/haliax/nn/normalization.py index 206eb5e..639a585 100644 --- a/src/haliax/nn/normalization.py +++ b/src/haliax/nn/normalization.py @@ -5,7 +5,7 @@ import dataclasses from abc import abstractmethod -from typing import Optional, TypeVar +from typing import TypeVar import equinox as eqx from jax import nn as jnn @@ -25,10 +25,10 @@ A = TypeVar("A", Scalar, NamedArray, jnp.ndarray) class LayerNormBase(ModuleWithStateDictSerialization): axis: AxisSpec = eqx.field(static=True) - weight: Optional[NamedArray] - bias: Optional[NamedArray] + weight: NamedArray | None + bias: NamedArray | None eps: float = eqx.field(default=1e-5, static=True) - dtype: Optional[jnp.dtype] = eqx.field(default=None, static=True) + dtype: jnp.dtype | None = eqx.field(default=None, static=True) @abstractmethod def __call__(self, x: NamedArray) -> NamedArray: @@ -42,7 +42,7 @@ class LayerNormBase(ModuleWithStateDictSerialization): *, use_weight: bool = True, use_bias: bool = True, - dtype: Optional[jnp.dtype] = None, + dtype: jnp.dtype | None = None, ): if use_weight: weight = hax.ones(axis) @@ -99,11 +99,11 @@ class LayerNorm(LayerNormBase): """ axis: AxisSpec = eqx.field(static=True) - weight: Optional[NamedArray] - bias: Optional[NamedArray] + weight: NamedArray | None + bias: NamedArray | None eps: float = eqx.field(default=1e-5, static=True) - dtype: Optional[jnp.dtype] = eqx.field(default=None, static=True) + dtype: jnp.dtype | None = eqx.field(default=None, static=True) def __call__(self, x: NamedArray) -> NamedArray: dtype = x.dtype @@ -140,7 +140,7 @@ class RmsNorm(LayerNormBase): return out -def logsumexp(a: A, axis: Optional[AxisSelection] = None) -> A: +def logsumexp(a: A, axis: AxisSelection | None = None) -> A: # TODO: logsumexp indirectly supports where via `b`. we should support it directly return wrap_reduction_call(jnn.logsumexp, a, axis=axis, single_axis_only=False, supports_where=False) @@ -148,11 +148,11 @@ def logsumexp(a: A, axis: Optional[AxisSelection] = None) -> A: # TODO: support where in softmax, etc -def softmax(a: A, axis: Optional[AxisSelection] = None) -> A: +def softmax(a: A, axis: AxisSelection | None = None) -> A: return wrap_axiswise_call(jnn.softmax, a, axis=axis, single_axis_only=False) -def log_softmax(a: A, axis: Optional[AxisSelection] = None) -> A: +def log_softmax(a: A, axis: AxisSelection | None = None) -> A: return wrap_axiswise_call(jnn.log_softmax, a, axis=axis, single_axis_only=False) @@ -160,10 +160,10 @@ def standardize( x: NamedArray, axis: AxisSpec, *, - mean: Optional[NamedArray] = None, - variance: Optional[NamedArray] = None, + mean: NamedArray | None = None, + variance: NamedArray | None = None, epsilon: float = 1e-5, - where: Optional[NamedArray] = None, + where: NamedArray | None = None, ) -> NamedArray: """Analogous to [jax.nn.standardize][], but with support for NamedArrays.""" x, mean, variance, where = haliax.broadcast_arrays(x, mean, variance, where) # type: ignore diff --git a/src/haliax/nn/pool.py b/src/haliax/nn/pool.py index 5b416da..86c5d53 100644 --- a/src/haliax/nn/pool.py +++ b/src/haliax/nn/pool.py @@ -5,7 +5,7 @@ # Pooling operations, inspired by Flax from functools import reduce -from typing import Callable, Literal, Optional +from typing import Callable, Literal import jax @@ -29,7 +29,7 @@ def pool( inputs: NamedArray, init: Scalar, reduce_fn: Callable[[Scalar, Scalar], Scalar], - stride: Optional[int | tuple[int, ...]] = None, + stride: int | tuple[int, ...] | None = None, padding: Padding = DEFAULT_PADDING, use_ceil: bool = False, ) -> NamedArray: @@ -147,7 +147,7 @@ def _patch_up_reduce_fn(reduce_fn): def max_pool( Window: AxisSpec, inputs: NamedArray, - stride: Optional[int | tuple[int, ...]] = None, + stride: int | tuple[int, ...] | None = None, padding: Padding = DEFAULT_PADDING, use_ceil: bool = False, ) -> NamedArray: @@ -171,7 +171,7 @@ def max_pool( def min_pool( Window: AxisSpec, inputs: NamedArray, - stride: Optional[int | tuple[int, ...]] = None, + stride: int | tuple[int, ...] | None = None, padding: Padding = DEFAULT_PADDING, use_ceil: bool = False, ) -> NamedArray: @@ -196,7 +196,7 @@ def min_pool( def mean_pool( Window: AxisSpec, inputs: NamedArray, - stride: Optional[int | tuple[int, ...]] = None, + stride: int | tuple[int, ...] | None = None, padding: Padding = DEFAULT_PADDING, *, use_ceil: bool = False, diff --git a/src/haliax/nn/scan.py b/src/haliax/nn/scan.py index a982d12..fdc642e 100644 --- a/src/haliax/nn/scan.py +++ b/src/haliax/nn/scan.py @@ -11,9 +11,7 @@ from typing import ( Any, Callable, Concatenate, - Dict, Generic, - Optional, Protocol, Sequence, Type, @@ -319,10 +317,10 @@ class BlockSeq(ModuleWithStateDictSerialization, Generic[M]): else: return x - def _state_dict_key_map(self) -> Dict[str, Optional[str]]: + def _state_dict_key_map(self) -> dict[str, str | None]: return {"blocks": None} - def from_state_dict(self: M, state_dict: StateDict, prefix: Optional[str] = None) -> M: + def from_state_dict(self: M, state_dict: StateDict, prefix: str | None = None) -> M: out_blocks = [] for i, block in enumerate(self.blocks): my_prefix = with_prefix(prefix, str(i)) @@ -331,7 +329,7 @@ class BlockSeq(ModuleWithStateDictSerialization, Generic[M]): return eqx.tree_at(lambda m: m.blocks, self, out_blocks) - def to_state_dict(self, prefix: Optional[str] = None) -> StateDict: + def to_state_dict(self, prefix: str | None = None) -> StateDict: """ Returns the unstacked format of the module, which is compatible with torch.nn.Sequential, with keys of the form (...). The stacked/vectorized format is required for haliax.nn.Stacked and vectorizes all such tensors into a single shared key.". """ @@ -610,7 +608,7 @@ class Stacked(ModuleWithStateDictSerialization, Generic[M]): return block(carry, *extra_args, **extra_kwargs) # TODO: this is for logic that's in levanter. We should move that logic to haliax I guess? - def _state_dict_key_map(self) -> Dict[str, Optional[str]]: + def _state_dict_key_map(self) -> dict[str, str | None]: return {"stacked": None} def unstacked(self) -> Sequence[M]: @@ -640,14 +638,14 @@ class Stacked(ModuleWithStateDictSerialization, Generic[M]): unstacked_leaves = tuple(zip(*unstacked_leaves)) return tuple(map(lambda x: jax.tree_util.tree_unflatten(structure, x), unstacked_leaves)) - def to_state_dict(self, prefix: Optional[str] = None) -> StateDict: + def to_state_dict(self, prefix: str | None = None) -> StateDict: # this method needs to "devectorize" the blocks, so that we have a list of blocks h.0.FOO, h.1.FOO, etc. # first just do the normal thing with our own dict, which we'll post-process state_dict: StateDict = super().to_state_dict(prefix) return _unstack_state_dict(state_dict, prefix) - def from_state_dict(self: M, state_dict: StateDict, prefix: Optional[str] = None) -> M: + def from_state_dict(self: M, state_dict: StateDict, prefix: str | None = None) -> M: # this method needs to "vectorize" the blocks, so that we have a single block h.FOO # first just do the normal thing with our own dict, which we'll post-process stacked = _stack_state_dict(state_dict, prefix=prefix) @@ -655,7 +653,7 @@ class Stacked(ModuleWithStateDictSerialization, Generic[M]): return out -def _stack_state_dict(state_dict: StateDict, prefix: Optional[str] = None) -> StateDict: +def _stack_state_dict(state_dict: StateDict, prefix: str | None = None) -> StateDict: """ Stack all keys matching prefix in a new state dict, returning a state dict that has all keys matching prefix stacked, but otherwise the same. @@ -667,7 +665,7 @@ def _stack_state_dict(state_dict: StateDict, prefix: Optional[str] = None) -> St """ vectorized_dict: StateDict = {} - tensors_to_vectorize: dict[str, list[Optional[Any]]] = {} + tensors_to_vectorize: dict[str, list[Any | None]] = {} if prefix is not None: prefix_for_pat = re.escape(prefix + ".") else: @@ -694,7 +692,7 @@ def _stack_state_dict(state_dict: StateDict, prefix: Optional[str] = None) -> St return vectorized_dict -def _unstack_state_dict(state_dict: StateDict, prefix: Optional[str] = None) -> StateDict: +def _unstack_state_dict(state_dict: StateDict, prefix: str | None = None) -> StateDict: """ Unstack all keys matching prefix in a new state dict, returning a state dict that has all keys matching prefix unstacked, but otherwise the same. Mostly for use with [haliax.nn.Stacked][]. diff --git a/src/haliax/ops.py b/src/haliax/ops.py index 3dd97df..3c08c15 100644 --- a/src/haliax/ops.py +++ b/src/haliax/ops.py @@ -4,7 +4,7 @@ import typing -from typing import Mapping, Optional, Union +from typing import Mapping import jax import jax.numpy as jnp @@ -54,11 +54,11 @@ def where( def where( - condition: Union[NamedOrNumeric, bool], - x: Optional[NamedOrNumeric] = None, - y: Optional[NamedOrNumeric] = None, - fill_value: Optional[int] = None, - new_axis: Optional[Axis] = None, + condition: NamedOrNumeric | bool, + x: NamedOrNumeric | None = None, + y: NamedOrNumeric | None = None, + fill_value: int | None = None, + new_axis: Axis | None = None, ) -> NamedArray | tuple[NamedArray, ...]: """Like jnp.where, but with named axes.""" diff --git a/src/haliax/partitioning.py b/src/haliax/partitioning.py index 621f34a..1ea67c5 100644 --- a/src/haliax/partitioning.py +++ b/src/haliax/partitioning.py @@ -10,7 +10,7 @@ import threading import typing import warnings from math import prod -from typing import Callable, ContextManager, Mapping, Optional, ParamSpec, Sequence, TypeVar, Union, cast +from typing import Callable, ContextManager, Mapping, Optional, ParamSpec, Sequence, TypeAlias, TypeVar, cast import equinox as eqx import jax @@ -30,9 +30,9 @@ from .jax_utils import Static, is_in_jit, is_jax_array_like, is_on_mac_metal from .tree_util import hashable_combine, hashable_partition from .util import StringHolderEnum -PhysicalAxisSpec = Union[(str), Sequence[str]] -ResourceMapping = Mapping[(str), PhysicalAxisSpec] -MeshLike = Union[Mesh, AbstractMesh] +PhysicalAxisSpec: TypeAlias = str | Sequence[str] +ResourceMapping: TypeAlias = Mapping[str, PhysicalAxisSpec] +MeshLike: TypeAlias = Mesh | AbstractMesh """Mapping from logical axis names to physical axis names""" F = typing.TypeVar("F", bound=typing.Callable) @@ -92,7 +92,7 @@ def current_thread_local_mapping(): return _mapping_holder.thread_data.resource_mapping -def _resolve_mesh(mesh: Optional[MeshLike] = None) -> Optional[MeshLike]: +def _resolve_mesh(mesh: MeshLike | None = None) -> MeshLike | None: """Inside jit, prefer an abstract mesh, outside jit prefer a concrete mesh.""" from jax._src.mesh import get_concrete_mesh @@ -172,7 +172,7 @@ def auto_sharded(x: T, mesh: Optional[Mesh] = None) -> T: return shard(x, mapping=mapping, mesh=mesh) -def shard(x: T, mapping: Optional[ResourceMapping] = None, mesh: Optional[Mesh] = None) -> T: +def shard(x: T, mapping: ResourceMapping | None = None, mesh: Mesh | None = None) -> T: """ Shard a PyTree using the provided axis mapping. NamedArrays in the PyTree are sharded using the axis mapping. Other arrays (i.e. plain JAX arrays) are left alone. @@ -227,14 +227,14 @@ def shard(x: T, mapping: Optional[ResourceMapping] = None, mesh: Optional[Mesh] @functools.wraps(shard) -def shard_with_axis_mapping(x: T, mapping: ResourceMapping, mesh: Optional[Mesh] = None) -> T: +def shard_with_axis_mapping(x: T, mapping: ResourceMapping, mesh: Mesh | None = None) -> T: # warnings.warn("`shard_with_axis_mapping` is deprecated. Use `shard` instead", DeprecationWarning) return shard(x, mapping, mesh) def pspec_for( tree: PyTree, - resource_mapping: Optional[ResourceMapping] = None, + resource_mapping: ResourceMapping | None = None, preserve_existing_shardings: bool = True, ) -> PyTree: """Infer the :class:`PartitionSpec` for a module. @@ -320,9 +320,9 @@ def pspec_for( def infer_resource_partitions( tree: PyTree, - resource_mapping: Optional[ResourceMapping] = None, + resource_mapping: ResourceMapping | None = None, preserve_existing_shardings: bool = True, - mesh: Optional[Mesh] = None, + mesh: Mesh | None = None, ) -> PyTree: """ Infer the sharding for a module, to be used with ``named_jit``. @@ -373,11 +373,11 @@ class _NamedJitWrapper(eqx.Module): _fn: Callable # [Args, R] _dynamic_fun: PyTree _static_fun: typing.Any - _axis_resources: Optional[ResourceMapping] - _in_axis_resources: Optional[ResourceMapping] - _out_axis_resources: Optional[ResourceMapping] - _donate_args: Optional[PyTree] - _donate_kwargs: Optional[PyTree] + _axis_resources: ResourceMapping | None + _in_axis_resources: ResourceMapping | None + _out_axis_resources: ResourceMapping | None + _donate_args: PyTree | None + _donate_kwargs: PyTree | None _pjit_args: Mapping[str, typing.Any] @property @@ -470,44 +470,44 @@ class _NamedJitWrapper(eqx.Module): @typing.overload def named_jit( fn: Callable[Args, R], - axis_resources: Optional[ResourceMapping] = None, + axis_resources: ResourceMapping | None = None, *, - in_axis_resources: Optional[ResourceMapping] = None, - out_axis_resources: Optional[ResourceMapping] = None, - donate_args: Optional[PyTree] = None, - donate_kwargs: Optional[PyTree] = None, + in_axis_resources: ResourceMapping | None = None, + out_axis_resources: ResourceMapping | None = None, + donate_args: PyTree | None = None, + donate_kwargs: PyTree | None = None, # args from jit keep_unused: bool = False, - backend: Optional[str] = None, - inline: Optional[bool] = None, + backend: str | None = None, + inline: bool | None = None, ) -> WrappedCallable[Args, R]: ... @typing.overload def named_jit( *, - axis_resources: Optional[ResourceMapping] = None, - in_axis_resources: Optional[ResourceMapping] = None, - out_axis_resources: Optional[ResourceMapping] = None, - donate_args: Optional[PyTree] = None, - donate_kwargs: Optional[PyTree] = None, + axis_resources: ResourceMapping | None = None, + in_axis_resources: ResourceMapping | None = None, + out_axis_resources: ResourceMapping | None = None, + donate_args: PyTree | None = None, + donate_kwargs: PyTree | None = None, # args from jit keep_unused: bool = False, - backend: Optional[str] = None, - inline: Optional[bool] = None, + backend: str | None = None, + inline: bool | None = None, ) -> typing.Callable[[Callable[Args, R]], WrappedCallable[Args, R]]: ... def named_jit( - fn: Optional[Callable[Args, R]] = None, - axis_resources: Optional[ResourceMapping] = None, + fn: Callable[Args, R] | None = None, + axis_resources: ResourceMapping | None = None, *, - in_axis_resources: Optional[ResourceMapping] = None, - out_axis_resources: Optional[ResourceMapping] = None, - donate_args: Optional[PyTree] = None, - donate_kwargs: Optional[PyTree] = None, + in_axis_resources: ResourceMapping | None = None, + out_axis_resources: ResourceMapping | None = None, + donate_args: PyTree | None = None, + donate_kwargs: PyTree | None = None, **pjit_args, -) -> typing.Union[WrappedCallable[Args, R], typing.Callable[[Callable[Args, R]], WrappedCallable[Args, R]]]: +) -> WrappedCallable[Args, R] | typing.Callable[[Callable[Args, R]], WrappedCallable[Args, R]]: """ A version of pjit that uses NamedArrays and the provided resource mapping to infer resource partitions for sharded computation for. @@ -673,7 +673,7 @@ def _cached_filter_eval_shape(fun, *args, **kwargs): return _eval_shape_cache[static] -def physical_axis_name(axis: AxisSelector, mapping: Optional[ResourceMapping] = None) -> Optional[PhysicalAxisSpec]: +def physical_axis_name(axis: AxisSelector, mapping: ResourceMapping | None = None) -> PhysicalAxisSpec | None: """Get the physical axis name for a logical axis from the mapping. Returns none if the axis is not mapped.""" if mapping is None: mapping = current_thread_local_mapping() @@ -685,7 +685,7 @@ def physical_axis_name(axis: AxisSelector, mapping: Optional[ResourceMapping] = return mapping.get(axis.name, None) -def physical_axis_size(axis: AxisSelector, mapping: Optional[ResourceMapping] = None) -> Optional[int]: +def physical_axis_size(axis: AxisSelector, mapping: ResourceMapping | None = None) -> int | None: """Get the physical axis size for a logical axis. This is the product of the size of all physical axes that this logical axis is mapped to.""" mesh = _resolve_mesh() @@ -695,7 +695,7 @@ def physical_axis_size(axis: AxisSelector, mapping: Optional[ResourceMapping] = mesh_shape = mesh.shape - name: Union[None, str, Sequence[str]] = physical_axis_name(axis, mapping) + name: None | str | Sequence[str] = physical_axis_name(axis, mapping) if name is None: return None elif isinstance(name, str): @@ -705,7 +705,7 @@ def physical_axis_size(axis: AxisSelector, mapping: Optional[ResourceMapping] = def sharding_for_axis( - axis: AxisSelection, mapping: Optional[ResourceMapping] = None, mesh: Optional[MeshLike] = None + axis: AxisSelection, mapping: ResourceMapping | None = None, mesh: MeshLike | None = None ) -> NamedSharding: """Get the sharding for a single axis""" resolved_mesh = _resolve_mesh(mesh) @@ -714,14 +714,16 @@ def sharding_for_axis( return NamedSharding(resolved_mesh, pspec_for_axis(axis, mapping)) + return NamedSharding(resolved_mesh, pspec_for_axis(axis, mapping)) + -def pspec_for_axis(axis: AxisSelection, mapping: Optional[ResourceMapping] = None) -> PartitionSpec: +def pspec_for_axis(axis: AxisSelection, mapping: ResourceMapping | None = None) -> PartitionSpec: """Get the PartitionSpec for a single axis""" axis = axis_spec_to_shape_dict(axis) return PartitionSpec(*(physical_axis_name(a, mapping) for a in axis)) -def round_axis_for_partitioning(axis: Axis, mapping: Optional[ResourceMapping] = None) -> Axis: +def round_axis_for_partitioning(axis: Axis, mapping: ResourceMapping | None = None) -> Axis: """Round an axis so that it's divisible by the size of the partition it's on""" size = physical_axis_size(axis, mapping) if size is None: diff --git a/src/haliax/quantization.py b/src/haliax/quantization.py index f531cc8..4783fc0 100644 --- a/src/haliax/quantization.py +++ b/src/haliax/quantization.py @@ -10,7 +10,7 @@ import dataclasses import functools import warnings from dataclasses import dataclass -from typing import Optional, Protocol, TypeVar +from typing import Protocol, TypeVar import aqt.jax.v2.config as aqt_config import equinox as eqx @@ -151,7 +151,7 @@ class Fp8DotGeneralOp(OverwriteWithGradient): input_amax_history: jnp.ndarray output_grad_amax_history: jnp.ndarray kernel_amax_history: jnp.ndarray - compute_dtype: Optional[DTypeLike] = eqx.field(static=True) + compute_dtype: DTypeLike | None = eqx.field(static=True) @classmethod def init(cls, amax_history_length: int = 1024, compute_dtype: DTypeLike = None): @@ -210,14 +210,14 @@ class Int8DotGeneralOp(OverwriteWithGradient): cfg = aqt_config.set_context(self.cfg, jrandom.PRNGKey(42), train_step=None) return cfg(lhs, rhs, dimension_numbers, precision, preferred_element_type) - def to_state_dict(tree: PyTree, prefix: Optional[str] = None) -> StateDict: + def to_state_dict(tree: PyTree, prefix: str | None = None) -> StateDict: warnings.warn("Ignore all int8 states (if any) for now.") return {} @dataclass(frozen=True) class QuantizationConfig: - targets: Optional[list[str] | str] = dataclasses.field(default=None) + targets: list[str] | str | None = dataclasses.field(default=None) """ If provided, only modules with names in this list will be quantized. If a single string, will be treated as a regex """ diff --git a/src/haliax/random.py b/src/haliax/random.py index ef203ec..9d1876d 100644 --- a/src/haliax/random.py +++ b/src/haliax/random.py @@ -4,7 +4,6 @@ """Wrappers around jax.random functions.""" -from typing import Optional import jax.random as jrandom @@ -142,9 +141,7 @@ def ball(key, shape: AxisSpec, D: Axis, p: float = 2.0, dtype=float): @named_call -def choice( - key, shape: AxisSpec, a: NamedArray, axis: AxisSelector, replace: bool = True, p: Optional[NamedArray] = None -): +def choice(key, shape: AxisSpec, a: NamedArray, axis: AxisSelector, replace: bool = True, p: NamedArray | None = None): """ Selects random elements from an array along the given axis. If p is provided, the elements are selected with probability proportional to their weights and it must be a 1-d array with its only axis being the axis. @@ -171,7 +168,7 @@ def choice( @named_call -def categorical(key, logits: NamedArray, axis: AxisSelector, shape: Optional[AxisSpec] = None): +def categorical(key, logits: NamedArray, axis: AxisSelector, shape: AxisSpec | None = None): """Sample random values from categorical distributions. Args: diff --git a/src/haliax/specialized_fns.py b/src/haliax/specialized_fns.py index 3a58116..c8db3b5 100644 --- a/src/haliax/specialized_fns.py +++ b/src/haliax/specialized_fns.py @@ -3,8 +3,6 @@ # SPDX-License-Identifier: Apache-2.0 -from typing import Optional, Tuple - import jax import jax.numpy as jnp @@ -13,15 +11,15 @@ from .core import NamedArray def top_k( - arr: NamedArray, axis: AxisSelector, k: int, new_axis: Optional[AxisSelector] = None -) -> Tuple[NamedArray, NamedArray]: + arr: NamedArray, axis: AxisSelector, k: int, new_axis: AxisSelector | None = None +) -> tuple[NamedArray, NamedArray]: """ Select the top k elements along the given axis. Args: arr (NamedArray): array to select from axis (AxisSelector): axis to select from k (int): number of elements to select - new_axis (Optional[AxisSelector]): new axis name, if none, the original axis will be resized to k + new_axis (AxisSelector | None): new axis name, if none, the original axis will be resized to k Returns: NamedArray: array with the top k elements along the given axis diff --git a/src/haliax/state_dict.py b/src/haliax/state_dict.py index a6c0323..a8e6bdf 100644 --- a/src/haliax/state_dict.py +++ b/src/haliax/state_dict.py @@ -3,7 +3,7 @@ # SPDX-License-Identifier: Apache-2.0 -from typing import Optional, TypeVar +from typing import TypeVar import equinox @@ -28,7 +28,7 @@ T = TypeVar("T") def to_torch_compatible_state_dict( - t: T, *, flatten: bool = True, prefix: Optional[str] = None, filter: FilterSpec = is_jax_array_like + t: T, *, flatten: bool = True, prefix: str | None = None, filter: FilterSpec = is_jax_array_like ) -> StateDict: """ Convert a tree to a state dict that is compatible with torch-style state dicts. diff --git a/src/haliax/tree_util.py b/src/haliax/tree_util.py index 74c443f..3322cdc 100644 --- a/src/haliax/tree_util.py +++ b/src/haliax/tree_util.py @@ -5,7 +5,8 @@ import dataclasses import functools -from typing import Optional + +# Removed unused import import equinox as eqx import jax @@ -101,7 +102,7 @@ def tree_structure(tree, is_leaf=None): return jax.tree_util.tree_structure(tree, is_leaf=is_leaf) -def resize_axis(tree: PyTree[NamedArray], old_axis: AxisSelector, new_size: int, key: Optional[PRNGKeyArray] = None): +def resize_axis(tree: PyTree[NamedArray], old_axis: AxisSelector, new_size: int, key: PRNGKeyArray | None = None): """Resizes the NamedArrays of a PyTree along a given axis. If the array needs to grow and key is not none, then the new elements are sampled from a truncated normal distribution with the same mean and standard deviation as the existing elements. If the key is none, they're just initialized to the mean. If the array needs to shrink, then it's diff --git a/src/haliax/types.py b/src/haliax/types.py index b6d09f4..6e582b2 100644 --- a/src/haliax/types.py +++ b/src/haliax/types.py @@ -3,7 +3,7 @@ # SPDX-License-Identifier: Apache-2.0 -from typing import Any, Callable, Literal, Protocol, Tuple, TypeAlias, Union +from typing import Any, Callable, Literal, Protocol, TypeAlias import jax.numpy as jnp import numpy as np @@ -20,23 +20,23 @@ except ImportError: @property def dtype(self) -> DType: ... - DTypeLike = Union[ - str, # like 'float32', 'int32' - type, # like np.float32, np.int32, float, int - np.dtype, # like np.dtype('float32'), np.dtype('int32') - SupportsDType, # like jnp.float32, jnp.int32 - ] + DTypeLike = ( + str # like 'float32', 'int32' + | type # like np.float32, np.int32, float, int + | np.dtype # like np.dtype('float32'), np.dtype('int32') + | SupportsDType # like jnp.float32, jnp.int32 + ) -Scalar = Union[float, int, jnp.ndarray] # ndarray b/c array(1) is a scalar -IntScalar = Union[int, jnp.ndarray] +Scalar = float | int | jnp.ndarray # ndarray b/c array(1) is a scalar +IntScalar = int | jnp.ndarray -PrecisionLike = Union[None, str, Precision, Tuple[str, str], Tuple[Precision, Precision]] +PrecisionLike = None | str | Precision | tuple[str, str] | tuple[Precision, Precision] GatherScatterModeStr = Literal["promise_in_bounds", "clip", "drop", "fill"] -FilterSpec = Union[bool, Callable[[Any], bool]] +FilterSpec = bool | Callable[[Any], bool] """ A filter specification. Typically used on a pytree to filter out certain subtrees. Boolean values are treated as-is, while callables are called on each element of the pytree. If the callable returns True, the element diff --git a/src/haliax/util.py b/src/haliax/util.py index 33572de..0703188 100644 --- a/src/haliax/util.py +++ b/src/haliax/util.py @@ -4,7 +4,7 @@ import functools -from typing import Sequence, Tuple, TypeAlias, TypeVar, Union +from typing import Sequence, TypeAlias, TypeVar import equinox @@ -23,7 +23,7 @@ def is_named_array(leaf): return isinstance(leaf, NamedArray) -def ensure_tuple(x: Union[Sequence[T], T]) -> Tuple[T, ...]: +def ensure_tuple(x: Sequence[T] | T) -> tuple[T, ...]: if isinstance(x, str): return (x,) # type: ignore elif isinstance(x, Sequence): @@ -31,7 +31,7 @@ def ensure_tuple(x: Union[Sequence[T], T]) -> Tuple[T, ...]: return (x,) -def maybe_untuple(x: Union[Sequence[T], T]) -> Union[T, Sequence[T]]: +def maybe_untuple(x: Sequence[T] | T) -> T | Sequence[T]: """ If x is a tuple with one element, return that element. Otherwise return x. """ diff --git a/src/haliax/wrap.py b/src/haliax/wrap.py index 8a34679..58d76e8 100644 --- a/src/haliax/wrap.py +++ b/src/haliax/wrap.py @@ -3,7 +3,7 @@ # SPDX-License-Identifier: Apache-2.0 -from typing import Optional, Protocol +from typing import Protocol import jax @@ -23,8 +23,8 @@ def wrap_elemwise_unary(f, a, *args, **kwargs): def wrap_reduction_call( fn, a, - axis: Optional[AxisSelection], - where: Optional[NamedArray] = None, + axis: AxisSelection | None, + where: NamedArray | None = None, single_axis_only: bool = False, supports_where: bool = True, **kwargs, @@ -72,7 +72,7 @@ def wrap_reduction_call( return jax.tree_util.tree_map(reduce_one_leaf, a, is_leaf=lambda x: isinstance(x, NamedArray)) -def wrap_axiswise_call(fn, a, axis: Optional[AxisSelection], *, single_axis_only: bool, **kwargs): +def wrap_axiswise_call(fn, a, axis: AxisSelection | None, *, single_axis_only: bool, **kwargs): if isinstance(a, NamedArray): if axis is None: return fn(a.array, axis=None, **kwargs) @@ -142,14 +142,14 @@ class ReductionFunction(Protocol): def __call__( self, array: NamedArray, - axis: Optional[AxisSelection] = None, - where: Optional[NamedArray] = None, + axis: AxisSelection | None = None, + where: NamedArray | None = None, **kwargs, ) -> NamedArray: ... class SimpleReductionFunction(Protocol): - def __call__(self, array: NamedArray, axis: Optional[AxisSelector] = None, **kwargs) -> NamedArray: ... + def __call__(self, array: NamedArray, axis: AxisSelector | None = None, **kwargs) -> NamedArray: ... __all__ = [ diff --git a/uv.lock b/uv.lock index 4741549..ccb4dcf 100644 --- a/uv.lock +++ b/uv.lock @@ -1,11 +1,10 @@ version = 1 revision = 3 -requires-python = ">=3.10" +requires-python = ">=3.11" resolution-markers = [ "python_full_version >= '3.13'", "python_full_version == '3.12.*'", - "python_full_version == '3.11.*'", - "python_full_version < '3.11'", + "python_full_version < '3.12'", ] [[package]] @@ -32,12 +31,9 @@ version = "0.9.0" source = { registry = "https://pypi.org/simple" } dependencies = [ { name = "absl-py" }, - { name = "flax", version = "0.10.7", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version < '3.11'" }, - { name = "flax", version = "0.12.0", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version >= '3.11'" }, - { name = "jax", version = "0.6.2", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version < '3.11'" }, - { name = "jax", version = "0.7.2", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version >= '3.11'" }, - { name = "jaxlib", version = "0.6.2", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version < '3.11'" }, - { name = "jaxlib", version = "0.7.2", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version >= '3.11'" }, + { name = "flax" }, + { name = "jax" }, + { name = "jaxlib" }, ] sdist = { url = "https://files.pythonhosted.org/packages/85/b2/028d15474268205dc2a7382759a51eb8903bd3a218a9d261874e2ec772a4/aqtp-0.9.0.tar.gz", hash = "sha256:a42f03f0de5ed54d0d0d9437741a44f6408eaed48103a3434f0ad405ff86874a", size = 885899, upload-time = "2025-08-01T17:54:59.738Z" } wheels = [ @@ -100,17 +96,6 @@ version = "3.4.3" source = { registry = "https://pypi.org/simple" } sdist = { url = "https://files.pythonhosted.org/packages/83/2d/5fd176ceb9b2fc619e63405525573493ca23441330fcdaee6bef9460e924/charset_normalizer-3.4.3.tar.gz", hash = "sha256:6fce4b8500244f6fcb71465d4a4930d132ba9ab8e71a7859e6a5d59851068d14", size = 122371, upload-time = "2025-08-09T07:57:28.46Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/d6/98/f3b8013223728a99b908c9344da3aa04ee6e3fa235f19409033eda92fb78/charset_normalizer-3.4.3-cp310-cp310-macosx_10_9_universal2.whl", hash = "sha256:fb7f67a1bfa6e40b438170ebdc8158b78dc465a5a67b6dde178a46987b244a72", size = 207695, upload-time = "2025-08-09T07:55:36.452Z" }, - { url = "https://files.pythonhosted.org/packages/21/40/5188be1e3118c82dcb7c2a5ba101b783822cfb413a0268ed3be0468532de/charset_normalizer-3.4.3-cp310-cp310-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:cc9370a2da1ac13f0153780040f465839e6cccb4a1e44810124b4e22483c93fe", size = 147153, upload-time = "2025-08-09T07:55:38.467Z" }, - { url = "https://files.pythonhosted.org/packages/37/60/5d0d74bc1e1380f0b72c327948d9c2aca14b46a9efd87604e724260f384c/charset_normalizer-3.4.3-cp310-cp310-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:07a0eae9e2787b586e129fdcbe1af6997f8d0e5abaa0bc98c0e20e124d67e601", size = 160428, upload-time = "2025-08-09T07:55:40.072Z" }, - { url = "https://files.pythonhosted.org/packages/85/9a/d891f63722d9158688de58d050c59dc3da560ea7f04f4c53e769de5140f5/charset_normalizer-3.4.3-cp310-cp310-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:74d77e25adda8581ffc1c720f1c81ca082921329452eba58b16233ab1842141c", size = 157627, upload-time = "2025-08-09T07:55:41.706Z" }, - { url = "https://files.pythonhosted.org/packages/65/1a/7425c952944a6521a9cfa7e675343f83fd82085b8af2b1373a2409c683dc/charset_normalizer-3.4.3-cp310-cp310-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:d0e909868420b7049dafd3a31d45125b31143eec59235311fc4c57ea26a4acd2", size = 152388, upload-time = "2025-08-09T07:55:43.262Z" }, - { url = "https://files.pythonhosted.org/packages/f0/c9/a2c9c2a355a8594ce2446085e2ec97fd44d323c684ff32042e2a6b718e1d/charset_normalizer-3.4.3-cp310-cp310-musllinux_1_2_aarch64.whl", hash = "sha256:c6f162aabe9a91a309510d74eeb6507fab5fff92337a15acbe77753d88d9dcf0", size = 150077, upload-time = "2025-08-09T07:55:44.903Z" }, - { url = "https://files.pythonhosted.org/packages/3b/38/20a1f44e4851aa1c9105d6e7110c9d020e093dfa5836d712a5f074a12bf7/charset_normalizer-3.4.3-cp310-cp310-musllinux_1_2_ppc64le.whl", hash = "sha256:4ca4c094de7771a98d7fbd67d9e5dbf1eb73efa4f744a730437d8a3a5cf994f0", size = 161631, upload-time = "2025-08-09T07:55:46.346Z" }, - { url = "https://files.pythonhosted.org/packages/a4/fa/384d2c0f57edad03d7bec3ebefb462090d8905b4ff5a2d2525f3bb711fac/charset_normalizer-3.4.3-cp310-cp310-musllinux_1_2_s390x.whl", hash = "sha256:02425242e96bcf29a49711b0ca9f37e451da7c70562bc10e8ed992a5a7a25cc0", size = 159210, upload-time = "2025-08-09T07:55:47.539Z" }, - { url = "https://files.pythonhosted.org/packages/33/9e/eca49d35867ca2db336b6ca27617deed4653b97ebf45dfc21311ce473c37/charset_normalizer-3.4.3-cp310-cp310-musllinux_1_2_x86_64.whl", hash = "sha256:78deba4d8f9590fe4dae384aeff04082510a709957e968753ff3c48399f6f92a", size = 153739, upload-time = "2025-08-09T07:55:48.744Z" }, - { url = "https://files.pythonhosted.org/packages/2a/91/26c3036e62dfe8de8061182d33be5025e2424002125c9500faff74a6735e/charset_normalizer-3.4.3-cp310-cp310-win32.whl", hash = "sha256:d79c198e27580c8e958906f803e63cddb77653731be08851c7df0b1a14a8fc0f", size = 99825, upload-time = "2025-08-09T07:55:50.305Z" }, - { url = "https://files.pythonhosted.org/packages/e2/c6/f05db471f81af1fa01839d44ae2a8bfeec8d2a8b4590f16c4e7393afd323/charset_normalizer-3.4.3-cp310-cp310-win_amd64.whl", hash = "sha256:c6e490913a46fa054e03699c70019ab869e990270597018cef1d8562132c2669", size = 107452, upload-time = "2025-08-09T07:55:51.461Z" }, { url = "https://files.pythonhosted.org/packages/7f/b5/991245018615474a60965a7c9cd2b4efbaabd16d582a5547c47ee1c7730b/charset_normalizer-3.4.3-cp311-cp311-macosx_10_9_universal2.whl", hash = "sha256:b256ee2e749283ef3ddcff51a675ff43798d92d746d1a6e4631bf8c707d22d0b", size = 204483, upload-time = "2025-08-09T07:55:53.12Z" }, { url = "https://files.pythonhosted.org/packages/c7/2a/ae245c41c06299ec18262825c1569c5d3298fc920e4ddf56ab011b417efd/charset_normalizer-3.4.3-cp311-cp311-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:13faeacfe61784e2559e690fc53fa4c5ae97c6fcedb8eb6fb8d0a15b475d2c64", size = 145520, upload-time = "2025-08-09T07:55:54.712Z" }, { url = "https://files.pythonhosted.org/packages/3a/a4/b3b6c76e7a635748c4421d2b92c7b8f90a432f98bda5082049af37ffc8e3/charset_normalizer-3.4.3-cp311-cp311-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:00237675befef519d9af72169d8604a067d92755e84fe76492fef5441db05b91", size = 158876, upload-time = "2025-08-09T07:55:56.024Z" }, @@ -158,42 +143,17 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/8a/1f/f041989e93b001bc4e44bb1669ccdcf54d3f00e628229a85b08d330615c5/charset_normalizer-3.4.3-py3-none-any.whl", hash = "sha256:ce571ab16d890d23b5c278547ba694193a45011ff86a9162a71307ed9f86759a", size = 53175, upload-time = "2025-08-09T07:57:26.864Z" }, ] -[[package]] -name = "chex" -version = "0.1.90" -source = { registry = "https://pypi.org/simple" } -resolution-markers = [ - "python_full_version < '3.11'", -] -dependencies = [ - { name = "absl-py", marker = "python_full_version < '3.11'" }, - { name = "jax", version = "0.6.2", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version < '3.11'" }, - { name = "jaxlib", version = "0.6.2", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version < '3.11'" }, - { name = "numpy", version = "2.2.6", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version < '3.11'" }, - { name = "toolz", marker = "python_full_version < '3.11'" }, - { name = "typing-extensions", marker = "python_full_version < '3.11'" }, -] -sdist = { url = "https://files.pythonhosted.org/packages/77/70/53c7d404ce9e2a94009aea7f77ef6e392f6740e071c62683a506647c520f/chex-0.1.90.tar.gz", hash = "sha256:d3c375aeb6154b08f1cccd2bee4ed83659ee2198a6acf1160d2fe2e4a6c87b5c", size = 92363, upload-time = "2025-07-23T19:50:47.945Z" } -wheels = [ - { url = "https://files.pythonhosted.org/packages/6f/3d/46bb04776c465cea2dd8aa2d4b61ab610b707f798f47838ef7e6105b025c/chex-0.1.90-py3-none-any.whl", hash = "sha256:fce3de82588f72d4796e545e574a433aa29229cbdcf792555e41bead24b704ae", size = 101047, upload-time = "2025-07-23T19:50:46.603Z" }, -] - [[package]] name = "chex" version = "0.1.91" source = { registry = "https://pypi.org/simple" } -resolution-markers = [ - "python_full_version >= '3.13'", - "python_full_version == '3.12.*'", - "python_full_version == '3.11.*'", -] dependencies = [ - { name = "absl-py", marker = "python_full_version >= '3.11'" }, - { name = "jax", version = "0.7.2", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version >= '3.11'" }, - { name = "jaxlib", version = "0.7.2", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version >= '3.11'" }, - { name = "numpy", version = "2.3.3", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version >= '3.11'" }, - { name = "toolz", marker = "python_full_version >= '3.11'" }, - { name = "typing-extensions", marker = "python_full_version >= '3.11'" }, + { name = "absl-py" }, + { name = "jax" }, + { name = "jaxlib" }, + { name = "numpy" }, + { name = "toolz" }, + { name = "typing-extensions" }, ] sdist = { url = "https://files.pythonhosted.org/packages/5b/7d/812f01e7b2ddf28a0caa8dde56bd951a2c8f691c9bbfce38d469458d1502/chex-0.1.91.tar.gz", hash = "sha256:65367a521415ada905b8c0222b0a41a68337fcadf79a1fb6fc992dbd95dd9f76", size = 90302, upload-time = "2025-09-01T21:49:32.834Z" } wheels = [ @@ -235,8 +195,7 @@ name = "equinox" version = "0.13.1" source = { registry = "https://pypi.org/simple" } dependencies = [ - { name = "jax", version = "0.6.2", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version < '3.11'" }, - { name = "jax", version = "0.7.2", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version >= '3.11'" }, + { name = "jax" }, { name = "jaxtyping" }, { name = "typing-extensions" }, { name = "wadler-lindig" }, @@ -266,18 +225,6 @@ epy = [ { name = "typing-extensions" }, ] -[[package]] -name = "exceptiongroup" -version = "1.3.0" -source = { registry = "https://pypi.org/simple" } -dependencies = [ - { name = "typing-extensions", marker = "python_full_version < '3.11'" }, -] -sdist = { url = "https://files.pythonhosted.org/packages/0b/9f/a65090624ecf468cdca03533906e7c69ed7588582240cfe7cc9e770b50eb/exceptiongroup-1.3.0.tar.gz", hash = "sha256:b241f5885f560bc56a59ee63ca4c6a8bfa46ae4ad651af316d4e81817bb9fd88", size = 29749, upload-time = "2025-05-10T17:42:51.123Z" } -wheels = [ - { url = "https://files.pythonhosted.org/packages/36/f4/c6e662dade71f56cd2f3735141b265c3c79293c109549c1e6933b0651ffc/exceptiongroup-1.3.0-py3-none-any.whl", hash = "sha256:4d111e6e0c13d0644cad6ddaa7ed0261a0b36971f6d23e7ec9b4b9097da78a10", size = 16674, upload-time = "2025-05-10T17:42:49.33Z" }, -] - [[package]] name = "filelock" version = "3.19.1" @@ -287,49 +234,21 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/42/14/42b2651a2f46b022ccd948bca9f2d5af0fd8929c4eec235b8d6d844fbe67/filelock-3.19.1-py3-none-any.whl", hash = "sha256:d38e30481def20772f5baf097c122c3babc4fcdb7e14e57049eb9d88c6dc017d", size = 15988, upload-time = "2025-08-14T16:56:01.633Z" }, ] -[[package]] -name = "flax" -version = "0.10.7" -source = { registry = "https://pypi.org/simple" } -resolution-markers = [ - "python_full_version < '3.11'", -] -dependencies = [ - { name = "jax", version = "0.6.2", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version < '3.11'" }, - { name = "msgpack", marker = "python_full_version < '3.11'" }, - { name = "optax", marker = "python_full_version < '3.11'" }, - { name = "orbax-checkpoint", marker = "python_full_version < '3.11'" }, - { name = "pyyaml", marker = "python_full_version < '3.11'" }, - { name = "rich", marker = "python_full_version < '3.11'" }, - { name = "tensorstore", marker = "python_full_version < '3.11'" }, - { name = "treescope", marker = "python_full_version < '3.11'" }, - { name = "typing-extensions", marker = "python_full_version < '3.11'" }, -] -sdist = { url = "https://files.pythonhosted.org/packages/e6/76/4ea55a60a47e98fcff591238ee26ed4624cb4fdc4893aa3ebf78d0d021f4/flax-0.10.7.tar.gz", hash = "sha256:2930d6671e23076f6db3b96afacf45c5060898f5c189ecab6dda7e05d26c2085", size = 5136099, upload-time = "2025-07-02T06:10:07.819Z" } -wheels = [ - { url = "https://files.pythonhosted.org/packages/11/f6/560d338687d40182c8429cf35c64cc022e0d57ba3e52191c4a78ed239b4e/flax-0.10.7-py3-none-any.whl", hash = "sha256:4033223a9a9969ba0b252e085e9714d0a1e9124ac300aaf48e92c40769c420f6", size = 456944, upload-time = "2025-07-02T06:10:05.807Z" }, -] - [[package]] name = "flax" version = "0.12.0" source = { registry = "https://pypi.org/simple" } -resolution-markers = [ - "python_full_version >= '3.13'", - "python_full_version == '3.12.*'", - "python_full_version == '3.11.*'", -] dependencies = [ - { name = "jax", version = "0.7.2", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version >= '3.11'" }, - { name = "msgpack", marker = "python_full_version >= '3.11'" }, - { name = "numpy", version = "2.3.3", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version >= '3.11'" }, - { name = "optax", marker = "python_full_version >= '3.11'" }, - { name = "orbax-checkpoint", marker = "python_full_version >= '3.11'" }, - { name = "pyyaml", marker = "python_full_version >= '3.11'" }, - { name = "rich", marker = "python_full_version >= '3.11'" }, - { name = "tensorstore", marker = "python_full_version >= '3.11'" }, - { name = "treescope", marker = "python_full_version >= '3.11'" }, - { name = "typing-extensions", marker = "python_full_version >= '3.11'" }, + { name = "jax" }, + { name = "msgpack" }, + { name = "numpy" }, + { name = "optax" }, + { name = "orbax-checkpoint" }, + { name = "pyyaml" }, + { name = "rich" }, + { name = "tensorstore" }, + { name = "treescope" }, + { name = "typing-extensions" }, ] sdist = { url = "https://files.pythonhosted.org/packages/8b/02/2d4fbc31dcf5fb02e2b8ce733f8eecaffc7f24e905df2da39539809b195b/flax-0.12.0.tar.gz", hash = "sha256:cb3d4a2028666640c1a2e5b267dadfbd42ef14c6db41896fb4c765a7f05ebe74", size = 5038989, upload-time = "2025-09-25T23:59:00.919Z" } wheels = [ @@ -375,8 +294,7 @@ source = { editable = "." } dependencies = [ { name = "aqtp" }, { name = "equinox" }, - { name = "jax", version = "0.6.2", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version < '3.11'" }, - { name = "jax", version = "0.7.2", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version >= '3.11'" }, + { name = "jax" }, { name = "jaxtyping" }, { name = "jmp" }, { name = "safetensors" }, @@ -384,8 +302,7 @@ dependencies = [ [package.dev-dependencies] dev = [ - { name = "chex", version = "0.1.90", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version < '3.11'" }, - { name = "chex", version = "0.1.91", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version >= '3.11'" }, + { name = "chex" }, { name = "mkdocs" }, { name = "mkdocs-include-markdown-plugin" }, { name = "mkdocs-literate-nav" }, @@ -481,92 +398,30 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/2c/e1/e6716421ea10d38022b952c159d5161ca1193197fb744506875fbb87ea7b/iniconfig-2.1.0-py3-none-any.whl", hash = "sha256:9deba5723312380e77435581c6bf4935c94cbfab9b1ed33ef8d238ea168eb760", size = 6050, upload-time = "2025-03-19T20:10:01.071Z" }, ] -[[package]] -name = "jax" -version = "0.6.2" -source = { registry = "https://pypi.org/simple" } -resolution-markers = [ - "python_full_version < '3.11'", -] -dependencies = [ - { name = "jaxlib", version = "0.6.2", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version < '3.11'" }, - { name = "ml-dtypes", marker = "python_full_version < '3.11'" }, - { name = "numpy", version = "2.2.6", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version < '3.11'" }, - { name = "opt-einsum", marker = "python_full_version < '3.11'" }, - { name = "scipy", version = "1.15.3", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version < '3.11'" }, -] -sdist = { url = "https://files.pythonhosted.org/packages/cf/1e/267f59c8fb7f143c3f778c76cb7ef1389db3fd7e4540f04b9f42ca90764d/jax-0.6.2.tar.gz", hash = "sha256:a437d29038cbc8300334119692744704ca7941490867b9665406b7f90665cd96", size = 2334091, upload-time = "2025-06-17T23:10:27.186Z" } -wheels = [ - { url = "https://files.pythonhosted.org/packages/31/a8/97ef0cbb7a17143ace2643d600a7b80d6705b2266fc31078229e406bdef2/jax-0.6.2-py3-none-any.whl", hash = "sha256:bb24a82dc60ccf704dcaf6dbd07d04957f68a6c686db19630dd75260d1fb788c", size = 2722396, upload-time = "2025-06-17T23:10:25.293Z" }, -] - [[package]] name = "jax" version = "0.7.2" source = { registry = "https://pypi.org/simple" } -resolution-markers = [ - "python_full_version >= '3.13'", - "python_full_version == '3.12.*'", - "python_full_version == '3.11.*'", -] dependencies = [ - { name = "jaxlib", version = "0.7.2", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version >= '3.11'" }, - { name = "ml-dtypes", marker = "python_full_version >= '3.11'" }, - { name = "numpy", version = "2.3.3", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version >= '3.11'" }, - { name = "opt-einsum", marker = "python_full_version >= '3.11'" }, - { name = "scipy", version = "1.16.2", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version >= '3.11'" }, + { name = "jaxlib" }, + { name = "ml-dtypes" }, + { name = "numpy" }, + { name = "opt-einsum" }, + { name = "scipy" }, ] sdist = { url = "https://files.pythonhosted.org/packages/8f/e7/1e8e8af59b7659c83dc07dfa1dc23bc13551e5ef89bdef19ced044a497fc/jax-0.7.2.tar.gz", hash = "sha256:71a42b964bc6d52e819311429e6c0f5742e2a4650226dab1a1dd26fd986ca70d", size = 2434085, upload-time = "2025-09-16T16:48:53.108Z" } wheels = [ { url = "https://files.pythonhosted.org/packages/d5/e6/5fd0f6fff79eb47469ff9c4fa27125b661517a2fbf8884689b02e9fdfaa8/jax-0.7.2-py3-none-any.whl", hash = "sha256:e7e32f9be51ae5cc6854225958c57de8cca2187d279844338465b15e8a1fe7f2", size = 2835570, upload-time = "2025-09-16T16:48:51.33Z" }, ] -[[package]] -name = "jaxlib" -version = "0.6.2" -source = { registry = "https://pypi.org/simple" } -resolution-markers = [ - "python_full_version < '3.11'", -] -dependencies = [ - { name = "ml-dtypes", marker = "python_full_version < '3.11'" }, - { name = "numpy", version = "2.2.6", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version < '3.11'" }, - { name = "scipy", version = "1.15.3", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version < '3.11'" }, -] -wheels = [ - { url = "https://files.pythonhosted.org/packages/15/c5/41598634c99cbebba46e6777286fb76abc449d33d50aeae5d36128ca8803/jaxlib-0.6.2-cp310-cp310-macosx_11_0_arm64.whl", hash = "sha256:da4601b2b5dc8c23d6afb293eacfb9aec4e1d1871cb2f29c5a151d103e73b0f8", size = 54298019, upload-time = "2025-06-17T23:10:36.916Z" }, - { url = "https://files.pythonhosted.org/packages/81/af/db07d746cd5867d5967528e7811da53374e94f64e80a890d6a5a4b95b130/jaxlib-0.6.2-cp310-cp310-manylinux2014_aarch64.whl", hash = "sha256:4205d098ce8efb5f7fe2fe5098bae6036094dc8d8829f5e0e0d7a9b155326336", size = 79440052, upload-time = "2025-06-17T23:10:41.282Z" }, - { url = "https://files.pythonhosted.org/packages/7e/d8/b7ae9e819c62c1854dbc2c70540a5c041173fbc8bec5e78ab7fd615a4aee/jaxlib-0.6.2-cp310-cp310-manylinux2014_x86_64.whl", hash = "sha256:c087a0eb6fb7f6f8f54d56f4730328dfde5040dd3b5ddfa810e7c28ea7102b42", size = 89917034, upload-time = "2025-06-17T23:10:45.897Z" }, - { url = "https://files.pythonhosted.org/packages/fd/e5/87e91bc70569ac5c3e3449eefcaf47986e892f10cfe1d5e5720dceae3068/jaxlib-0.6.2-cp310-cp310-win_amd64.whl", hash = "sha256:153eaa51f778b60851720729d4f461a91edd9ba3932f6f3bc598d4413870038b", size = 57896337, upload-time = "2025-06-17T23:10:50.179Z" }, - { url = "https://files.pythonhosted.org/packages/a4/ee/6899b0aed36a4acc51319465ddd83c7c300a062a9e236cceee00984ffe0b/jaxlib-0.6.2-cp311-cp311-macosx_11_0_arm64.whl", hash = "sha256:a208ff61c58128d306bb4e5ad0858bd2b0960f2c1c10ad42c548f74a60c0020e", size = 54300346, upload-time = "2025-06-17T23:10:54.591Z" }, - { url = "https://files.pythonhosted.org/packages/e6/03/34bb6b346609079a71942cfbf507892e3c877a06a430a0df8429c455cebc/jaxlib-0.6.2-cp311-cp311-manylinux2014_aarch64.whl", hash = "sha256:11eae7e05bc5a79875da36324afb9eddd4baeaef2a0386caf6d4f3720b9aef28", size = 79438425, upload-time = "2025-06-17T23:10:58.356Z" }, - { url = "https://files.pythonhosted.org/packages/80/02/49b05cbab519ffd3cb79586336451fbbf8b6523f67128a794acc9f179000/jaxlib-0.6.2-cp311-cp311-manylinux2014_x86_64.whl", hash = "sha256:335d7e3515ce78b52a410136f46aa4a7ea14d0e7d640f34e1e137409554ad0ac", size = 89920354, upload-time = "2025-06-17T23:11:03.086Z" }, - { url = "https://files.pythonhosted.org/packages/a7/7a/93b28d9452b46c15fc28dd65405672fc8a158b35d46beabaa0fe9631afb0/jaxlib-0.6.2-cp311-cp311-win_amd64.whl", hash = "sha256:c6815509997d6b05e5c9daa7994b9ad473ce3e8c8a17bdbbcacc3c744f76f7a0", size = 57895707, upload-time = "2025-06-17T23:11:07.074Z" }, - { url = "https://files.pythonhosted.org/packages/ac/db/05e702d2534e87abf606b1067b46a273b120e6adc7d459696e3ce7399317/jaxlib-0.6.2-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:34d8a684a8be949dd87dd4acc97101b4106a0dc9ad151ec891da072319a57b99", size = 54301644, upload-time = "2025-06-17T23:11:10.977Z" }, - { url = "https://files.pythonhosted.org/packages/0d/8a/b0a96887b97a25d45ae2c30e4acecd2f95acd074c18ec737dda8c5cc7016/jaxlib-0.6.2-cp312-cp312-manylinux2014_aarch64.whl", hash = "sha256:87ec2dc9c3ed9ab936eec8535160c5fbd2c849948559f1c5daa75f63fabe5942", size = 79439161, upload-time = "2025-06-17T23:11:14.822Z" }, - { url = "https://files.pythonhosted.org/packages/ba/e8/71c2555431edb5dd115cf86a7b599aa7e1be26728d89ae59aa11251d299c/jaxlib-0.6.2-cp312-cp312-manylinux2014_x86_64.whl", hash = "sha256:f1dd09b481a93c1d4c750013f467f74194493ba7bd29fcd4d1cec16e3a214f65", size = 89942952, upload-time = "2025-06-17T23:11:19.181Z" }, - { url = "https://files.pythonhosted.org/packages/de/3a/06849113c844b86d20174df54735c84202ccf82cbd36d805f478c834418b/jaxlib-0.6.2-cp312-cp312-win_amd64.whl", hash = "sha256:921dbd4db214eba19a29ba9f2450d880e08b2b2c7b968f28cc89da3e62366af4", size = 57919603, upload-time = "2025-06-17T23:11:23.207Z" }, - { url = "https://files.pythonhosted.org/packages/af/38/bed4279c2a3407820ed8bcd72dbad43c330ada35f88fafe9952b35abf785/jaxlib-0.6.2-cp313-cp313-macosx_11_0_arm64.whl", hash = "sha256:bff67b188133ce1f0111c7b163ac321fd646b59ed221ea489063e2e0f85cb967", size = 54300638, upload-time = "2025-06-17T23:11:26.372Z" }, - { url = "https://files.pythonhosted.org/packages/52/dc/9e35a1dc089ddf3d6be53ef2e6ba4718c5b6c0f90bccc535a20edac0c895/jaxlib-0.6.2-cp313-cp313-manylinux2014_aarch64.whl", hash = "sha256:70498837caf538bd458ff6858c8bfd404db82015aba8f663670197fa9900ff02", size = 79439983, upload-time = "2025-06-17T23:11:30.016Z" }, - { url = "https://files.pythonhosted.org/packages/34/16/e93f0184b80a4e1ad38c6998aa3a2f7569c0b0152cbae39f7572393eda04/jaxlib-0.6.2-cp313-cp313-manylinux2014_x86_64.whl", hash = "sha256:f94163f14c8fd3ba93ae14b631abacf14cb031bba0b59138869984b4d10375f8", size = 89941720, upload-time = "2025-06-17T23:11:34.62Z" }, - { url = "https://files.pythonhosted.org/packages/06/b9/ea50792ee0333dba764e06c305fe098bce1cb938dcb66fbe2fc47ef5dd02/jaxlib-0.6.2-cp313-cp313-win_amd64.whl", hash = "sha256:b977604cd36c74b174d25ed685017379468138eb747d865f75e466cb273c801d", size = 57919073, upload-time = "2025-06-17T23:11:39.344Z" }, - { url = "https://files.pythonhosted.org/packages/09/ce/9596391c104a0547fcaf6a8c72078bbae79dbc8e7f0843dc8318f6606328/jaxlib-0.6.2-cp313-cp313t-manylinux2014_aarch64.whl", hash = "sha256:39cf9555f85ae1ce2e2c1a59fc71f2eca4f9867a7cb934fef881ba56b11371d1", size = 79579638, upload-time = "2025-06-17T23:11:43.054Z" }, - { url = "https://files.pythonhosted.org/packages/10/79/f6e80f7f4cacfc9f03e64ac57ecb856b140de7c2f939b25f8dcf1aff63f9/jaxlib-0.6.2-cp313-cp313t-manylinux2014_x86_64.whl", hash = "sha256:3abd536e44b05fb1657507e3ff1fc3691f99613bae3921ecab9e82f27255f784", size = 90066675, upload-time = "2025-06-17T23:11:47.454Z" }, -] - [[package]] name = "jaxlib" version = "0.7.2" source = { registry = "https://pypi.org/simple" } -resolution-markers = [ - "python_full_version >= '3.13'", - "python_full_version == '3.12.*'", - "python_full_version == '3.11.*'", -] dependencies = [ - { name = "ml-dtypes", marker = "python_full_version >= '3.11'" }, - { name = "numpy", version = "2.3.3", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version >= '3.11'" }, - { name = "scipy", version = "1.16.2", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version >= '3.11'" }, + { name = "ml-dtypes" }, + { name = "numpy" }, + { name = "scipy" }, ] wheels = [ { url = "https://files.pythonhosted.org/packages/55/fe/41e1df8a02acdc12472b2922e41495cf0a9b805f5fd1f163c9aaf81b30df/jaxlib-0.7.2-cp311-cp311-macosx_11_0_arm64.whl", hash = "sha256:9fbf90afce30e34eba2ea929a506f5907bdd4062358122de499ce9e671a0ba1f", size = 53550443, upload-time = "2025-09-16T16:49:04.061Z" }, @@ -622,8 +477,7 @@ name = "jmp" version = "0.0.4" source = { registry = "https://pypi.org/simple" } dependencies = [ - { name = "numpy", version = "2.2.6", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version < '3.11'" }, - { name = "numpy", version = "2.3.3", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version >= '3.11'" }, + { name = "numpy" }, ] sdist = { url = "https://files.pythonhosted.org/packages/ab/b0/e90fbbffef4b345329c878a69f0336d3edc5a1f9fcba193931aca2132d62/jmp-0.0.4.tar.gz", hash = "sha256:5dfeb0fd7c7a9f72a70fff0aab9d0cbfae32a809c02f4037ff3485ceb33e1730", size = 18582, upload-time = "2023-01-30T12:47:13.634Z" } wheels = [ @@ -657,17 +511,6 @@ version = "3.0.3" source = { registry = "https://pypi.org/simple" } sdist = { url = "https://files.pythonhosted.org/packages/7e/99/7690b6d4034fffd95959cbe0c02de8deb3098cc577c67bb6a24fe5d7caa7/markupsafe-3.0.3.tar.gz", hash = "sha256:722695808f4b6457b320fdc131280796bdceb04ab50fe1795cd540799ebe1698", size = 80313, upload-time = "2025-09-27T18:37:40.426Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/e8/4b/3541d44f3937ba468b75da9eebcae497dcf67adb65caa16760b0a6807ebb/markupsafe-3.0.3-cp310-cp310-macosx_10_9_x86_64.whl", hash = "sha256:2f981d352f04553a7171b8e44369f2af4055f888dfb147d55e42d29e29e74559", size = 11631, upload-time = "2025-09-27T18:36:05.558Z" }, - { url = "https://files.pythonhosted.org/packages/98/1b/fbd8eed11021cabd9226c37342fa6ca4e8a98d8188a8d9b66740494960e4/markupsafe-3.0.3-cp310-cp310-macosx_11_0_arm64.whl", hash = "sha256:e1c1493fb6e50ab01d20a22826e57520f1284df32f2d8601fdd90b6304601419", size = 12057, upload-time = "2025-09-27T18:36:07.165Z" }, - { url = "https://files.pythonhosted.org/packages/40/01/e560d658dc0bb8ab762670ece35281dec7b6c1b33f5fbc09ebb57a185519/markupsafe-3.0.3-cp310-cp310-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:1ba88449deb3de88bd40044603fafffb7bc2b055d626a330323a9ed736661695", size = 22050, upload-time = "2025-09-27T18:36:08.005Z" }, - { url = "https://files.pythonhosted.org/packages/af/cd/ce6e848bbf2c32314c9b237839119c5a564a59725b53157c856e90937b7a/markupsafe-3.0.3-cp310-cp310-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:f42d0984e947b8adf7dd6dde396e720934d12c506ce84eea8476409563607591", size = 20681, upload-time = "2025-09-27T18:36:08.881Z" }, - { url = "https://files.pythonhosted.org/packages/c9/2a/b5c12c809f1c3045c4d580b035a743d12fcde53cf685dbc44660826308da/markupsafe-3.0.3-cp310-cp310-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:c0c0b3ade1c0b13b936d7970b1d37a57acde9199dc2aecc4c336773e1d86049c", size = 20705, upload-time = "2025-09-27T18:36:10.131Z" }, - { url = "https://files.pythonhosted.org/packages/cf/e3/9427a68c82728d0a88c50f890d0fc072a1484de2f3ac1ad0bfc1a7214fd5/markupsafe-3.0.3-cp310-cp310-musllinux_1_2_aarch64.whl", hash = "sha256:0303439a41979d9e74d18ff5e2dd8c43ed6c6001fd40e5bf2e43f7bd9bbc523f", size = 21524, upload-time = "2025-09-27T18:36:11.324Z" }, - { url = "https://files.pythonhosted.org/packages/bc/36/23578f29e9e582a4d0278e009b38081dbe363c5e7165113fad546918a232/markupsafe-3.0.3-cp310-cp310-musllinux_1_2_riscv64.whl", hash = "sha256:d2ee202e79d8ed691ceebae8e0486bd9a2cd4794cec4824e1c99b6f5009502f6", size = 20282, upload-time = "2025-09-27T18:36:12.573Z" }, - { url = "https://files.pythonhosted.org/packages/56/21/dca11354e756ebd03e036bd8ad58d6d7168c80ce1fe5e75218e4945cbab7/markupsafe-3.0.3-cp310-cp310-musllinux_1_2_x86_64.whl", hash = "sha256:177b5253b2834fe3678cb4a5f0059808258584c559193998be2601324fdeafb1", size = 20745, upload-time = "2025-09-27T18:36:13.504Z" }, - { url = "https://files.pythonhosted.org/packages/87/99/faba9369a7ad6e4d10b6a5fbf71fa2a188fe4a593b15f0963b73859a1bbd/markupsafe-3.0.3-cp310-cp310-win32.whl", hash = "sha256:2a15a08b17dd94c53a1da0438822d70ebcd13f8c3a95abe3a9ef9f11a94830aa", size = 14571, upload-time = "2025-09-27T18:36:14.779Z" }, - { url = "https://files.pythonhosted.org/packages/d6/25/55dc3ab959917602c96985cb1253efaa4ff42f71194bddeb61eb7278b8be/markupsafe-3.0.3-cp310-cp310-win_amd64.whl", hash = "sha256:c4ffb7ebf07cfe8931028e3e4c85f0357459a3f9f9490886198848f4fa002ec8", size = 15056, upload-time = "2025-09-27T18:36:16.125Z" }, - { url = "https://files.pythonhosted.org/packages/d0/9e/0a02226640c255d1da0b8d12e24ac2aa6734da68bff14c05dd53b94a0fc3/markupsafe-3.0.3-cp310-cp310-win_arm64.whl", hash = "sha256:e2103a929dfa2fcaf9bb4e7c091983a49c9ac3b19c9061b6d5427dd7d14d81a1", size = 13932, upload-time = "2025-09-27T18:36:17.311Z" }, { url = "https://files.pythonhosted.org/packages/08/db/fefacb2136439fc8dd20e797950e749aa1f4997ed584c62cfb8ef7c2be0e/markupsafe-3.0.3-cp311-cp311-macosx_10_9_x86_64.whl", hash = "sha256:1cc7ea17a6824959616c525620e387f6dd30fec8cb44f649e31712db02123dad", size = 11631, upload-time = "2025-09-27T18:36:18.185Z" }, { url = "https://files.pythonhosted.org/packages/e1/2e/5898933336b61975ce9dc04decbc0a7f2fee78c30353c5efba7f2d6ff27a/markupsafe-3.0.3-cp311-cp311-macosx_11_0_arm64.whl", hash = "sha256:4bd4cd07944443f5a265608cc6aab442e4f74dff8088b0dfc8238647b8f6ae9a", size = 12058, upload-time = "2025-09-27T18:36:19.444Z" }, { url = "https://files.pythonhosted.org/packages/1d/09/adf2df3699d87d1d8184038df46a9c80d78c0148492323f4693df54e17bb/markupsafe-3.0.3-cp311-cp311-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:6b5420a1d9450023228968e7e6a9ce57f65d148ab56d2313fcd589eee96a7a50", size = 24287, upload-time = "2025-09-27T18:36:20.768Z" }, @@ -907,7 +750,6 @@ dependencies = [ { name = "griffe" }, { name = "mkdocs-autorefs" }, { name = "mkdocstrings" }, - { name = "typing-extensions", marker = "python_full_version < '3.11'" }, ] sdist = { url = "https://files.pythonhosted.org/packages/95/ae/58ab2bfbee2792e92a98b97e872f7c003deb903071f75d8d83aa55db28fa/mkdocstrings_python-1.18.2.tar.gz", hash = "sha256:4ad536920a07b6336f50d4c6d5603316fafb1172c5c882370cbbc954770ad323", size = 207972, upload-time = "2025-08-28T16:11:19.847Z" } wheels = [ @@ -919,15 +761,10 @@ name = "ml-dtypes" version = "0.5.3" source = { registry = "https://pypi.org/simple" } dependencies = [ - { name = "numpy", version = "2.2.6", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version < '3.11'" }, - { name = "numpy", version = "2.3.3", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version >= '3.11'" }, + { name = "numpy" }, ] sdist = { url = "https://files.pythonhosted.org/packages/78/a7/aad060393123cfb383956dca68402aff3db1e1caffd5764887ed5153f41b/ml_dtypes-0.5.3.tar.gz", hash = "sha256:95ce33057ba4d05df50b1f3cfefab22e351868a843b3b15a46c65836283670c9", size = 692316, upload-time = "2025-07-29T18:39:19.454Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/ac/bb/1f32124ab6d3a279ea39202fe098aea95b2d81ef0ce1d48612b6bf715e82/ml_dtypes-0.5.3-cp310-cp310-macosx_10_9_universal2.whl", hash = "sha256:0a1d68a7cb53e3f640b2b6a34d12c0542da3dd935e560fdf463c0c77f339fc20", size = 667409, upload-time = "2025-07-29T18:38:17.321Z" }, - { url = "https://files.pythonhosted.org/packages/1d/ac/e002d12ae19136e25bb41c7d14d7e1a1b08f3c0e99a44455ff6339796507/ml_dtypes-0.5.3-cp310-cp310-manylinux_2_27_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:0cd5a6c711b5350f3cbc2ac28def81cd1c580075ccb7955e61e9d8f4bfd40d24", size = 4960702, upload-time = "2025-07-29T18:38:19.616Z" }, - { url = "https://files.pythonhosted.org/packages/dd/12/79e9954e6b3255a4b1becb191a922d6e2e94d03d16a06341ae9261963ae8/ml_dtypes-0.5.3-cp310-cp310-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:bdcf26c2dbc926b8a35ec8cbfad7eff1a8bd8239e12478caca83a1fc2c400dc2", size = 4933471, upload-time = "2025-07-29T18:38:21.809Z" }, - { url = "https://files.pythonhosted.org/packages/d5/aa/d1eff619e83cd1ddf6b561d8240063d978e5d887d1861ba09ef01778ec3a/ml_dtypes-0.5.3-cp310-cp310-win_amd64.whl", hash = "sha256:aecbd7c5272c82e54d5b99d8435fd10915d1bc704b7df15e4d9ca8dc3902be61", size = 206330, upload-time = "2025-07-29T18:38:23.663Z" }, { url = "https://files.pythonhosted.org/packages/af/f1/720cb1409b5d0c05cff9040c0e9fba73fa4c67897d33babf905d5d46a070/ml_dtypes-0.5.3-cp311-cp311-macosx_10_9_universal2.whl", hash = "sha256:4a177b882667c69422402df6ed5c3428ce07ac2c1f844d8a1314944651439458", size = 667412, upload-time = "2025-07-29T18:38:25.275Z" }, { url = "https://files.pythonhosted.org/packages/6a/d5/05861ede5d299f6599f86e6bc1291714e2116d96df003cfe23cc54bcc568/ml_dtypes-0.5.3-cp311-cp311-manylinux_2_27_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:9849ce7267444c0a717c80c6900997de4f36e2815ce34ac560a3edb2d9a64cd2", size = 4964606, upload-time = "2025-07-29T18:38:27.045Z" }, { url = "https://files.pythonhosted.org/packages/db/dc/72992b68de367741bfab8df3b3fe7c29f982b7279d341aa5bf3e7ef737ea/ml_dtypes-0.5.3-cp311-cp311-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:c3f5ae0309d9f888fd825c2e9d0241102fadaca81d888f26f845bc8c13c1e4ee", size = 4938435, upload-time = "2025-07-29T18:38:29.193Z" }, @@ -962,16 +799,6 @@ version = "1.1.1" source = { registry = "https://pypi.org/simple" } sdist = { url = "https://files.pythonhosted.org/packages/45/b1/ea4f68038a18c77c9467400d166d74c4ffa536f34761f7983a104357e614/msgpack-1.1.1.tar.gz", hash = "sha256:77b79ce34a2bdab2594f490c8e80dd62a02d650b91a75159a63ec413b8d104cd", size = 173555, upload-time = "2025-06-13T06:52:51.324Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/33/52/f30da112c1dc92cf64f57d08a273ac771e7b29dea10b4b30369b2d7e8546/msgpack-1.1.1-cp310-cp310-macosx_10_9_x86_64.whl", hash = "sha256:353b6fc0c36fde68b661a12949d7d49f8f51ff5fa019c1e47c87c4ff34b080ed", size = 81799, upload-time = "2025-06-13T06:51:37.228Z" }, - { url = "https://files.pythonhosted.org/packages/e4/35/7bfc0def2f04ab4145f7f108e3563f9b4abae4ab0ed78a61f350518cc4d2/msgpack-1.1.1-cp310-cp310-macosx_11_0_arm64.whl", hash = "sha256:79c408fcf76a958491b4e3b103d1c417044544b68e96d06432a189b43d1215c8", size = 78278, upload-time = "2025-06-13T06:51:38.534Z" }, - { url = "https://files.pythonhosted.org/packages/e8/c5/df5d6c1c39856bc55f800bf82778fd4c11370667f9b9e9d51b2f5da88f20/msgpack-1.1.1-cp310-cp310-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:78426096939c2c7482bf31ef15ca219a9e24460289c00dd0b94411040bb73ad2", size = 402805, upload-time = "2025-06-13T06:51:39.538Z" }, - { url = "https://files.pythonhosted.org/packages/20/8e/0bb8c977efecfe6ea7116e2ed73a78a8d32a947f94d272586cf02a9757db/msgpack-1.1.1-cp310-cp310-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:8b17ba27727a36cb73aabacaa44b13090feb88a01d012c0f4be70c00f75048b4", size = 408642, upload-time = "2025-06-13T06:51:41.092Z" }, - { url = "https://files.pythonhosted.org/packages/59/a1/731d52c1aeec52006be6d1f8027c49fdc2cfc3ab7cbe7c28335b2910d7b6/msgpack-1.1.1-cp310-cp310-manylinux_2_5_i686.manylinux1_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:7a17ac1ea6ec3c7687d70201cfda3b1e8061466f28f686c24f627cae4ea8efd0", size = 395143, upload-time = "2025-06-13T06:51:42.575Z" }, - { url = "https://files.pythonhosted.org/packages/2b/92/b42911c52cda2ba67a6418ffa7d08969edf2e760b09015593c8a8a27a97d/msgpack-1.1.1-cp310-cp310-musllinux_1_2_aarch64.whl", hash = "sha256:88d1e966c9235c1d4e2afac21ca83933ba59537e2e2727a999bf3f515ca2af26", size = 395986, upload-time = "2025-06-13T06:51:43.807Z" }, - { url = "https://files.pythonhosted.org/packages/61/dc/8ae165337e70118d4dab651b8b562dd5066dd1e6dd57b038f32ebc3e2f07/msgpack-1.1.1-cp310-cp310-musllinux_1_2_i686.whl", hash = "sha256:f6d58656842e1b2ddbe07f43f56b10a60f2ba5826164910968f5933e5178af75", size = 402682, upload-time = "2025-06-13T06:51:45.534Z" }, - { url = "https://files.pythonhosted.org/packages/58/27/555851cb98dcbd6ce041df1eacb25ac30646575e9cd125681aa2f4b1b6f1/msgpack-1.1.1-cp310-cp310-musllinux_1_2_x86_64.whl", hash = "sha256:96decdfc4adcbc087f5ea7ebdcfd3dee9a13358cae6e81d54be962efc38f6338", size = 406368, upload-time = "2025-06-13T06:51:46.97Z" }, - { url = "https://files.pythonhosted.org/packages/d4/64/39a26add4ce16f24e99eabb9005e44c663db00e3fce17d4ae1ae9d61df99/msgpack-1.1.1-cp310-cp310-win32.whl", hash = "sha256:6640fd979ca9a212e4bcdf6eb74051ade2c690b862b679bfcb60ae46e6dc4bfd", size = 65004, upload-time = "2025-06-13T06:51:48.582Z" }, - { url = "https://files.pythonhosted.org/packages/7d/18/73dfa3e9d5d7450d39debde5b0d848139f7de23bd637a4506e36c9800fd6/msgpack-1.1.1-cp310-cp310-win_amd64.whl", hash = "sha256:8b65b53204fe1bd037c40c4148d00ef918eb2108d24c9aaa20bc31f9810ce0a8", size = 71548, upload-time = "2025-06-13T06:51:49.558Z" }, { url = "https://files.pythonhosted.org/packages/7f/83/97f24bf9848af23fe2ba04380388216defc49a8af6da0c28cc636d722502/msgpack-1.1.1-cp311-cp311-macosx_10_9_x86_64.whl", hash = "sha256:71ef05c1726884e44f8b1d1773604ab5d4d17729d8491403a705e649116c9558", size = 82728, upload-time = "2025-06-13T06:51:50.68Z" }, { url = "https://files.pythonhosted.org/packages/aa/7f/2eaa388267a78401f6e182662b08a588ef4f3de6f0eab1ec09736a7aaa2b/msgpack-1.1.1-cp311-cp311-macosx_11_0_arm64.whl", hash = "sha256:36043272c6aede309d29d56851f8841ba907a1a3d04435e43e8a19928e243c1d", size = 79279, upload-time = "2025-06-13T06:51:51.72Z" }, { url = "https://files.pythonhosted.org/packages/f8/46/31eb60f4452c96161e4dfd26dbca562b4ec68c72e4ad07d9566d7ea35e8a/msgpack-1.1.1-cp311-cp311-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:a32747b1b39c3ac27d0670122b57e6e57f28eefb725e0b625618d1b59bf9d1e0", size = 423859, upload-time = "2025-06-13T06:51:52.749Z" }, @@ -1011,17 +838,10 @@ source = { registry = "https://pypi.org/simple" } dependencies = [ { name = "mypy-extensions" }, { name = "pathspec" }, - { name = "tomli", marker = "python_full_version < '3.11'" }, { name = "typing-extensions" }, ] sdist = { url = "https://files.pythonhosted.org/packages/c0/77/8f0d0001ffad290cef2f7f216f96c814866248a0b92a722365ed54648e7e/mypy-1.18.2.tar.gz", hash = "sha256:06a398102a5f203d7477b2923dda3634c36727fa5c237d8f859ef90c42a9924b", size = 3448846, upload-time = "2025-09-19T00:11:10.519Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/03/6f/657961a0743cff32e6c0611b63ff1c1970a0b482ace35b069203bf705187/mypy-1.18.2-cp310-cp310-macosx_10_9_x86_64.whl", hash = "sha256:c1eab0cf6294dafe397c261a75f96dc2c31bffe3b944faa24db5def4e2b0f77c", size = 12807973, upload-time = "2025-09-19T00:10:35.282Z" }, - { url = "https://files.pythonhosted.org/packages/10/e9/420822d4f661f13ca8900f5fa239b40ee3be8b62b32f3357df9a3045a08b/mypy-1.18.2-cp310-cp310-macosx_11_0_arm64.whl", hash = "sha256:7a780ca61fc239e4865968ebc5240bb3bf610ef59ac398de9a7421b54e4a207e", size = 11896527, upload-time = "2025-09-19T00:10:55.791Z" }, - { url = "https://files.pythonhosted.org/packages/aa/73/a05b2bbaa7005f4642fcfe40fb73f2b4fb6bb44229bd585b5878e9a87ef8/mypy-1.18.2-cp310-cp310-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:448acd386266989ef11662ce3c8011fd2a7b632e0ec7d61a98edd8e27472225b", size = 12507004, upload-time = "2025-09-19T00:11:05.411Z" }, - { url = "https://files.pythonhosted.org/packages/4f/01/f6e4b9f0d031c11ccbd6f17da26564f3a0f3c4155af344006434b0a05a9d/mypy-1.18.2-cp310-cp310-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:f9e171c465ad3901dc652643ee4bffa8e9fef4d7d0eece23b428908c77a76a66", size = 13245947, upload-time = "2025-09-19T00:10:46.923Z" }, - { url = "https://files.pythonhosted.org/packages/d7/97/19727e7499bfa1ae0773d06afd30ac66a58ed7437d940c70548634b24185/mypy-1.18.2-cp310-cp310-musllinux_1_2_x86_64.whl", hash = "sha256:592ec214750bc00741af1f80cbf96b5013d81486b7bb24cb052382c19e40b428", size = 13499217, upload-time = "2025-09-19T00:09:39.472Z" }, - { url = "https://files.pythonhosted.org/packages/9f/4f/90dc8c15c1441bf31cf0f9918bb077e452618708199e530f4cbd5cede6ff/mypy-1.18.2-cp310-cp310-win_amd64.whl", hash = "sha256:7fb95f97199ea11769ebe3638c29b550b5221e997c63b14ef93d2e971606ebed", size = 9766753, upload-time = "2025-09-19T00:10:49.161Z" }, { url = "https://files.pythonhosted.org/packages/88/87/cafd3ae563f88f94eec33f35ff722d043e09832ea8530ef149ec1efbaf08/mypy-1.18.2-cp311-cp311-macosx_10_9_x86_64.whl", hash = "sha256:807d9315ab9d464125aa9fcf6d84fde6e1dc67da0b6f80e7405506b8ac72bc7f", size = 12731198, upload-time = "2025-09-19T00:09:44.857Z" }, { url = "https://files.pythonhosted.org/packages/0f/e0/1e96c3d4266a06d4b0197ace5356d67d937d8358e2ee3ffac71faa843724/mypy-1.18.2-cp311-cp311-macosx_11_0_arm64.whl", hash = "sha256:776bb00de1778caf4db739c6e83919c1d85a448f71979b6a0edd774ea8399341", size = 11817879, upload-time = "2025-09-19T00:09:47.131Z" }, { url = "https://files.pythonhosted.org/packages/72/ef/0c9ba89eb03453e76bdac5a78b08260a848c7bfc5d6603634774d9cd9525/mypy-1.18.2-cp311-cp311-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:1379451880512ffce14505493bd9fe469e0697543717298242574882cf8cdb8d", size = 12427292, upload-time = "2025-09-19T00:10:22.472Z" }, @@ -1076,80 +896,10 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/d2/1d/1b658dbd2b9fa9c4c9f32accbfc0205d532c8c6194dc0f2a4c0428e7128a/nodeenv-1.9.1-py2.py3-none-any.whl", hash = "sha256:ba11c9782d29c27c70ffbdda2d7415098754709be8a7056d79a737cd901155c9", size = 22314, upload-time = "2024-06-04T18:44:08.352Z" }, ] -[[package]] -name = "numpy" -version = "2.2.6" -source = { registry = "https://pypi.org/simple" } -resolution-markers = [ - "python_full_version < '3.11'", -] -sdist = { url = "https://files.pythonhosted.org/packages/76/21/7d2a95e4bba9dc13d043ee156a356c0a8f0c6309dff6b21b4d71a073b8a8/numpy-2.2.6.tar.gz", hash = "sha256:e29554e2bef54a90aa5cc07da6ce955accb83f21ab5de01a62c8478897b264fd", size = 20276440, upload-time = "2025-05-17T22:38:04.611Z" } -wheels = [ - { url = "https://files.pythonhosted.org/packages/9a/3e/ed6db5be21ce87955c0cbd3009f2803f59fa08df21b5df06862e2d8e2bdd/numpy-2.2.6-cp310-cp310-macosx_10_9_x86_64.whl", hash = "sha256:b412caa66f72040e6d268491a59f2c43bf03eb6c96dd8f0307829feb7fa2b6fb", size = 21165245, upload-time = "2025-05-17T21:27:58.555Z" }, - { url = "https://files.pythonhosted.org/packages/22/c2/4b9221495b2a132cc9d2eb862e21d42a009f5a60e45fc44b00118c174bff/numpy-2.2.6-cp310-cp310-macosx_11_0_arm64.whl", hash = "sha256:8e41fd67c52b86603a91c1a505ebaef50b3314de0213461c7a6e99c9a3beff90", size = 14360048, upload-time = "2025-05-17T21:28:21.406Z" }, - { url = "https://files.pythonhosted.org/packages/fd/77/dc2fcfc66943c6410e2bf598062f5959372735ffda175b39906d54f02349/numpy-2.2.6-cp310-cp310-macosx_14_0_arm64.whl", hash = "sha256:37e990a01ae6ec7fe7fa1c26c55ecb672dd98b19c3d0e1d1f326fa13cb38d163", size = 5340542, upload-time = "2025-05-17T21:28:30.931Z" }, - { url = "https://files.pythonhosted.org/packages/7a/4f/1cb5fdc353a5f5cc7feb692db9b8ec2c3d6405453f982435efc52561df58/numpy-2.2.6-cp310-cp310-macosx_14_0_x86_64.whl", hash = "sha256:5a6429d4be8ca66d889b7cf70f536a397dc45ba6faeb5f8c5427935d9592e9cf", size = 6878301, upload-time = "2025-05-17T21:28:41.613Z" }, - { url = "https://files.pythonhosted.org/packages/eb/17/96a3acd228cec142fcb8723bd3cc39c2a474f7dcf0a5d16731980bcafa95/numpy-2.2.6-cp310-cp310-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:efd28d4e9cd7d7a8d39074a4d44c63eda73401580c5c76acda2ce969e0a38e83", size = 14297320, upload-time = "2025-05-17T21:29:02.78Z" }, - { url = "https://files.pythonhosted.org/packages/b4/63/3de6a34ad7ad6646ac7d2f55ebc6ad439dbbf9c4370017c50cf403fb19b5/numpy-2.2.6-cp310-cp310-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:fc7b73d02efb0e18c000e9ad8b83480dfcd5dfd11065997ed4c6747470ae8915", size = 16801050, upload-time = "2025-05-17T21:29:27.675Z" }, - { url = "https://files.pythonhosted.org/packages/07/b6/89d837eddef52b3d0cec5c6ba0456c1bf1b9ef6a6672fc2b7873c3ec4e2e/numpy-2.2.6-cp310-cp310-musllinux_1_2_aarch64.whl", hash = "sha256:74d4531beb257d2c3f4b261bfb0fc09e0f9ebb8842d82a7b4209415896adc680", size = 15807034, upload-time = "2025-05-17T21:29:51.102Z" }, - { url = "https://files.pythonhosted.org/packages/01/c8/dc6ae86e3c61cfec1f178e5c9f7858584049b6093f843bca541f94120920/numpy-2.2.6-cp310-cp310-musllinux_1_2_x86_64.whl", hash = "sha256:8fc377d995680230e83241d8a96def29f204b5782f371c532579b4f20607a289", size = 18614185, upload-time = "2025-05-17T21:30:18.703Z" }, - { url = "https://files.pythonhosted.org/packages/5b/c5/0064b1b7e7c89137b471ccec1fd2282fceaae0ab3a9550f2568782d80357/numpy-2.2.6-cp310-cp310-win32.whl", hash = "sha256:b093dd74e50a8cba3e873868d9e93a85b78e0daf2e98c6797566ad8044e8363d", size = 6527149, upload-time = "2025-05-17T21:30:29.788Z" }, - { url = "https://files.pythonhosted.org/packages/a3/dd/4b822569d6b96c39d1215dbae0582fd99954dcbcf0c1a13c61783feaca3f/numpy-2.2.6-cp310-cp310-win_amd64.whl", hash = "sha256:f0fd6321b839904e15c46e0d257fdd101dd7f530fe03fd6359c1ea63738703f3", size = 12904620, upload-time = "2025-05-17T21:30:48.994Z" }, - { url = "https://files.pythonhosted.org/packages/da/a8/4f83e2aa666a9fbf56d6118faaaf5f1974d456b1823fda0a176eff722839/numpy-2.2.6-cp311-cp311-macosx_10_9_x86_64.whl", hash = "sha256:f9f1adb22318e121c5c69a09142811a201ef17ab257a1e66ca3025065b7f53ae", size = 21176963, upload-time = "2025-05-17T21:31:19.36Z" }, - { url = "https://files.pythonhosted.org/packages/b3/2b/64e1affc7972decb74c9e29e5649fac940514910960ba25cd9af4488b66c/numpy-2.2.6-cp311-cp311-macosx_11_0_arm64.whl", hash = "sha256:c820a93b0255bc360f53eca31a0e676fd1101f673dda8da93454a12e23fc5f7a", size = 14406743, upload-time = "2025-05-17T21:31:41.087Z" }, - { url = "https://files.pythonhosted.org/packages/4a/9f/0121e375000b5e50ffdd8b25bf78d8e1a5aa4cca3f185d41265198c7b834/numpy-2.2.6-cp311-cp311-macosx_14_0_arm64.whl", hash = "sha256:3d70692235e759f260c3d837193090014aebdf026dfd167834bcba43e30c2a42", size = 5352616, upload-time = "2025-05-17T21:31:50.072Z" }, - { url = "https://files.pythonhosted.org/packages/31/0d/b48c405c91693635fbe2dcd7bc84a33a602add5f63286e024d3b6741411c/numpy-2.2.6-cp311-cp311-macosx_14_0_x86_64.whl", hash = "sha256:481b49095335f8eed42e39e8041327c05b0f6f4780488f61286ed3c01368d491", size = 6889579, upload-time = "2025-05-17T21:32:01.712Z" }, - { url = "https://files.pythonhosted.org/packages/52/b8/7f0554d49b565d0171eab6e99001846882000883998e7b7d9f0d98b1f934/numpy-2.2.6-cp311-cp311-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:b64d8d4d17135e00c8e346e0a738deb17e754230d7e0810ac5012750bbd85a5a", size = 14312005, upload-time = "2025-05-17T21:32:23.332Z" }, - { url = "https://files.pythonhosted.org/packages/b3/dd/2238b898e51bd6d389b7389ffb20d7f4c10066d80351187ec8e303a5a475/numpy-2.2.6-cp311-cp311-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:ba10f8411898fc418a521833e014a77d3ca01c15b0c6cdcce6a0d2897e6dbbdf", size = 16821570, upload-time = "2025-05-17T21:32:47.991Z" }, - { url = "https://files.pythonhosted.org/packages/83/6c/44d0325722cf644f191042bf47eedad61c1e6df2432ed65cbe28509d404e/numpy-2.2.6-cp311-cp311-musllinux_1_2_aarch64.whl", hash = "sha256:bd48227a919f1bafbdda0583705e547892342c26fb127219d60a5c36882609d1", size = 15818548, upload-time = "2025-05-17T21:33:11.728Z" }, - { url = "https://files.pythonhosted.org/packages/ae/9d/81e8216030ce66be25279098789b665d49ff19eef08bfa8cb96d4957f422/numpy-2.2.6-cp311-cp311-musllinux_1_2_x86_64.whl", hash = "sha256:9551a499bf125c1d4f9e250377c1ee2eddd02e01eac6644c080162c0c51778ab", size = 18620521, upload-time = "2025-05-17T21:33:39.139Z" }, - { url = "https://files.pythonhosted.org/packages/6a/fd/e19617b9530b031db51b0926eed5345ce8ddc669bb3bc0044b23e275ebe8/numpy-2.2.6-cp311-cp311-win32.whl", hash = "sha256:0678000bb9ac1475cd454c6b8c799206af8107e310843532b04d49649c717a47", size = 6525866, upload-time = "2025-05-17T21:33:50.273Z" }, - { url = "https://files.pythonhosted.org/packages/31/0a/f354fb7176b81747d870f7991dc763e157a934c717b67b58456bc63da3df/numpy-2.2.6-cp311-cp311-win_amd64.whl", hash = "sha256:e8213002e427c69c45a52bbd94163084025f533a55a59d6f9c5b820774ef3303", size = 12907455, upload-time = "2025-05-17T21:34:09.135Z" }, - { url = "https://files.pythonhosted.org/packages/82/5d/c00588b6cf18e1da539b45d3598d3557084990dcc4331960c15ee776ee41/numpy-2.2.6-cp312-cp312-macosx_10_13_x86_64.whl", hash = "sha256:41c5a21f4a04fa86436124d388f6ed60a9343a6f767fced1a8a71c3fbca038ff", size = 20875348, upload-time = "2025-05-17T21:34:39.648Z" }, - { url = "https://files.pythonhosted.org/packages/66/ee/560deadcdde6c2f90200450d5938f63a34b37e27ebff162810f716f6a230/numpy-2.2.6-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:de749064336d37e340f640b05f24e9e3dd678c57318c7289d222a8a2f543e90c", size = 14119362, upload-time = "2025-05-17T21:35:01.241Z" }, - { url = "https://files.pythonhosted.org/packages/3c/65/4baa99f1c53b30adf0acd9a5519078871ddde8d2339dc5a7fde80d9d87da/numpy-2.2.6-cp312-cp312-macosx_14_0_arm64.whl", hash = "sha256:894b3a42502226a1cac872f840030665f33326fc3dac8e57c607905773cdcde3", size = 5084103, upload-time = "2025-05-17T21:35:10.622Z" }, - { url = "https://files.pythonhosted.org/packages/cc/89/e5a34c071a0570cc40c9a54eb472d113eea6d002e9ae12bb3a8407fb912e/numpy-2.2.6-cp312-cp312-macosx_14_0_x86_64.whl", hash = "sha256:71594f7c51a18e728451bb50cc60a3ce4e6538822731b2933209a1f3614e9282", size = 6625382, upload-time = "2025-05-17T21:35:21.414Z" }, - { url = "https://files.pythonhosted.org/packages/f8/35/8c80729f1ff76b3921d5c9487c7ac3de9b2a103b1cd05e905b3090513510/numpy-2.2.6-cp312-cp312-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:f2618db89be1b4e05f7a1a847a9c1c0abd63e63a1607d892dd54668dd92faf87", size = 14018462, upload-time = "2025-05-17T21:35:42.174Z" }, - { url = "https://files.pythonhosted.org/packages/8c/3d/1e1db36cfd41f895d266b103df00ca5b3cbe965184df824dec5c08c6b803/numpy-2.2.6-cp312-cp312-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:fd83c01228a688733f1ded5201c678f0c53ecc1006ffbc404db9f7a899ac6249", size = 16527618, upload-time = "2025-05-17T21:36:06.711Z" }, - { url = "https://files.pythonhosted.org/packages/61/c6/03ed30992602c85aa3cd95b9070a514f8b3c33e31124694438d88809ae36/numpy-2.2.6-cp312-cp312-musllinux_1_2_aarch64.whl", hash = "sha256:37c0ca431f82cd5fa716eca9506aefcabc247fb27ba69c5062a6d3ade8cf8f49", size = 15505511, upload-time = "2025-05-17T21:36:29.965Z" }, - { url = "https://files.pythonhosted.org/packages/b7/25/5761d832a81df431e260719ec45de696414266613c9ee268394dd5ad8236/numpy-2.2.6-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:fe27749d33bb772c80dcd84ae7e8df2adc920ae8297400dabec45f0dedb3f6de", size = 18313783, upload-time = "2025-05-17T21:36:56.883Z" }, - { url = "https://files.pythonhosted.org/packages/57/0a/72d5a3527c5ebffcd47bde9162c39fae1f90138c961e5296491ce778e682/numpy-2.2.6-cp312-cp312-win32.whl", hash = "sha256:4eeaae00d789f66c7a25ac5f34b71a7035bb474e679f410e5e1a94deb24cf2d4", size = 6246506, upload-time = "2025-05-17T21:37:07.368Z" }, - { url = "https://files.pythonhosted.org/packages/36/fa/8c9210162ca1b88529ab76b41ba02d433fd54fecaf6feb70ef9f124683f1/numpy-2.2.6-cp312-cp312-win_amd64.whl", hash = "sha256:c1f9540be57940698ed329904db803cf7a402f3fc200bfe599334c9bd84a40b2", size = 12614190, upload-time = "2025-05-17T21:37:26.213Z" }, - { url = "https://files.pythonhosted.org/packages/f9/5c/6657823f4f594f72b5471f1db1ab12e26e890bb2e41897522d134d2a3e81/numpy-2.2.6-cp313-cp313-macosx_10_13_x86_64.whl", hash = "sha256:0811bb762109d9708cca4d0b13c4f67146e3c3b7cf8d34018c722adb2d957c84", size = 20867828, upload-time = "2025-05-17T21:37:56.699Z" }, - { url = "https://files.pythonhosted.org/packages/dc/9e/14520dc3dadf3c803473bd07e9b2bd1b69bc583cb2497b47000fed2fa92f/numpy-2.2.6-cp313-cp313-macosx_11_0_arm64.whl", hash = "sha256:287cc3162b6f01463ccd86be154f284d0893d2b3ed7292439ea97eafa8170e0b", size = 14143006, upload-time = "2025-05-17T21:38:18.291Z" }, - { url = "https://files.pythonhosted.org/packages/4f/06/7e96c57d90bebdce9918412087fc22ca9851cceaf5567a45c1f404480e9e/numpy-2.2.6-cp313-cp313-macosx_14_0_arm64.whl", hash = "sha256:f1372f041402e37e5e633e586f62aa53de2eac8d98cbfb822806ce4bbefcb74d", size = 5076765, upload-time = "2025-05-17T21:38:27.319Z" }, - { url = "https://files.pythonhosted.org/packages/73/ed/63d920c23b4289fdac96ddbdd6132e9427790977d5457cd132f18e76eae0/numpy-2.2.6-cp313-cp313-macosx_14_0_x86_64.whl", hash = "sha256:55a4d33fa519660d69614a9fad433be87e5252f4b03850642f88993f7b2ca566", size = 6617736, upload-time = "2025-05-17T21:38:38.141Z" }, - { url = "https://files.pythonhosted.org/packages/85/c5/e19c8f99d83fd377ec8c7e0cf627a8049746da54afc24ef0a0cb73d5dfb5/numpy-2.2.6-cp313-cp313-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:f92729c95468a2f4f15e9bb94c432a9229d0d50de67304399627a943201baa2f", size = 14010719, upload-time = "2025-05-17T21:38:58.433Z" }, - { url = "https://files.pythonhosted.org/packages/19/49/4df9123aafa7b539317bf6d342cb6d227e49f7a35b99c287a6109b13dd93/numpy-2.2.6-cp313-cp313-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:1bc23a79bfabc5d056d106f9befb8d50c31ced2fbc70eedb8155aec74a45798f", size = 16526072, upload-time = "2025-05-17T21:39:22.638Z" }, - { url = "https://files.pythonhosted.org/packages/b2/6c/04b5f47f4f32f7c2b0e7260442a8cbcf8168b0e1a41ff1495da42f42a14f/numpy-2.2.6-cp313-cp313-musllinux_1_2_aarch64.whl", hash = "sha256:e3143e4451880bed956e706a3220b4e5cf6172ef05fcc397f6f36a550b1dd868", size = 15503213, upload-time = "2025-05-17T21:39:45.865Z" }, - { url = "https://files.pythonhosted.org/packages/17/0a/5cd92e352c1307640d5b6fec1b2ffb06cd0dabe7d7b8227f97933d378422/numpy-2.2.6-cp313-cp313-musllinux_1_2_x86_64.whl", hash = "sha256:b4f13750ce79751586ae2eb824ba7e1e8dba64784086c98cdbbcc6a42112ce0d", size = 18316632, upload-time = "2025-05-17T21:40:13.331Z" }, - { url = "https://files.pythonhosted.org/packages/f0/3b/5cba2b1d88760ef86596ad0f3d484b1cbff7c115ae2429678465057c5155/numpy-2.2.6-cp313-cp313-win32.whl", hash = "sha256:5beb72339d9d4fa36522fc63802f469b13cdbe4fdab4a288f0c441b74272ebfd", size = 6244532, upload-time = "2025-05-17T21:43:46.099Z" }, - { url = "https://files.pythonhosted.org/packages/cb/3b/d58c12eafcb298d4e6d0d40216866ab15f59e55d148a5658bb3132311fcf/numpy-2.2.6-cp313-cp313-win_amd64.whl", hash = "sha256:b0544343a702fa80c95ad5d3d608ea3599dd54d4632df855e4c8d24eb6ecfa1c", size = 12610885, upload-time = "2025-05-17T21:44:05.145Z" }, - { url = "https://files.pythonhosted.org/packages/6b/9e/4bf918b818e516322db999ac25d00c75788ddfd2d2ade4fa66f1f38097e1/numpy-2.2.6-cp313-cp313t-macosx_10_13_x86_64.whl", hash = "sha256:0bca768cd85ae743b2affdc762d617eddf3bcf8724435498a1e80132d04879e6", size = 20963467, upload-time = "2025-05-17T21:40:44Z" }, - { url = "https://files.pythonhosted.org/packages/61/66/d2de6b291507517ff2e438e13ff7b1e2cdbdb7cb40b3ed475377aece69f9/numpy-2.2.6-cp313-cp313t-macosx_11_0_arm64.whl", hash = "sha256:fc0c5673685c508a142ca65209b4e79ed6740a4ed6b2267dbba90f34b0b3cfda", size = 14225144, upload-time = "2025-05-17T21:41:05.695Z" }, - { url = "https://files.pythonhosted.org/packages/e4/25/480387655407ead912e28ba3a820bc69af9adf13bcbe40b299d454ec011f/numpy-2.2.6-cp313-cp313t-macosx_14_0_arm64.whl", hash = "sha256:5bd4fc3ac8926b3819797a7c0e2631eb889b4118a9898c84f585a54d475b7e40", size = 5200217, upload-time = "2025-05-17T21:41:15.903Z" }, - { url = "https://files.pythonhosted.org/packages/aa/4a/6e313b5108f53dcbf3aca0c0f3e9c92f4c10ce57a0a721851f9785872895/numpy-2.2.6-cp313-cp313t-macosx_14_0_x86_64.whl", hash = "sha256:fee4236c876c4e8369388054d02d0e9bb84821feb1a64dd59e137e6511a551f8", size = 6712014, upload-time = "2025-05-17T21:41:27.321Z" }, - { url = "https://files.pythonhosted.org/packages/b7/30/172c2d5c4be71fdf476e9de553443cf8e25feddbe185e0bd88b096915bcc/numpy-2.2.6-cp313-cp313t-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:e1dda9c7e08dc141e0247a5b8f49cf05984955246a327d4c48bda16821947b2f", size = 14077935, upload-time = "2025-05-17T21:41:49.738Z" }, - { url = "https://files.pythonhosted.org/packages/12/fb/9e743f8d4e4d3c710902cf87af3512082ae3d43b945d5d16563f26ec251d/numpy-2.2.6-cp313-cp313t-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:f447e6acb680fd307f40d3da4852208af94afdfab89cf850986c3ca00562f4fa", size = 16600122, upload-time = "2025-05-17T21:42:14.046Z" }, - { url = "https://files.pythonhosted.org/packages/12/75/ee20da0e58d3a66f204f38916757e01e33a9737d0b22373b3eb5a27358f9/numpy-2.2.6-cp313-cp313t-musllinux_1_2_aarch64.whl", hash = "sha256:389d771b1623ec92636b0786bc4ae56abafad4a4c513d36a55dce14bd9ce8571", size = 15586143, upload-time = "2025-05-17T21:42:37.464Z" }, - { url = "https://files.pythonhosted.org/packages/76/95/bef5b37f29fc5e739947e9ce5179ad402875633308504a52d188302319c8/numpy-2.2.6-cp313-cp313t-musllinux_1_2_x86_64.whl", hash = "sha256:8e9ace4a37db23421249ed236fdcdd457d671e25146786dfc96835cd951aa7c1", size = 18385260, upload-time = "2025-05-17T21:43:05.189Z" }, - { url = "https://files.pythonhosted.org/packages/09/04/f2f83279d287407cf36a7a8053a5abe7be3622a4363337338f2585e4afda/numpy-2.2.6-cp313-cp313t-win32.whl", hash = "sha256:038613e9fb8c72b0a41f025a7e4c3f0b7a1b5d768ece4796b674c8f3fe13efff", size = 6377225, upload-time = "2025-05-17T21:43:16.254Z" }, - { url = "https://files.pythonhosted.org/packages/67/0e/35082d13c09c02c011cf21570543d202ad929d961c02a147493cb0c2bdf5/numpy-2.2.6-cp313-cp313t-win_amd64.whl", hash = "sha256:6031dd6dfecc0cf9f668681a37648373bddd6421fff6c66ec1624eed0180ee06", size = 12771374, upload-time = "2025-05-17T21:43:35.479Z" }, - { url = "https://files.pythonhosted.org/packages/9e/3b/d94a75f4dbf1ef5d321523ecac21ef23a3cd2ac8b78ae2aac40873590229/numpy-2.2.6-pp310-pypy310_pp73-macosx_10_15_x86_64.whl", hash = "sha256:0b605b275d7bd0c640cad4e5d30fa701a8d59302e127e5f79138ad62762c3e3d", size = 21040391, upload-time = "2025-05-17T21:44:35.948Z" }, - { url = "https://files.pythonhosted.org/packages/17/f4/09b2fa1b58f0fb4f7c7963a1649c64c4d315752240377ed74d9cd878f7b5/numpy-2.2.6-pp310-pypy310_pp73-macosx_14_0_x86_64.whl", hash = "sha256:7befc596a7dc9da8a337f79802ee8adb30a552a94f792b9c9d18c840055907db", size = 6786754, upload-time = "2025-05-17T21:44:47.446Z" }, - { url = "https://files.pythonhosted.org/packages/af/30/feba75f143bdc868a1cc3f44ccfa6c4b9ec522b36458e738cd00f67b573f/numpy-2.2.6-pp310-pypy310_pp73-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:ce47521a4754c8f4593837384bd3424880629f718d87c5d44f8ed763edd63543", size = 16643476, upload-time = "2025-05-17T21:45:11.871Z" }, - { url = "https://files.pythonhosted.org/packages/37/48/ac2a9584402fb6c0cd5b5d1a91dcf176b15760130dd386bbafdbfe3640bf/numpy-2.2.6-pp310-pypy310_pp73-win_amd64.whl", hash = "sha256:d042d24c90c41b54fd506da306759e06e568864df8ec17ccc17e9e884634fd00", size = 12812666, upload-time = "2025-05-17T21:45:31.426Z" }, -] - [[package]] name = "numpy" version = "2.3.3" source = { registry = "https://pypi.org/simple" } -resolution-markers = [ - "python_full_version >= '3.13'", - "python_full_version == '3.12.*'", - "python_full_version == '3.11.*'", -] sdist = { url = "https://files.pythonhosted.org/packages/d0/19/95b3d357407220ed24c139018d2518fab0a61a948e68286a25f1a4d049ff/numpy-2.3.3.tar.gz", hash = "sha256:ddc7c39727ba62b80dfdbedf400d1c10ddfa8eefbd7ec8dcb118be8b56d31029", size = 20576648, upload-time = "2025-09-09T16:54:12.543Z" } wheels = [ { url = "https://files.pythonhosted.org/packages/7a/45/e80d203ef6b267aa29b22714fb558930b27960a0c5ce3c19c999232bb3eb/numpy-2.3.3-cp311-cp311-macosx_10_9_x86_64.whl", hash = "sha256:0ffc4f5caba7dfcbe944ed674b7eef683c7e94874046454bb79ed7ee0236f59d", size = 21259253, upload-time = "2025-09-09T15:56:02.094Z" }, @@ -1242,14 +992,10 @@ version = "0.2.6" source = { registry = "https://pypi.org/simple" } dependencies = [ { name = "absl-py" }, - { name = "chex", version = "0.1.90", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version < '3.11'" }, - { name = "chex", version = "0.1.91", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version >= '3.11'" }, - { name = "jax", version = "0.6.2", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version < '3.11'" }, - { name = "jax", version = "0.7.2", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version >= '3.11'" }, - { name = "jaxlib", version = "0.6.2", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version < '3.11'" }, - { name = "jaxlib", version = "0.7.2", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version >= '3.11'" }, - { name = "numpy", version = "2.2.6", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version < '3.11'" }, - { name = "numpy", version = "2.3.3", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version >= '3.11'" }, + { name = "chex" }, + { name = "jax" }, + { name = "jaxlib" }, + { name = "numpy" }, ] sdist = { url = "https://files.pythonhosted.org/packages/6d/3b/90c11f740a3538200b61cd2b7d9346959cb9e31e0bdea3d2f886b7262203/optax-0.2.6.tar.gz", hash = "sha256:ba8d1e12678eba2657484d6feeca4fb281b8066bdfd5efbfc0f41b87663109c0", size = 269660, upload-time = "2025-09-15T22:41:24.76Z" } wheels = [ @@ -1265,12 +1011,10 @@ dependencies = [ { name = "aiofiles" }, { name = "etils", extra = ["epath", "epy"] }, { name = "humanize" }, - { name = "jax", version = "0.6.2", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version < '3.11'" }, - { name = "jax", version = "0.7.2", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version >= '3.11'" }, + { name = "jax" }, { name = "msgpack" }, { name = "nest-asyncio" }, - { name = "numpy", version = "2.2.6", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version < '3.11'" }, - { name = "numpy", version = "2.3.3", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version >= '3.11'" }, + { name = "numpy" }, { name = "protobuf" }, { name = "pyyaml" }, { name = "simplejson" }, @@ -1385,12 +1129,10 @@ version = "8.4.2" source = { registry = "https://pypi.org/simple" } dependencies = [ { name = "colorama", marker = "sys_platform == 'win32'" }, - { name = "exceptiongroup", marker = "python_full_version < '3.11'" }, { name = "iniconfig" }, { name = "packaging" }, { name = "pluggy" }, { name = "pygments" }, - { name = "tomli", marker = "python_full_version < '3.11'" }, ] sdist = { url = "https://files.pythonhosted.org/packages/a3/5c/00a0e072241553e1a7496d638deababa67c5058571567b92a7eaa258397c/pytest-8.4.2.tar.gz", hash = "sha256:86c0d0b93306b961d58d62a4db4879f27fe25513d4b969df351abdddb3c30e01", size = 1519618, upload-time = "2025-09-04T14:34:22.711Z" } wheels = [ @@ -1415,15 +1157,6 @@ version = "6.0.3" source = { registry = "https://pypi.org/simple" } sdist = { url = "https://files.pythonhosted.org/packages/05/8e/961c0007c59b8dd7729d542c61a4d537767a59645b82a0b521206e1e25c2/pyyaml-6.0.3.tar.gz", hash = "sha256:d76623373421df22fb4cf8817020cbb7ef15c725b9d5e45f17e189bfc384190f", size = 130960, upload-time = "2025-09-25T21:33:16.546Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/f4/a0/39350dd17dd6d6c6507025c0e53aef67a9293a6d37d3511f23ea510d5800/pyyaml-6.0.3-cp310-cp310-macosx_10_13_x86_64.whl", hash = "sha256:214ed4befebe12df36bcc8bc2b64b396ca31be9304b8f59e25c11cf94a4c033b", size = 184227, upload-time = "2025-09-25T21:31:46.04Z" }, - { url = "https://files.pythonhosted.org/packages/05/14/52d505b5c59ce73244f59c7a50ecf47093ce4765f116cdb98286a71eeca2/pyyaml-6.0.3-cp310-cp310-macosx_11_0_arm64.whl", hash = "sha256:02ea2dfa234451bbb8772601d7b8e426c2bfa197136796224e50e35a78777956", size = 174019, upload-time = "2025-09-25T21:31:47.706Z" }, - { url = "https://files.pythonhosted.org/packages/43/f7/0e6a5ae5599c838c696adb4e6330a59f463265bfa1e116cfd1fbb0abaaae/pyyaml-6.0.3-cp310-cp310-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:b30236e45cf30d2b8e7b3e85881719e98507abed1011bf463a8fa23e9c3e98a8", size = 740646, upload-time = "2025-09-25T21:31:49.21Z" }, - { url = "https://files.pythonhosted.org/packages/2f/3a/61b9db1d28f00f8fd0ae760459a5c4bf1b941baf714e207b6eb0657d2578/pyyaml-6.0.3-cp310-cp310-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:66291b10affd76d76f54fad28e22e51719ef9ba22b29e1d7d03d6777a9174198", size = 840793, upload-time = "2025-09-25T21:31:50.735Z" }, - { url = "https://files.pythonhosted.org/packages/7a/1e/7acc4f0e74c4b3d9531e24739e0ab832a5edf40e64fbae1a9c01941cabd7/pyyaml-6.0.3-cp310-cp310-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:9c7708761fccb9397fe64bbc0395abcae8c4bf7b0eac081e12b809bf47700d0b", size = 770293, upload-time = "2025-09-25T21:31:51.828Z" }, - { url = "https://files.pythonhosted.org/packages/8b/ef/abd085f06853af0cd59fa5f913d61a8eab65d7639ff2a658d18a25d6a89d/pyyaml-6.0.3-cp310-cp310-musllinux_1_2_aarch64.whl", hash = "sha256:418cf3f2111bc80e0933b2cd8cd04f286338bb88bdc7bc8e6dd775ebde60b5e0", size = 732872, upload-time = "2025-09-25T21:31:53.282Z" }, - { url = "https://files.pythonhosted.org/packages/1f/15/2bc9c8faf6450a8b3c9fc5448ed869c599c0a74ba2669772b1f3a0040180/pyyaml-6.0.3-cp310-cp310-musllinux_1_2_x86_64.whl", hash = "sha256:5e0b74767e5f8c593e8c9b5912019159ed0533c70051e9cce3e8b6aa699fcd69", size = 758828, upload-time = "2025-09-25T21:31:54.807Z" }, - { url = "https://files.pythonhosted.org/packages/a3/00/531e92e88c00f4333ce359e50c19b8d1de9fe8d581b1534e35ccfbc5f393/pyyaml-6.0.3-cp310-cp310-win32.whl", hash = "sha256:28c8d926f98f432f88adc23edf2e6d4921ac26fb084b028c733d01868d19007e", size = 142415, upload-time = "2025-09-25T21:31:55.885Z" }, - { url = "https://files.pythonhosted.org/packages/2a/fa/926c003379b19fca39dd4634818b00dec6c62d87faf628d1394e137354d4/pyyaml-6.0.3-cp310-cp310-win_amd64.whl", hash = "sha256:bdb2c67c6c1390b63c6ff89f210c8fd09d9a1217a465701eac7316313c915e4c", size = 158561, upload-time = "2025-09-25T21:31:57.406Z" }, { url = "https://files.pythonhosted.org/packages/6d/16/a95b6757765b7b031c9374925bb718d55e0a9ba8a1b6a12d25962ea44347/pyyaml-6.0.3-cp311-cp311-macosx_10_13_x86_64.whl", hash = "sha256:44edc647873928551a01e7a563d7452ccdebee747728c1080d881d68af7b997e", size = 185826, upload-time = "2025-09-25T21:31:58.655Z" }, { url = "https://files.pythonhosted.org/packages/16/19/13de8e4377ed53079ee996e1ab0a9c33ec2faf808a4647b7b4c0d46dd239/pyyaml-6.0.3-cp311-cp311-macosx_11_0_arm64.whl", hash = "sha256:652cb6edd41e718550aad172851962662ff2681490a8a711af6a4d288dd96824", size = 175577, upload-time = "2025-09-25T21:32:00.088Z" }, { url = "https://files.pythonhosted.org/packages/0c/62/d2eb46264d4b157dae1275b573017abec435397aa59cbcdab6fc978a8af4/pyyaml-6.0.3-cp311-cp311-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:10892704fc220243f5305762e276552a0395f7beb4dbf9b14ec8fd43b57f126c", size = 775556, upload-time = "2025-09-25T21:32:01.31Z" }, @@ -1535,76 +1268,12 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/2c/c3/c0be1135726618dc1e28d181b8c442403d8dbb9e273fd791de2d4384bcdd/safetensors-0.6.2-cp38-abi3-win_amd64.whl", hash = "sha256:c7b214870df923cbc1593c3faee16bec59ea462758699bd3fee399d00aac072c", size = 320192, upload-time = "2025-08-08T13:13:59.467Z" }, ] -[[package]] -name = "scipy" -version = "1.15.3" -source = { registry = "https://pypi.org/simple" } -resolution-markers = [ - "python_full_version < '3.11'", -] -dependencies = [ - { name = "numpy", version = "2.2.6", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version < '3.11'" }, -] -sdist = { url = "https://files.pythonhosted.org/packages/0f/37/6964b830433e654ec7485e45a00fc9a27cf868d622838f6b6d9c5ec0d532/scipy-1.15.3.tar.gz", hash = "sha256:eae3cf522bc7df64b42cad3925c876e1b0b6c35c1337c93e12c0f366f55b0eaf", size = 59419214, upload-time = "2025-05-08T16:13:05.955Z" } -wheels = [ - { url = "https://files.pythonhosted.org/packages/78/2f/4966032c5f8cc7e6a60f1b2e0ad686293b9474b65246b0c642e3ef3badd0/scipy-1.15.3-cp310-cp310-macosx_10_13_x86_64.whl", hash = "sha256:a345928c86d535060c9c2b25e71e87c39ab2f22fc96e9636bd74d1dbf9de448c", size = 38702770, upload-time = "2025-05-08T16:04:20.849Z" }, - { url = "https://files.pythonhosted.org/packages/a0/6e/0c3bf90fae0e910c274db43304ebe25a6b391327f3f10b5dcc638c090795/scipy-1.15.3-cp310-cp310-macosx_12_0_arm64.whl", hash = "sha256:ad3432cb0f9ed87477a8d97f03b763fd1d57709f1bbde3c9369b1dff5503b253", size = 30094511, upload-time = "2025-05-08T16:04:27.103Z" }, - { url = "https://files.pythonhosted.org/packages/ea/b1/4deb37252311c1acff7f101f6453f0440794f51b6eacb1aad4459a134081/scipy-1.15.3-cp310-cp310-macosx_14_0_arm64.whl", hash = "sha256:aef683a9ae6eb00728a542b796f52a5477b78252edede72b8327a886ab63293f", size = 22368151, upload-time = "2025-05-08T16:04:31.731Z" }, - { url = "https://files.pythonhosted.org/packages/38/7d/f457626e3cd3c29b3a49ca115a304cebb8cc6f31b04678f03b216899d3c6/scipy-1.15.3-cp310-cp310-macosx_14_0_x86_64.whl", hash = "sha256:1c832e1bd78dea67d5c16f786681b28dd695a8cb1fb90af2e27580d3d0967e92", size = 25121732, upload-time = "2025-05-08T16:04:36.596Z" }, - { url = "https://files.pythonhosted.org/packages/db/0a/92b1de4a7adc7a15dcf5bddc6e191f6f29ee663b30511ce20467ef9b82e4/scipy-1.15.3-cp310-cp310-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:263961f658ce2165bbd7b99fa5135195c3a12d9bef045345016b8b50c315cb82", size = 35547617, upload-time = "2025-05-08T16:04:43.546Z" }, - { url = "https://files.pythonhosted.org/packages/8e/6d/41991e503e51fc1134502694c5fa7a1671501a17ffa12716a4a9151af3df/scipy-1.15.3-cp310-cp310-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:9e2abc762b0811e09a0d3258abee2d98e0c703eee49464ce0069590846f31d40", size = 37662964, upload-time = "2025-05-08T16:04:49.431Z" }, - { url = "https://files.pythonhosted.org/packages/25/e1/3df8f83cb15f3500478c889be8fb18700813b95e9e087328230b98d547ff/scipy-1.15.3-cp310-cp310-musllinux_1_2_aarch64.whl", hash = "sha256:ed7284b21a7a0c8f1b6e5977ac05396c0d008b89e05498c8b7e8f4a1423bba0e", size = 37238749, upload-time = "2025-05-08T16:04:55.215Z" }, - { url = "https://files.pythonhosted.org/packages/93/3e/b3257cf446f2a3533ed7809757039016b74cd6f38271de91682aa844cfc5/scipy-1.15.3-cp310-cp310-musllinux_1_2_x86_64.whl", hash = "sha256:5380741e53df2c566f4d234b100a484b420af85deb39ea35a1cc1be84ff53a5c", size = 40022383, upload-time = "2025-05-08T16:05:01.914Z" }, - { url = "https://files.pythonhosted.org/packages/d1/84/55bc4881973d3f79b479a5a2e2df61c8c9a04fcb986a213ac9c02cfb659b/scipy-1.15.3-cp310-cp310-win_amd64.whl", hash = "sha256:9d61e97b186a57350f6d6fd72640f9e99d5a4a2b8fbf4b9ee9a841eab327dc13", size = 41259201, upload-time = "2025-05-08T16:05:08.166Z" }, - { url = "https://files.pythonhosted.org/packages/96/ab/5cc9f80f28f6a7dff646c5756e559823614a42b1939d86dd0ed550470210/scipy-1.15.3-cp311-cp311-macosx_10_13_x86_64.whl", hash = "sha256:993439ce220d25e3696d1b23b233dd010169b62f6456488567e830654ee37a6b", size = 38714255, upload-time = "2025-05-08T16:05:14.596Z" }, - { url = "https://files.pythonhosted.org/packages/4a/4a/66ba30abe5ad1a3ad15bfb0b59d22174012e8056ff448cb1644deccbfed2/scipy-1.15.3-cp311-cp311-macosx_12_0_arm64.whl", hash = "sha256:34716e281f181a02341ddeaad584205bd2fd3c242063bd3423d61ac259ca7eba", size = 30111035, upload-time = "2025-05-08T16:05:20.152Z" }, - { url = "https://files.pythonhosted.org/packages/4b/fa/a7e5b95afd80d24313307f03624acc65801846fa75599034f8ceb9e2cbf6/scipy-1.15.3-cp311-cp311-macosx_14_0_arm64.whl", hash = "sha256:3b0334816afb8b91dab859281b1b9786934392aa3d527cd847e41bb6f45bee65", size = 22384499, upload-time = "2025-05-08T16:05:24.494Z" }, - { url = "https://files.pythonhosted.org/packages/17/99/f3aaddccf3588bb4aea70ba35328c204cadd89517a1612ecfda5b2dd9d7a/scipy-1.15.3-cp311-cp311-macosx_14_0_x86_64.whl", hash = "sha256:6db907c7368e3092e24919b5e31c76998b0ce1684d51a90943cb0ed1b4ffd6c1", size = 25152602, upload-time = "2025-05-08T16:05:29.313Z" }, - { url = "https://files.pythonhosted.org/packages/56/c5/1032cdb565f146109212153339f9cb8b993701e9fe56b1c97699eee12586/scipy-1.15.3-cp311-cp311-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:721d6b4ef5dc82ca8968c25b111e307083d7ca9091bc38163fb89243e85e3889", size = 35503415, upload-time = "2025-05-08T16:05:34.699Z" }, - { url = "https://files.pythonhosted.org/packages/bd/37/89f19c8c05505d0601ed5650156e50eb881ae3918786c8fd7262b4ee66d3/scipy-1.15.3-cp311-cp311-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:39cb9c62e471b1bb3750066ecc3a3f3052b37751c7c3dfd0fd7e48900ed52982", size = 37652622, upload-time = "2025-05-08T16:05:40.762Z" }, - { url = "https://files.pythonhosted.org/packages/7e/31/be59513aa9695519b18e1851bb9e487de66f2d31f835201f1b42f5d4d475/scipy-1.15.3-cp311-cp311-musllinux_1_2_aarch64.whl", hash = "sha256:795c46999bae845966368a3c013e0e00947932d68e235702b5c3f6ea799aa8c9", size = 37244796, upload-time = "2025-05-08T16:05:48.119Z" }, - { url = "https://files.pythonhosted.org/packages/10/c0/4f5f3eeccc235632aab79b27a74a9130c6c35df358129f7ac8b29f562ac7/scipy-1.15.3-cp311-cp311-musllinux_1_2_x86_64.whl", hash = "sha256:18aaacb735ab38b38db42cb01f6b92a2d0d4b6aabefeb07f02849e47f8fb3594", size = 40047684, upload-time = "2025-05-08T16:05:54.22Z" }, - { url = "https://files.pythonhosted.org/packages/ab/a7/0ddaf514ce8a8714f6ed243a2b391b41dbb65251affe21ee3077ec45ea9a/scipy-1.15.3-cp311-cp311-win_amd64.whl", hash = "sha256:ae48a786a28412d744c62fd7816a4118ef97e5be0bee968ce8f0a2fba7acf3bb", size = 41246504, upload-time = "2025-05-08T16:06:00.437Z" }, - { url = "https://files.pythonhosted.org/packages/37/4b/683aa044c4162e10ed7a7ea30527f2cbd92e6999c10a8ed8edb253836e9c/scipy-1.15.3-cp312-cp312-macosx_10_13_x86_64.whl", hash = "sha256:6ac6310fdbfb7aa6612408bd2f07295bcbd3fda00d2d702178434751fe48e019", size = 38766735, upload-time = "2025-05-08T16:06:06.471Z" }, - { url = "https://files.pythonhosted.org/packages/7b/7e/f30be3d03de07f25dc0ec926d1681fed5c732d759ac8f51079708c79e680/scipy-1.15.3-cp312-cp312-macosx_12_0_arm64.whl", hash = "sha256:185cd3d6d05ca4b44a8f1595af87f9c372bb6acf9c808e99aa3e9aa03bd98cf6", size = 30173284, upload-time = "2025-05-08T16:06:11.686Z" }, - { url = "https://files.pythonhosted.org/packages/07/9c/0ddb0d0abdabe0d181c1793db51f02cd59e4901da6f9f7848e1f96759f0d/scipy-1.15.3-cp312-cp312-macosx_14_0_arm64.whl", hash = "sha256:05dc6abcd105e1a29f95eada46d4a3f251743cfd7d3ae8ddb4088047f24ea477", size = 22446958, upload-time = "2025-05-08T16:06:15.97Z" }, - { url = "https://files.pythonhosted.org/packages/af/43/0bce905a965f36c58ff80d8bea33f1f9351b05fad4beaad4eae34699b7a1/scipy-1.15.3-cp312-cp312-macosx_14_0_x86_64.whl", hash = "sha256:06efcba926324df1696931a57a176c80848ccd67ce6ad020c810736bfd58eb1c", size = 25242454, upload-time = "2025-05-08T16:06:20.394Z" }, - { url = "https://files.pythonhosted.org/packages/56/30/a6f08f84ee5b7b28b4c597aca4cbe545535c39fe911845a96414700b64ba/scipy-1.15.3-cp312-cp312-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:c05045d8b9bfd807ee1b9f38761993297b10b245f012b11b13b91ba8945f7e45", size = 35210199, upload-time = "2025-05-08T16:06:26.159Z" }, - { url = "https://files.pythonhosted.org/packages/0b/1f/03f52c282437a168ee2c7c14a1a0d0781a9a4a8962d84ac05c06b4c5b555/scipy-1.15.3-cp312-cp312-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:271e3713e645149ea5ea3e97b57fdab61ce61333f97cfae392c28ba786f9bb49", size = 37309455, upload-time = "2025-05-08T16:06:32.778Z" }, - { url = "https://files.pythonhosted.org/packages/89/b1/fbb53137f42c4bf630b1ffdfc2151a62d1d1b903b249f030d2b1c0280af8/scipy-1.15.3-cp312-cp312-musllinux_1_2_aarch64.whl", hash = "sha256:6cfd56fc1a8e53f6e89ba3a7a7251f7396412d655bca2aa5611c8ec9a6784a1e", size = 36885140, upload-time = "2025-05-08T16:06:39.249Z" }, - { url = "https://files.pythonhosted.org/packages/2e/2e/025e39e339f5090df1ff266d021892694dbb7e63568edcfe43f892fa381d/scipy-1.15.3-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:0ff17c0bb1cb32952c09217d8d1eed9b53d1463e5f1dd6052c7857f83127d539", size = 39710549, upload-time = "2025-05-08T16:06:45.729Z" }, - { url = "https://files.pythonhosted.org/packages/e6/eb/3bf6ea8ab7f1503dca3a10df2e4b9c3f6b3316df07f6c0ded94b281c7101/scipy-1.15.3-cp312-cp312-win_amd64.whl", hash = "sha256:52092bc0472cfd17df49ff17e70624345efece4e1a12b23783a1ac59a1b728ed", size = 40966184, upload-time = "2025-05-08T16:06:52.623Z" }, - { url = "https://files.pythonhosted.org/packages/73/18/ec27848c9baae6e0d6573eda6e01a602e5649ee72c27c3a8aad673ebecfd/scipy-1.15.3-cp313-cp313-macosx_10_13_x86_64.whl", hash = "sha256:2c620736bcc334782e24d173c0fdbb7590a0a436d2fdf39310a8902505008759", size = 38728256, upload-time = "2025-05-08T16:06:58.696Z" }, - { url = "https://files.pythonhosted.org/packages/74/cd/1aef2184948728b4b6e21267d53b3339762c285a46a274ebb7863c9e4742/scipy-1.15.3-cp313-cp313-macosx_12_0_arm64.whl", hash = "sha256:7e11270a000969409d37ed399585ee530b9ef6aa99d50c019de4cb01e8e54e62", size = 30109540, upload-time = "2025-05-08T16:07:04.209Z" }, - { url = "https://files.pythonhosted.org/packages/5b/d8/59e452c0a255ec352bd0a833537a3bc1bfb679944c4938ab375b0a6b3a3e/scipy-1.15.3-cp313-cp313-macosx_14_0_arm64.whl", hash = "sha256:8c9ed3ba2c8a2ce098163a9bdb26f891746d02136995df25227a20e71c396ebb", size = 22383115, upload-time = "2025-05-08T16:07:08.998Z" }, - { url = "https://files.pythonhosted.org/packages/08/f5/456f56bbbfccf696263b47095291040655e3cbaf05d063bdc7c7517f32ac/scipy-1.15.3-cp313-cp313-macosx_14_0_x86_64.whl", hash = "sha256:0bdd905264c0c9cfa74a4772cdb2070171790381a5c4d312c973382fc6eaf730", size = 25163884, upload-time = "2025-05-08T16:07:14.091Z" }, - { url = "https://files.pythonhosted.org/packages/a2/66/a9618b6a435a0f0c0b8a6d0a2efb32d4ec5a85f023c2b79d39512040355b/scipy-1.15.3-cp313-cp313-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:79167bba085c31f38603e11a267d862957cbb3ce018d8b38f79ac043bc92d825", size = 35174018, upload-time = "2025-05-08T16:07:19.427Z" }, - { url = "https://files.pythonhosted.org/packages/b5/09/c5b6734a50ad4882432b6bb7c02baf757f5b2f256041da5df242e2d7e6b6/scipy-1.15.3-cp313-cp313-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:c9deabd6d547aee2c9a81dee6cc96c6d7e9a9b1953f74850c179f91fdc729cb7", size = 37269716, upload-time = "2025-05-08T16:07:25.712Z" }, - { url = "https://files.pythonhosted.org/packages/77/0a/eac00ff741f23bcabd352731ed9b8995a0a60ef57f5fd788d611d43d69a1/scipy-1.15.3-cp313-cp313-musllinux_1_2_aarch64.whl", hash = "sha256:dde4fc32993071ac0c7dd2d82569e544f0bdaff66269cb475e0f369adad13f11", size = 36872342, upload-time = "2025-05-08T16:07:31.468Z" }, - { url = "https://files.pythonhosted.org/packages/fe/54/4379be86dd74b6ad81551689107360d9a3e18f24d20767a2d5b9253a3f0a/scipy-1.15.3-cp313-cp313-musllinux_1_2_x86_64.whl", hash = "sha256:f77f853d584e72e874d87357ad70f44b437331507d1c311457bed8ed2b956126", size = 39670869, upload-time = "2025-05-08T16:07:38.002Z" }, - { url = "https://files.pythonhosted.org/packages/87/2e/892ad2862ba54f084ffe8cc4a22667eaf9c2bcec6d2bff1d15713c6c0703/scipy-1.15.3-cp313-cp313-win_amd64.whl", hash = "sha256:b90ab29d0c37ec9bf55424c064312930ca5f4bde15ee8619ee44e69319aab163", size = 40988851, upload-time = "2025-05-08T16:08:33.671Z" }, - { url = "https://files.pythonhosted.org/packages/1b/e9/7a879c137f7e55b30d75d90ce3eb468197646bc7b443ac036ae3fe109055/scipy-1.15.3-cp313-cp313t-macosx_10_13_x86_64.whl", hash = "sha256:3ac07623267feb3ae308487c260ac684b32ea35fd81e12845039952f558047b8", size = 38863011, upload-time = "2025-05-08T16:07:44.039Z" }, - { url = "https://files.pythonhosted.org/packages/51/d1/226a806bbd69f62ce5ef5f3ffadc35286e9fbc802f606a07eb83bf2359de/scipy-1.15.3-cp313-cp313t-macosx_12_0_arm64.whl", hash = "sha256:6487aa99c2a3d509a5227d9a5e889ff05830a06b2ce08ec30df6d79db5fcd5c5", size = 30266407, upload-time = "2025-05-08T16:07:49.891Z" }, - { url = "https://files.pythonhosted.org/packages/e5/9b/f32d1d6093ab9eeabbd839b0f7619c62e46cc4b7b6dbf05b6e615bbd4400/scipy-1.15.3-cp313-cp313t-macosx_14_0_arm64.whl", hash = "sha256:50f9e62461c95d933d5c5ef4a1f2ebf9a2b4e83b0db374cb3f1de104d935922e", size = 22540030, upload-time = "2025-05-08T16:07:54.121Z" }, - { url = "https://files.pythonhosted.org/packages/e7/29/c278f699b095c1a884f29fda126340fcc201461ee8bfea5c8bdb1c7c958b/scipy-1.15.3-cp313-cp313t-macosx_14_0_x86_64.whl", hash = "sha256:14ed70039d182f411ffc74789a16df3835e05dc469b898233a245cdfd7f162cb", size = 25218709, upload-time = "2025-05-08T16:07:58.506Z" }, - { url = "https://files.pythonhosted.org/packages/24/18/9e5374b617aba742a990581373cd6b68a2945d65cc588482749ef2e64467/scipy-1.15.3-cp313-cp313t-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:0a769105537aa07a69468a0eefcd121be52006db61cdd8cac8a0e68980bbb723", size = 34809045, upload-time = "2025-05-08T16:08:03.929Z" }, - { url = "https://files.pythonhosted.org/packages/e1/fe/9c4361e7ba2927074360856db6135ef4904d505e9b3afbbcb073c4008328/scipy-1.15.3-cp313-cp313t-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:9db984639887e3dffb3928d118145ffe40eff2fa40cb241a306ec57c219ebbbb", size = 36703062, upload-time = "2025-05-08T16:08:09.558Z" }, - { url = "https://files.pythonhosted.org/packages/b7/8e/038ccfe29d272b30086b25a4960f757f97122cb2ec42e62b460d02fe98e9/scipy-1.15.3-cp313-cp313t-musllinux_1_2_aarch64.whl", hash = "sha256:40e54d5c7e7ebf1aa596c374c49fa3135f04648a0caabcb66c52884b943f02b4", size = 36393132, upload-time = "2025-05-08T16:08:15.34Z" }, - { url = "https://files.pythonhosted.org/packages/10/7e/5c12285452970be5bdbe8352c619250b97ebf7917d7a9a9e96b8a8140f17/scipy-1.15.3-cp313-cp313t-musllinux_1_2_x86_64.whl", hash = "sha256:5e721fed53187e71d0ccf382b6bf977644c533e506c4d33c3fb24de89f5c3ed5", size = 38979503, upload-time = "2025-05-08T16:08:21.513Z" }, - { url = "https://files.pythonhosted.org/packages/81/06/0a5e5349474e1cbc5757975b21bd4fad0e72ebf138c5592f191646154e06/scipy-1.15.3-cp313-cp313t-win_amd64.whl", hash = "sha256:76ad1fb5f8752eabf0fa02e4cc0336b4e8f021e2d5f061ed37d6d264db35e3ca", size = 40308097, upload-time = "2025-05-08T16:08:27.627Z" }, -] - [[package]] name = "scipy" version = "1.16.2" source = { registry = "https://pypi.org/simple" } -resolution-markers = [ - "python_full_version >= '3.13'", - "python_full_version == '3.12.*'", - "python_full_version == '3.11.*'", -] dependencies = [ - { name = "numpy", version = "2.3.3", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version >= '3.11'" }, + { name = "numpy" }, ] sdist = { url = "https://files.pythonhosted.org/packages/4c/3b/546a6f0bfe791bbb7f8d591613454d15097e53f906308ec6f7c1ce588e8e/scipy-1.16.2.tar.gz", hash = "sha256:af029b153d243a80afb6eabe40b0a07f8e35c9adc269c019f364ad747f826a6b", size = 30580599, upload-time = "2025-09-11T17:48:08.271Z" } wheels = [ @@ -1676,19 +1345,6 @@ version = "3.20.2" source = { registry = "https://pypi.org/simple" } sdist = { url = "https://files.pythonhosted.org/packages/41/f4/a1ac5ed32f7ed9a088d62a59d410d4c204b3b3815722e2ccfb491fa8251b/simplejson-3.20.2.tar.gz", hash = "sha256:5fe7a6ce14d1c300d80d08695b7f7e633de6cd72c80644021874d985b3393649", size = 85784, upload-time = "2025-09-26T16:29:36.64Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/78/09/2bf3761de89ea2d91bdce6cf107dcd858892d0adc22c995684878826cc6b/simplejson-3.20.2-cp310-cp310-macosx_10_9_universal2.whl", hash = "sha256:6d7286dc11af60a2f76eafb0c2acde2d997e87890e37e24590bb513bec9f1bc5", size = 94039, upload-time = "2025-09-26T16:27:29.283Z" }, - { url = "https://files.pythonhosted.org/packages/0f/33/c3277db8931f0ae9e54b9292668863365672d90fb0f632f4cf9829cb7d68/simplejson-3.20.2-cp310-cp310-macosx_10_9_x86_64.whl", hash = "sha256:c01379b4861c3b0aa40cba8d44f2b448f5743999aa68aaa5d3ef7049d4a28a2d", size = 75894, upload-time = "2025-09-26T16:27:30.378Z" }, - { url = "https://files.pythonhosted.org/packages/fa/ea/ae47b04d03c7c8a7b7b1a8b39a6e27c3bd424e52f4988d70aca6293ff5e5/simplejson-3.20.2-cp310-cp310-macosx_11_0_arm64.whl", hash = "sha256:a16b029ca25645b3bc44e84a4f941efa51bf93c180b31bd704ce6349d1fc77c1", size = 76116, upload-time = "2025-09-26T16:27:31.42Z" }, - { url = "https://files.pythonhosted.org/packages/4b/42/6c9af551e5a8d0f171d6dce3d9d1260068927f7b80f1f09834e07887c8c4/simplejson-3.20.2-cp310-cp310-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:3e22a5fb7b1437ffb057e02e1936a3bfb19084ae9d221ec5e9f4cf85f69946b6", size = 138827, upload-time = "2025-09-26T16:27:32.486Z" }, - { url = "https://files.pythonhosted.org/packages/2b/22/5e268bbcbe9f75577491e406ec0a5536f5b2fa91a3b52031fea51cd83e1d/simplejson-3.20.2-cp310-cp310-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:d8b6ff02fc7b8555c906c24735908854819b0d0dc85883d453e23ca4c0445d01", size = 146772, upload-time = "2025-09-26T16:27:34.036Z" }, - { url = "https://files.pythonhosted.org/packages/71/b4/800f14728e2ad666f420dfdb57697ca128aeae7f991b35759c09356b829a/simplejson-3.20.2-cp310-cp310-manylinux_2_5_i686.manylinux1_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:2bfc1c396ad972ba4431130b42307b2321dba14d988580c1ac421ec6a6b7cee3", size = 134497, upload-time = "2025-09-26T16:27:35.211Z" }, - { url = "https://files.pythonhosted.org/packages/c1/b9/c54eef4226c6ac8e9a389bbe5b21fef116768f97a2dc1a683c716ffe66ef/simplejson-3.20.2-cp310-cp310-manylinux_2_5_x86_64.manylinux1_x86_64.manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:3a97249ee1aee005d891b5a211faf58092a309f3d9d440bc269043b08f662eda", size = 138172, upload-time = "2025-09-26T16:27:36.44Z" }, - { url = "https://files.pythonhosted.org/packages/09/36/4e282f5211b34620f1b2e4b51d9ddaab5af82219b9b7b78360a33f7e5387/simplejson-3.20.2-cp310-cp310-musllinux_1_2_aarch64.whl", hash = "sha256:f1036be00b5edaddbddbb89c0f80ed229714a941cfd21e51386dc69c237201c2", size = 140272, upload-time = "2025-09-26T16:27:37.605Z" }, - { url = "https://files.pythonhosted.org/packages/aa/b0/94ad2cf32f477c449e1f63c863d8a513e2408d651c4e58fe4b6a7434e168/simplejson-3.20.2-cp310-cp310-musllinux_1_2_i686.whl", hash = "sha256:5d6f5bacb8cdee64946b45f2680afa3f54cd38e62471ceda89f777693aeca4e4", size = 140468, upload-time = "2025-09-26T16:27:39.015Z" }, - { url = "https://files.pythonhosted.org/packages/e5/46/827731e4163be3f987cb8ee90f5d444161db8f540b5e735355faa098d9bc/simplejson-3.20.2-cp310-cp310-musllinux_1_2_ppc64le.whl", hash = "sha256:8db6841fb796ec5af632f677abf21c6425a1ebea0d9ac3ef1a340b8dc69f52b8", size = 148700, upload-time = "2025-09-26T16:27:40.171Z" }, - { url = "https://files.pythonhosted.org/packages/c7/28/c32121064b1ec2fb7b5d872d9a1abda62df064d35e0160eddfa907118343/simplejson-3.20.2-cp310-cp310-musllinux_1_2_x86_64.whl", hash = "sha256:c0a341f7cc2aae82ee2b31f8a827fd2e51d09626f8b3accc441a6907c88aedb7", size = 141323, upload-time = "2025-09-26T16:27:41.324Z" }, - { url = "https://files.pythonhosted.org/packages/46/b6/c897c54326fe86dd12d101981171a49361949f4728294f418c3b86a1af77/simplejson-3.20.2-cp310-cp310-win32.whl", hash = "sha256:27f9c01a6bc581d32ab026f515226864576da05ef322d7fc141cd8a15a95ce53", size = 74377, upload-time = "2025-09-26T16:27:42.533Z" }, - { url = "https://files.pythonhosted.org/packages/ad/87/a6e03d4d80cca99c1fee4e960f3440e2f21be9470e537970f960ca5547f1/simplejson-3.20.2-cp310-cp310-win_amd64.whl", hash = "sha256:c0a63ec98a4547ff366871bf832a7367ee43d047bcec0b07b66c794e2137b476", size = 76081, upload-time = "2025-09-26T16:27:43.945Z" }, { url = "https://files.pythonhosted.org/packages/b9/3e/96898c6c66d9dca3f9bd14d7487bf783b4acc77471b42f979babbb68d4ca/simplejson-3.20.2-cp311-cp311-macosx_10_9_universal2.whl", hash = "sha256:06190b33cd7849efc413a5738d3da00b90e4a5382fd3d584c841ac20fb828c6f", size = 92633, upload-time = "2025-09-26T16:27:45.028Z" }, { url = "https://files.pythonhosted.org/packages/6b/a2/cd2e10b880368305d89dd540685b8bdcc136df2b3c76b5ddd72596254539/simplejson-3.20.2-cp311-cp311-macosx_10_9_x86_64.whl", hash = "sha256:4ad4eac7d858947a30d2c404e61f16b84d16be79eb6fb316341885bdde864fa8", size = 75309, upload-time = "2025-09-26T16:27:46.142Z" }, { url = "https://files.pythonhosted.org/packages/5d/02/290f7282eaa6ebe945d35c47e6534348af97472446951dce0d144e013f4c/simplejson-3.20.2-cp311-cp311-macosx_11_0_arm64.whl", hash = "sha256:b392e11c6165d4a0fde41754a0e13e1d88a5ad782b245a973dd4b2bdb4e5076a", size = 75308, upload-time = "2025-09-26T16:27:47.542Z" }, @@ -1758,16 +1414,10 @@ version = "0.1.77" source = { registry = "https://pypi.org/simple" } dependencies = [ { name = "ml-dtypes" }, - { name = "numpy", version = "2.2.6", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version < '3.11'" }, - { name = "numpy", version = "2.3.3", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version >= '3.11'" }, + { name = "numpy" }, ] sdist = { url = "https://files.pythonhosted.org/packages/48/4c/7db3b759e38e14c5eafeada78705f347f42a9ba132914a2ccad60bce5605/tensorstore-0.1.77.tar.gz", hash = "sha256:5ae62828503cea71e64d808bda959877ed75ea23f1adffca903635b842acc1e8", size = 6880812, upload-time = "2025-09-20T00:19:02.497Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/65/fd/46b2a2d0b9c428eaebaed179f8cf68a9bcffb96e78a9987c9d4a73a5d834/tensorstore-0.1.77-cp310-cp310-macosx_10_14_x86_64.whl", hash = "sha256:985655addf29ee6543fd84cb7c521967c2ed531fd7dbbeb69bd885abacee77f6", size = 15710763, upload-time = "2025-09-20T00:18:09.964Z" }, - { url = "https://files.pythonhosted.org/packages/0d/eb/06d2f59f58d40dd69c100baad15a9f28e884e3515afb68fdc2893a779fb9/tensorstore-0.1.77-cp310-cp310-macosx_11_0_arm64.whl", hash = "sha256:a936b74887be52de98e3bb8d18d46e8768208155e616d615f1237880224c4fd7", size = 13771531, upload-time = "2025-09-20T00:18:12.811Z" }, - { url = "https://files.pythonhosted.org/packages/f5/1a/5fca4445ac760b1341f7ebb6f68d863263ce48e068b63e74d6a05dea9ef2/tensorstore-0.1.77-cp310-cp310-manylinux_2_27_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:8d41a022e7531325ee0d173ce26da17df7dbea5954bd868bb1164712434f057b", size = 17710228, upload-time = "2025-09-20T00:18:15.49Z" }, - { url = "https://files.pythonhosted.org/packages/4f/a0/1ad099b963119c40598b6c8578f331f9c7b70aa7b64331aaf9dd2d9e87a5/tensorstore-0.1.77-cp310-cp310-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:82e11e3981b1946da5bedda2b58d6f45bec2f7265bf64bc4c58d26fd5ee5325a", size = 19548584, upload-time = "2025-09-20T00:18:18.025Z" }, - { url = "https://files.pythonhosted.org/packages/13/72/5784c3346b87422c4c6f3c182ce74ab8735e8a72af11b3510c9fdd825455/tensorstore-0.1.77-cp310-cp310-win_amd64.whl", hash = "sha256:88213e3ab2f0a4a3a5a46edfca6e74dc0162b7e5e76d517a0a5554fe2f6951d7", size = 12705119, upload-time = "2025-09-20T00:18:20.313Z" }, { url = "https://files.pythonhosted.org/packages/bd/0e/5104cec25693d345e769e14426daff368409b814f7a9a49ceda4edf0976b/tensorstore-0.1.77-cp311-cp311-macosx_10_14_x86_64.whl", hash = "sha256:5c543184acb1282fa905513284d836c62faaaf4919ef6245ddc5f0a4800866f9", size = 15712049, upload-time = "2025-09-20T00:18:22.908Z" }, { url = "https://files.pythonhosted.org/packages/df/d6/d5342046640ad4ab2e9c4f34654d8fab0f5600cf77c7dca3b1aee2cbd70e/tensorstore-0.1.77-cp311-cp311-macosx_11_0_arm64.whl", hash = "sha256:8c08c03f261bb6fe34e41fedc483f7f8c6935ba02c36ae345d7b45572fbda21e", size = 13773861, upload-time = "2025-09-20T00:18:25.51Z" }, { url = "https://files.pythonhosted.org/packages/97/85/e33575dca0cb2812aa19ae0e1b564b213ca21356b6c489ab30e71c69b83f/tensorstore-0.1.77-cp311-cp311-manylinux_2_27_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:0848c0a004cb4e8443b3bee4238d51dfadbac55b834e939336bf9b86923d73f5", size = 17709679, upload-time = "2025-09-20T00:18:28.402Z" }, @@ -1794,45 +1444,6 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/4f/bd/de8d508070629b6d84a30d01d57e4a65c69aa7f5abe7560b8fad3b50ea59/termcolor-3.1.0-py3-none-any.whl", hash = "sha256:591dd26b5c2ce03b9e43f391264626557873ce1d379019786f99b0c2bee140aa", size = 7684, upload-time = "2025-04-30T11:37:52.382Z" }, ] -[[package]] -name = "tomli" -version = "2.2.1" -source = { registry = "https://pypi.org/simple" } -sdist = { url = "https://files.pythonhosted.org/packages/18/87/302344fed471e44a87289cf4967697d07e532f2421fdaf868a303cbae4ff/tomli-2.2.1.tar.gz", hash = "sha256:cd45e1dc79c835ce60f7404ec8119f2eb06d38b1deba146f07ced3bbc44505ff", size = 17175, upload-time = "2024-11-27T22:38:36.873Z" } -wheels = [ - { url = "https://files.pythonhosted.org/packages/43/ca/75707e6efa2b37c77dadb324ae7d9571cb424e61ea73fad7c56c2d14527f/tomli-2.2.1-cp311-cp311-macosx_10_9_x86_64.whl", hash = "sha256:678e4fa69e4575eb77d103de3df8a895e1591b48e740211bd1067378c69e8249", size = 131077, upload-time = "2024-11-27T22:37:54.956Z" }, - { url = "https://files.pythonhosted.org/packages/c7/16/51ae563a8615d472fdbffc43a3f3d46588c264ac4f024f63f01283becfbb/tomli-2.2.1-cp311-cp311-macosx_11_0_arm64.whl", hash = "sha256:023aa114dd824ade0100497eb2318602af309e5a55595f76b626d6d9f3b7b0a6", size = 123429, upload-time = "2024-11-27T22:37:56.698Z" }, - { url = "https://files.pythonhosted.org/packages/f1/dd/4f6cd1e7b160041db83c694abc78e100473c15d54620083dbd5aae7b990e/tomli-2.2.1-cp311-cp311-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:ece47d672db52ac607a3d9599a9d48dcb2f2f735c6c2d1f34130085bb12b112a", size = 226067, upload-time = "2024-11-27T22:37:57.63Z" }, - { url = "https://files.pythonhosted.org/packages/a9/6b/c54ede5dc70d648cc6361eaf429304b02f2871a345bbdd51e993d6cdf550/tomli-2.2.1-cp311-cp311-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:6972ca9c9cc9f0acaa56a8ca1ff51e7af152a9f87fb64623e31d5c83700080ee", size = 236030, upload-time = "2024-11-27T22:37:59.344Z" }, - { url = "https://files.pythonhosted.org/packages/1f/47/999514fa49cfaf7a92c805a86c3c43f4215621855d151b61c602abb38091/tomli-2.2.1-cp311-cp311-manylinux_2_5_i686.manylinux1_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:c954d2250168d28797dd4e3ac5cf812a406cd5a92674ee4c8f123c889786aa8e", size = 240898, upload-time = "2024-11-27T22:38:00.429Z" }, - { url = "https://files.pythonhosted.org/packages/73/41/0a01279a7ae09ee1573b423318e7934674ce06eb33f50936655071d81a24/tomli-2.2.1-cp311-cp311-musllinux_1_2_aarch64.whl", hash = "sha256:8dd28b3e155b80f4d54beb40a441d366adcfe740969820caf156c019fb5c7ec4", size = 229894, upload-time = "2024-11-27T22:38:02.094Z" }, - { url = "https://files.pythonhosted.org/packages/55/18/5d8bc5b0a0362311ce4d18830a5d28943667599a60d20118074ea1b01bb7/tomli-2.2.1-cp311-cp311-musllinux_1_2_i686.whl", hash = "sha256:e59e304978767a54663af13c07b3d1af22ddee3bb2fb0618ca1593e4f593a106", size = 245319, upload-time = "2024-11-27T22:38:03.206Z" }, - { url = "https://files.pythonhosted.org/packages/92/a3/7ade0576d17f3cdf5ff44d61390d4b3febb8a9fc2b480c75c47ea048c646/tomli-2.2.1-cp311-cp311-musllinux_1_2_x86_64.whl", hash = "sha256:33580bccab0338d00994d7f16f4c4ec25b776af3ffaac1ed74e0b3fc95e885a8", size = 238273, upload-time = "2024-11-27T22:38:04.217Z" }, - { url = "https://files.pythonhosted.org/packages/72/6f/fa64ef058ac1446a1e51110c375339b3ec6be245af9d14c87c4a6412dd32/tomli-2.2.1-cp311-cp311-win32.whl", hash = "sha256:465af0e0875402f1d226519c9904f37254b3045fc5084697cefb9bdde1ff99ff", size = 98310, upload-time = "2024-11-27T22:38:05.908Z" }, - { url = "https://files.pythonhosted.org/packages/6a/1c/4a2dcde4a51b81be3530565e92eda625d94dafb46dbeb15069df4caffc34/tomli-2.2.1-cp311-cp311-win_amd64.whl", hash = "sha256:2d0f2fdd22b02c6d81637a3c95f8cd77f995846af7414c5c4b8d0545afa1bc4b", size = 108309, upload-time = "2024-11-27T22:38:06.812Z" }, - { url = "https://files.pythonhosted.org/packages/52/e1/f8af4c2fcde17500422858155aeb0d7e93477a0d59a98e56cbfe75070fd0/tomli-2.2.1-cp312-cp312-macosx_10_13_x86_64.whl", hash = "sha256:4a8f6e44de52d5e6c657c9fe83b562f5f4256d8ebbfe4ff922c495620a7f6cea", size = 132762, upload-time = "2024-11-27T22:38:07.731Z" }, - { url = "https://files.pythonhosted.org/packages/03/b8/152c68bb84fc00396b83e7bbddd5ec0bd3dd409db4195e2a9b3e398ad2e3/tomli-2.2.1-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:8d57ca8095a641b8237d5b079147646153d22552f1c637fd3ba7f4b0b29167a8", size = 123453, upload-time = "2024-11-27T22:38:09.384Z" }, - { url = "https://files.pythonhosted.org/packages/c8/d6/fc9267af9166f79ac528ff7e8c55c8181ded34eb4b0e93daa767b8841573/tomli-2.2.1-cp312-cp312-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:4e340144ad7ae1533cb897d406382b4b6fede8890a03738ff1683af800d54192", size = 233486, upload-time = "2024-11-27T22:38:10.329Z" }, - { url = "https://files.pythonhosted.org/packages/5c/51/51c3f2884d7bab89af25f678447ea7d297b53b5a3b5730a7cb2ef6069f07/tomli-2.2.1-cp312-cp312-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:db2b95f9de79181805df90bedc5a5ab4c165e6ec3fe99f970d0e302f384ad222", size = 242349, upload-time = "2024-11-27T22:38:11.443Z" }, - { url = "https://files.pythonhosted.org/packages/ab/df/bfa89627d13a5cc22402e441e8a931ef2108403db390ff3345c05253935e/tomli-2.2.1-cp312-cp312-manylinux_2_5_i686.manylinux1_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:40741994320b232529c802f8bc86da4e1aa9f413db394617b9a256ae0f9a7f77", size = 252159, upload-time = "2024-11-27T22:38:13.099Z" }, - { url = "https://files.pythonhosted.org/packages/9e/6e/fa2b916dced65763a5168c6ccb91066f7639bdc88b48adda990db10c8c0b/tomli-2.2.1-cp312-cp312-musllinux_1_2_aarch64.whl", hash = "sha256:400e720fe168c0f8521520190686ef8ef033fb19fc493da09779e592861b78c6", size = 237243, upload-time = "2024-11-27T22:38:14.766Z" }, - { url = "https://files.pythonhosted.org/packages/b4/04/885d3b1f650e1153cbb93a6a9782c58a972b94ea4483ae4ac5cedd5e4a09/tomli-2.2.1-cp312-cp312-musllinux_1_2_i686.whl", hash = "sha256:02abe224de6ae62c19f090f68da4e27b10af2b93213d36cf44e6e1c5abd19fdd", size = 259645, upload-time = "2024-11-27T22:38:15.843Z" }, - { url = "https://files.pythonhosted.org/packages/9c/de/6b432d66e986e501586da298e28ebeefd3edc2c780f3ad73d22566034239/tomli-2.2.1-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:b82ebccc8c8a36f2094e969560a1b836758481f3dc360ce9a3277c65f374285e", size = 244584, upload-time = "2024-11-27T22:38:17.645Z" }, - { url = "https://files.pythonhosted.org/packages/1c/9a/47c0449b98e6e7d1be6cbac02f93dd79003234ddc4aaab6ba07a9a7482e2/tomli-2.2.1-cp312-cp312-win32.whl", hash = "sha256:889f80ef92701b9dbb224e49ec87c645ce5df3fa2cc548664eb8a25e03127a98", size = 98875, upload-time = "2024-11-27T22:38:19.159Z" }, - { url = "https://files.pythonhosted.org/packages/ef/60/9b9638f081c6f1261e2688bd487625cd1e660d0a85bd469e91d8db969734/tomli-2.2.1-cp312-cp312-win_amd64.whl", hash = "sha256:7fc04e92e1d624a4a63c76474610238576942d6b8950a2d7f908a340494e67e4", size = 109418, upload-time = "2024-11-27T22:38:20.064Z" }, - { url = "https://files.pythonhosted.org/packages/04/90/2ee5f2e0362cb8a0b6499dc44f4d7d48f8fff06d28ba46e6f1eaa61a1388/tomli-2.2.1-cp313-cp313-macosx_10_13_x86_64.whl", hash = "sha256:f4039b9cbc3048b2416cc57ab3bda989a6fcf9b36cf8937f01a6e731b64f80d7", size = 132708, upload-time = "2024-11-27T22:38:21.659Z" }, - { url = "https://files.pythonhosted.org/packages/c0/ec/46b4108816de6b385141f082ba99e315501ccd0a2ea23db4a100dd3990ea/tomli-2.2.1-cp313-cp313-macosx_11_0_arm64.whl", hash = "sha256:286f0ca2ffeeb5b9bd4fcc8d6c330534323ec51b2f52da063b11c502da16f30c", size = 123582, upload-time = "2024-11-27T22:38:22.693Z" }, - { url = "https://files.pythonhosted.org/packages/a0/bd/b470466d0137b37b68d24556c38a0cc819e8febe392d5b199dcd7f578365/tomli-2.2.1-cp313-cp313-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:a92ef1a44547e894e2a17d24e7557a5e85a9e1d0048b0b5e7541f76c5032cb13", size = 232543, upload-time = "2024-11-27T22:38:24.367Z" }, - { url = "https://files.pythonhosted.org/packages/d9/e5/82e80ff3b751373f7cead2815bcbe2d51c895b3c990686741a8e56ec42ab/tomli-2.2.1-cp313-cp313-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:9316dc65bed1684c9a98ee68759ceaed29d229e985297003e494aa825ebb0281", size = 241691, upload-time = "2024-11-27T22:38:26.081Z" }, - { url = "https://files.pythonhosted.org/packages/05/7e/2a110bc2713557d6a1bfb06af23dd01e7dde52b6ee7dadc589868f9abfac/tomli-2.2.1-cp313-cp313-manylinux_2_5_i686.manylinux1_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:e85e99945e688e32d5a35c1ff38ed0b3f41f43fad8df0bdf79f72b2ba7bc5272", size = 251170, upload-time = "2024-11-27T22:38:27.921Z" }, - { url = "https://files.pythonhosted.org/packages/64/7b/22d713946efe00e0adbcdfd6d1aa119ae03fd0b60ebed51ebb3fa9f5a2e5/tomli-2.2.1-cp313-cp313-musllinux_1_2_aarch64.whl", hash = "sha256:ac065718db92ca818f8d6141b5f66369833d4a80a9d74435a268c52bdfa73140", size = 236530, upload-time = "2024-11-27T22:38:29.591Z" }, - { url = "https://files.pythonhosted.org/packages/38/31/3a76f67da4b0cf37b742ca76beaf819dca0ebef26d78fc794a576e08accf/tomli-2.2.1-cp313-cp313-musllinux_1_2_i686.whl", hash = "sha256:d920f33822747519673ee656a4b6ac33e382eca9d331c87770faa3eef562aeb2", size = 258666, upload-time = "2024-11-27T22:38:30.639Z" }, - { url = "https://files.pythonhosted.org/packages/07/10/5af1293da642aded87e8a988753945d0cf7e00a9452d3911dd3bb354c9e2/tomli-2.2.1-cp313-cp313-musllinux_1_2_x86_64.whl", hash = "sha256:a198f10c4d1b1375d7687bc25294306e551bf1abfa4eace6650070a5c1ae2744", size = 243954, upload-time = "2024-11-27T22:38:31.702Z" }, - { url = "https://files.pythonhosted.org/packages/5b/b9/1ed31d167be802da0fc95020d04cd27b7d7065cc6fbefdd2f9186f60d7bd/tomli-2.2.1-cp313-cp313-win32.whl", hash = "sha256:d3f5614314d758649ab2ab3a62d4f2004c825922f9e370b29416484086b264ec", size = 98724, upload-time = "2024-11-27T22:38:32.837Z" }, - { url = "https://files.pythonhosted.org/packages/c7/32/b0963458706accd9afcfeb867c0f9175a741bf7b19cd424230714d722198/tomli-2.2.1-cp313-cp313-win_amd64.whl", hash = "sha256:a38aa0308e754b0e3c67e344754dff64999ff9b513e691d0e786265c93583c69", size = 109383, upload-time = "2024-11-27T22:38:34.455Z" }, - { url = "https://files.pythonhosted.org/packages/6e/c2/61d3e0f47e2b74ef40a68b9e6ad5984f6241a942f7cd3bbfbdbd03861ea9/tomli-2.2.1-py3-none-any.whl", hash = "sha256:cb55c73c5f4408779d0cf3eef9f762b9c9f147a77de7b258bef0a5628adc85cc", size = 14257, upload-time = "2024-11-27T22:38:35.385Z" }, -] - [[package]] name = "toolz" version = "1.0.0" @@ -1847,8 +1458,7 @@ name = "treescope" version = "0.1.10" source = { registry = "https://pypi.org/simple" } dependencies = [ - { name = "numpy", version = "2.2.6", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version < '3.11'" }, - { name = "numpy", version = "2.3.3", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version >= '3.11'" }, + { name = "numpy" }, ] sdist = { url = "https://files.pythonhosted.org/packages/f0/2a/d13d3c38862632742d2fe2f7ae307c431db06538fd05ca03020d207b5dcc/treescope-0.1.10.tar.gz", hash = "sha256:20f74656f34ab2d8716715013e8163a0da79bdc2554c16d5023172c50d27ea95", size = 138870, upload-time = "2025-08-08T05:43:48.048Z" } wheels = [ @@ -1881,7 +1491,6 @@ dependencies = [ { name = "distlib" }, { name = "filelock" }, { name = "platformdirs" }, - { name = "typing-extensions", marker = "python_full_version < '3.11'" }, ] sdist = { url = "https://files.pythonhosted.org/packages/1c/14/37fcdba2808a6c615681cd216fecae00413c9dab44fb2e57805ecf3eaee3/virtualenv-20.34.0.tar.gz", hash = "sha256:44815b2c9dee7ed86e387b842a84f20b93f7f417f95886ca1996a72a4138eb1a", size = 6003808, upload-time = "2025-08-13T14:24:07.464Z" } wheels = [ @@ -1903,9 +1512,6 @@ version = "6.0.0" source = { registry = "https://pypi.org/simple" } sdist = { url = "https://files.pythonhosted.org/packages/db/7d/7f3d619e951c88ed75c6037b246ddcf2d322812ee8ea189be89511721d54/watchdog-6.0.0.tar.gz", hash = "sha256:9ddf7c82fda3ae8e24decda1338ede66e1c99883db93711d8fb941eaa2d8c282", size = 131220, upload-time = "2024-11-01T14:07:13.037Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/0c/56/90994d789c61df619bfc5ce2ecdabd5eeff564e1eb47512bd01b5e019569/watchdog-6.0.0-cp310-cp310-macosx_10_9_universal2.whl", hash = "sha256:d1cdb490583ebd691c012b3d6dae011000fe42edb7a82ece80965b42abd61f26", size = 96390, upload-time = "2024-11-01T14:06:24.793Z" }, - { url = "https://files.pythonhosted.org/packages/55/46/9a67ee697342ddf3c6daa97e3a587a56d6c4052f881ed926a849fcf7371c/watchdog-6.0.0-cp310-cp310-macosx_10_9_x86_64.whl", hash = "sha256:bc64ab3bdb6a04d69d4023b29422170b74681784ffb9463ed4870cf2f3e66112", size = 88389, upload-time = "2024-11-01T14:06:27.112Z" }, - { url = "https://files.pythonhosted.org/packages/44/65/91b0985747c52064d8701e1075eb96f8c40a79df889e59a399453adfb882/watchdog-6.0.0-cp310-cp310-macosx_11_0_arm64.whl", hash = "sha256:c897ac1b55c5a1461e16dae288d22bb2e412ba9807df8397a635d88f671d36c3", size = 89020, upload-time = "2024-11-01T14:06:29.876Z" }, { url = "https://files.pythonhosted.org/packages/e0/24/d9be5cd6642a6aa68352ded4b4b10fb0d7889cb7f45814fb92cecd35f101/watchdog-6.0.0-cp311-cp311-macosx_10_9_universal2.whl", hash = "sha256:6eb11feb5a0d452ee41f824e271ca311a09e250441c262ca2fd7ebcf2461a06c", size = 96393, upload-time = "2024-11-01T14:06:31.756Z" }, { url = "https://files.pythonhosted.org/packages/63/7a/6013b0d8dbc56adca7fdd4f0beed381c59f6752341b12fa0886fa7afc78b/watchdog-6.0.0-cp311-cp311-macosx_10_9_x86_64.whl", hash = "sha256:ef810fbf7b781a5a593894e4f439773830bdecb885e6880d957d5b9382a960d2", size = 88392, upload-time = "2024-11-01T14:06:32.99Z" }, { url = "https://files.pythonhosted.org/packages/d1/40/b75381494851556de56281e053700e46bff5b37bf4c7267e858640af5a7f/watchdog-6.0.0-cp311-cp311-macosx_11_0_arm64.whl", hash = "sha256:afd0fe1b2270917c5e23c2a65ce50c2a4abb63daafb0d419fde368e272a76b7c", size = 89019, upload-time = "2024-11-01T14:06:34.963Z" }, @@ -1915,8 +1521,6 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/68/98/b0345cabdce2041a01293ba483333582891a3bd5769b08eceb0d406056ef/watchdog-6.0.0-cp313-cp313-macosx_10_13_universal2.whl", hash = "sha256:490ab2ef84f11129844c23fb14ecf30ef3d8a6abafd3754a6f75ca1e6654136c", size = 96480, upload-time = "2024-11-01T14:06:42.952Z" }, { url = "https://files.pythonhosted.org/packages/85/83/cdf13902c626b28eedef7ec4f10745c52aad8a8fe7eb04ed7b1f111ca20e/watchdog-6.0.0-cp313-cp313-macosx_10_13_x86_64.whl", hash = "sha256:76aae96b00ae814b181bb25b1b98076d5fc84e8a53cd8885a318b42b6d3a5134", size = 88451, upload-time = "2024-11-01T14:06:45.084Z" }, { url = "https://files.pythonhosted.org/packages/fe/c4/225c87bae08c8b9ec99030cd48ae9c4eca050a59bf5c2255853e18c87b50/watchdog-6.0.0-cp313-cp313-macosx_11_0_arm64.whl", hash = "sha256:a175f755fc2279e0b7312c0035d52e27211a5bc39719dd529625b1930917345b", size = 89057, upload-time = "2024-11-01T14:06:47.324Z" }, - { url = "https://files.pythonhosted.org/packages/30/ad/d17b5d42e28a8b91f8ed01cb949da092827afb9995d4559fd448d0472763/watchdog-6.0.0-pp310-pypy310_pp73-macosx_10_15_x86_64.whl", hash = "sha256:c7ac31a19f4545dd92fc25d200694098f42c9a8e391bc00bdd362c5736dbf881", size = 87902, upload-time = "2024-11-01T14:06:53.119Z" }, - { url = "https://files.pythonhosted.org/packages/5c/ca/c3649991d140ff6ab67bfc85ab42b165ead119c9e12211e08089d763ece5/watchdog-6.0.0-pp310-pypy310_pp73-macosx_11_0_arm64.whl", hash = "sha256:9513f27a1a582d9808cf21a07dae516f0fab1cf2d7683a742c498b93eedabb11", size = 88380, upload-time = "2024-11-01T14:06:55.19Z" }, { url = "https://files.pythonhosted.org/packages/a9/c7/ca4bf3e518cb57a686b2feb4f55a1892fd9a3dd13f470fca14e00f80ea36/watchdog-6.0.0-py3-none-manylinux2014_aarch64.whl", hash = "sha256:7607498efa04a3542ae3e05e64da8202e58159aa1fa4acddf7678d34a35d4f13", size = 79079, upload-time = "2024-11-01T14:06:59.472Z" }, { url = "https://files.pythonhosted.org/packages/5c/51/d46dc9332f9a647593c947b4b88e2381c8dfc0942d15b8edc0310fa4abb1/watchdog-6.0.0-py3-none-manylinux2014_armv7l.whl", hash = "sha256:9041567ee8953024c83343288ccc458fd0a2d811d6a0fd68c4c22609e3490379", size = 79078, upload-time = "2024-11-01T14:07:01.431Z" }, { url = "https://files.pythonhosted.org/packages/d4/57/04edbf5e169cd318d5f07b4766fee38e825d64b6913ca157ca32d1a42267/watchdog-6.0.0-py3-none-manylinux2014_i686.whl", hash = "sha256:82dc3e3143c7e38ec49d61af98d6558288c415eac98486a5c581726e0737c00e", size = 79076, upload-time = "2024-11-01T14:07:02.568Z" }, commit 96aef9053cea5071ffa2e635d1d124d713623b62 Date: 2025-10-02T14:56:42-04:00 Linear Mup Layers diff --git a/src/haliax/nn/linear.py b/src/haliax/nn/linear.py index ddba493..cde11f7 100644 --- a/src/haliax/nn/linear.py +++ b/src/haliax/nn/linear.py @@ -37,8 +37,9 @@ class Linear(ModuleWithStateDictSerialization): Out: AxisSpec = eqx.field(static=True) dot_general: DotGeneralOp = eqx.field(default_factory=DotGeneralOp.default) - @staticmethod + @classmethod def init( + cls, In: AxisSpec, Out: AxisSpec, *, @@ -197,7 +198,10 @@ class MoELinear(eqx.Module): dim_numbers = jax.lax.RaggedDotDimensionNumbers( dot_dimension_numbers=( # contracting - (ensure_tuple(inputs.axis_indices(self.In)), ensure_tuple(self.weight.axis_indices(self.In))), + ( + ensure_tuple(inputs.axis_indices(self.In)), + ensure_tuple(self.weight.axis_indices(self.In)), + ), # batch ((), ()), ), diff --git a/src/haliax/nn/mup.py b/src/haliax/nn/mup.py new file mode 100644 index 0000000..15e1008 --- /dev/null +++ b/src/haliax/nn/mup.py @@ -0,0 +1,121 @@ +# Copyright 2025 The Levanter Authors +# +# SPDX-License-Identifier: Apache-2.0 + + +import dataclasses +import math +from typing import Optional + +from jax.random import PRNGKey + +import haliax as hax + +from .._src.state_dict import ( + Mod, + default_eqx_module_from_state_dict, + default_eqx_module_to_state_dict, + StateDict, +) +from ..axis import AxisSpec +from ..jax_utils import named_call +from ..quantization import DotGeneralOp + +from .linear import Linear + + +class MupMixin: + @staticmethod + def mup_init_scale(In: AxisSpec, Out: AxisSpec): + return 1 + + @property + def mup_lr_scale(self): + return 1 + + @property + def mup_active_scale(self): + return 1 + + +class MupLinear(Linear, MupMixin): + @classmethod + def init( + cls, + In: AxisSpec, + Out: AxisSpec, + *, + key: PRNGKey, + use_bias: bool = True, + out_first: bool = True, + dot_general: Optional[DotGeneralOp] = None, + init_scale: float = 1.0, + ) -> "MupLinear": + """ + Args: + In: AxisSpec: The input axis spec + Out: AxisSpec: The output axis spec + key: PRNGKeyArray: The PRNG key to use for initialization + use_bias: bool: Whether to use a bias term + out_first: bool: Whether to put output axes first in the weight matrix. out_first is how PyTorch does it. + dot_general: Callable: The dot_general function to use. Defaults to jax.lax.dot_general. + init_scale: float: The scale to use for initialization. We scale init by 1/sqrt(Input.size)*init_scale + """ + joint_spec = hax.concat_axis_specs(Out, In) if out_first else hax.concat_axis_specs(In, Out) + + weight = hax.random.truncated_normal(key, joint_spec, -3, 3) * (init_scale * cls.mup_init_scale(In, Out)) + bias = hax.zeros(Out) if use_bias else None + + if dot_general is None: + dot_general = DotGeneralOp.default() + + return cls(weight, bias, In, Out, dot_general=dot_general) + + @named_call + def __call__(self, inputs, *, key: Optional[PRNGKey] = None): + """ + Args: + inputs (NamedArray): Input array + key: Not used, but there for compat with other modules + """ + del key + q = inputs.dot( + self.weight * self.mup_active_scale, + axis=self.In, + dot_general=self.dot_general, + ) + q = hax.auto_sharded(q) + + if self.bias is not None: + q = q + self.bias + q = hax.auto_sharded(q) + + return q + + def to_state_dict(self, prefix: Optional[str] = None) -> StateDict: + scaled = dataclasses.replace(self, weight=self.weight * self.mup_active_scale) + return default_eqx_module_to_state_dict(scaled, prefix) + + def from_state_dict(self: Mod, state_dict: StateDict, prefix: Optional[str] = None) -> Mod: + unscaled = default_eqx_module_from_state_dict(self, state_dict, prefix) + return dataclasses.replace(unscaled, weight=unscaled.weight / self.mup_active_scale) + + +class InputLinear(MupLinear): + pass + + +class OutputLinear(MupLinear): + @property + def mup_active_scale(self): + return 1 / hax.axis_size(self.In) + + +class HiddenLinear(MupLinear): + @property + def mup_lr_scale(self): + return 1 / hax.axis_size(self.In) + + @property + def mup_init_scale(self): + return 1 / math.sqrt(hax.axis_size(self.In)) commit 5e65c2eea75197b232ffd3015fa3d956e6bca9a8 Date: 2025-10-02T16:43:49-04:00 Test Linear Layers diff --git a/src/haliax/nn/mup.py b/src/haliax/nn/mup.py index 15e1008..0fbcf4e 100644 --- a/src/haliax/nn/mup.py +++ b/src/haliax/nn/mup.py @@ -116,6 +116,7 @@ class HiddenLinear(MupLinear): def mup_lr_scale(self): return 1 / hax.axis_size(self.In) - @property - def mup_init_scale(self): - return 1 / math.sqrt(hax.axis_size(self.In)) + @staticmethod + def mup_init_scale(In: AxisSpec, Out: AxisSpec): + del Out + return 1 / math.sqrt(hax.axis_size(In)) diff --git a/tests/test_mup_linear.py b/tests/test_mup_linear.py new file mode 100644 index 0000000..63b42b7 --- /dev/null +++ b/tests/test_mup_linear.py @@ -0,0 +1,120 @@ +# Copyright 2025 The Levanter Authors +# +# SPDX-License-Identifier: Apache-2.0 + + +import dataclasses + +import jax.numpy as jnp +import jax.random as jrandom +import pytest + +import haliax as hax +from haliax.nn import Linear +from haliax.nn.mup import HiddenLinear, InputLinear, MupLinear, OutputLinear + + +@pytest.mark.parametrize("out_first", [True, False]) +def test_mup_linear_init_matches_linear_axes(out_first: bool): + In = (hax.Axis("I", 3), hax.Axis("J", 2)) + Out = (hax.Axis("O", 5),) + key_linear, key_mup = jrandom.split(jrandom.PRNGKey(0)) + + linear = Linear.init(In, Out, key=key_linear, out_first=out_first) + mup = MupLinear.init(In, Out, key=key_mup, out_first=out_first) + + assert linear.weight.axes == mup.weight.axes + if linear.bias is not None: + assert mup.bias is not None + assert linear.bias.axes == mup.bias.axes + + +def test_mup_linear_respects_bias_flag(): + In = hax.Axis("I", 4) + Out = hax.Axis("O", 3) + layer = MupLinear.init(In, Out, key=jrandom.PRNGKey(1), use_bias=False) + assert layer.bias is None + + +def test_mup_linear_call_matches_linear(): + Batch = hax.Axis("B", 2) + In = (hax.Axis("I", 3),) + Out = (hax.Axis("O", 4),) + + weight = hax.ones(hax.concat_axis_specs(Out, In)) * 0.5 + bias = hax.full(Out, 0.25) + + linear = Linear(weight, bias, In, Out) + mup = MupLinear(weight, bias, In, Out) + + inputs = hax.full(hax.concat_axis_specs(Batch, In), 2.0) + + expected = linear(inputs) + actual = mup(inputs) + + assert actual.axes == expected.axes + assert jnp.allclose(actual.array, expected.array) + + +@pytest.mark.parametrize("out_first", [True, False]) +def test_hidden_linear_init_matches_linear_scaling(out_first: bool): + In = hax.Axis("I", 6) + Out = hax.Axis("O", 5) + key = jrandom.PRNGKey(0) + + linear = Linear.init(In, Out, key=key, use_bias=False, out_first=out_first) + hidden = HiddenLinear.init(In, Out, key=key, use_bias=False, out_first=out_first) + + assert jnp.allclose(hidden.weight.array, linear.weight.array) + + +def test_output_linear_scales_activation_by_input_size(): + Batch = hax.Axis("B", 2) + In = hax.Axis("I", 3) + Out = hax.Axis("O", 2) + + layer = OutputLinear.init(In, Out, key=jrandom.PRNGKey(2), use_bias=False) + layer = dataclasses.replace(layer, weight=hax.ones(layer.weight.axes)) + + inputs = hax.full((Batch, In), 2.0) + expected = hax.full(hax.concat_axis_specs(Batch, layer.Out), 2.0) + + actual = layer(inputs) + + assert actual.axes == expected.axes + assert jnp.allclose(actual.array, expected.array) + + +def test_output_linear_state_dict_scales_weight(): + In = hax.Axis("I", 4) + Out = hax.Axis("O", 3) + + layer = OutputLinear.init(In, Out, key=jrandom.PRNGKey(3), use_bias=False) + layer = dataclasses.replace(layer, weight=hax.ones(layer.weight.axes)) + + state = layer.to_state_dict() + assert jnp.allclose(state["weight"], layer.weight.array * layer.mup_active_scale) + + template = OutputLinear.init(In, Out, key=jrandom.PRNGKey(4), use_bias=False) + restored = template.from_state_dict(state) + + assert jnp.allclose(restored.weight.array, layer.weight.array) + + +def test_input_linear_behaves_like_base_linear(): + Batch = hax.Axis("B", 2) + In = hax.Axis("I", 3) + Out = hax.Axis("O", 4) + + weight = hax.ones((Out, In)) * 0.1 + bias = hax.zeros(Out) + + linear = Linear(weight, bias, In, Out) + input_linear = InputLinear(weight, bias, In, Out) + + inputs = hax.random.normal(jrandom.PRNGKey(5), (Batch, In)) + + expected = linear(inputs) + actual = input_linear(inputs) + + assert jnp.allclose(actual.array, expected.array) commit 133e2e0411e519d946443649b0d67519e7f5cd7d Date: 2025-10-02T19:44:10-04:00 MuP Embedding diff --git a/src/haliax/nn/mup.py b/src/haliax/nn/mup.py index 0fbcf4e..1f98f03 100644 --- a/src/haliax/nn/mup.py +++ b/src/haliax/nn/mup.py @@ -5,6 +5,7 @@ import dataclasses import math +import warnings from typing import Optional from jax.random import PRNGKey @@ -13,14 +14,17 @@ import haliax as hax from .._src.state_dict import ( Mod, + StateDict, default_eqx_module_from_state_dict, default_eqx_module_to_state_dict, - StateDict, + to_state_dict as _tree_to_state_dict, + with_prefix, ) -from ..axis import AxisSpec +from ..axis import Axis, AxisSpec from ..jax_utils import named_call from ..quantization import DotGeneralOp +from .embedding import Embedding from .linear import Linear @@ -61,9 +65,15 @@ class MupLinear(Linear, MupMixin): dot_general: Callable: The dot_general function to use. Defaults to jax.lax.dot_general. init_scale: float: The scale to use for initialization. We scale init by 1/sqrt(Input.size)*init_scale """ - joint_spec = hax.concat_axis_specs(Out, In) if out_first else hax.concat_axis_specs(In, Out) + joint_spec = ( + hax.concat_axis_specs(Out, In) + if out_first + else hax.concat_axis_specs(In, Out) + ) - weight = hax.random.truncated_normal(key, joint_spec, -3, 3) * (init_scale * cls.mup_init_scale(In, Out)) + weight = hax.random.truncated_normal(key, joint_spec, -3, 3) * ( + init_scale * cls.mup_init_scale(In, Out) + ) bias = hax.zeros(Out) if use_bias else None if dot_general is None: @@ -96,11 +106,16 @@ class MupLinear(Linear, MupMixin): scaled = dataclasses.replace(self, weight=self.weight * self.mup_active_scale) return default_eqx_module_to_state_dict(scaled, prefix) - def from_state_dict(self: Mod, state_dict: StateDict, prefix: Optional[str] = None) -> Mod: + def from_state_dict( + self: Mod, state_dict: StateDict, prefix: Optional[str] = None + ) -> Mod: unscaled = default_eqx_module_from_state_dict(self, state_dict, prefix) - return dataclasses.replace(unscaled, weight=unscaled.weight / self.mup_active_scale) + return dataclasses.replace( + unscaled, weight=unscaled.weight / self.mup_active_scale + ) +# Input Linear doesn't change ABC Parameters, but for clarity class InputLinear(MupLinear): pass @@ -118,5 +133,59 @@ class HiddenLinear(MupLinear): @staticmethod def mup_init_scale(In: AxisSpec, Out: AxisSpec): - del Out return 1 / math.sqrt(hax.axis_size(In)) + + +class MupEmbedding(Embedding, MupMixin): + """Embedding module with muP-aware scaling for tied embeddings.""" + + @staticmethod + def mup_init_scale(In: AxisSpec, Out: AxisSpec): + return 1 / hax.axis_size(Out) + + @classmethod + def init( + cls, + Vocab: Axis, + Embed: AxisSpec, + *, + init_scale: float = 1.0, + key: PRNGKey, + initializer_range: Optional[float] = None, + ) -> "MupEmbedding": + """Initializes the embedding weights following µP scaling rules.""" + + if initializer_range is not None: + warnings.warn( + "initializer_range is deprecated. Use init_scale instead.", + DeprecationWarning, + ) + init_scale = initializer_range + + weight = hax.random.truncated_normal( + key, hax.concat_axis_specs(Vocab, Embed), -3, 3 + ) * (init_scale * cls.mup_init_scale(Vocab, Embed)) + + return cls(weight=weight, Vocab=Vocab, Embed=Embed) + + @property + def unembedding_mup_active_scale(self) -> float: + """Scale factor applied to logits when using the weights for unembedding.""" + + return 1 / hax.axis_size(self.Embed) + + @property + def unembedding_weight(self): + """Effective weight matrix used on the unembedding path.""" + + return self.weight * self.unembedding_mup_active_scale + + def unembed(self, input_embeds): + logits = super().unembed(input_embeds) + return logits * self.unembedding_mup_active_scale + + def to_state_dict(self, prefix: Optional[str] = None) -> StateDict: + state_dict = default_eqx_module_to_state_dict(self, prefix) + unembed_key = with_prefix(prefix, "unembedding_weight") + state_dict.update(_tree_to_state_dict(self.unembedding_weight, unembed_key)) + return state_dict commit 23d529dbfcb60024c65b408dfe2a4ab0fa6048e4 Date: 2025-10-02T19:49:17-04:00 Embedding Test diff --git a/tests/test_mup_embedding.py b/tests/test_mup_embedding.py new file mode 100644 index 0000000..ab8335c --- /dev/null +++ b/tests/test_mup_embedding.py @@ -0,0 +1,71 @@ +# Copyright 2025 The Levanter Authors +# +# SPDX-License-Identifier: Apache-2.0 + +import jax.numpy as jnp +import jax.random as jrandom +import pytest + +import haliax as hax +from haliax.nn import Embedding +from haliax.nn.mup import MupEmbedding +from haliax.state_dict import from_state_dict + + +@pytest.mark.parametrize("init_scale", [0.5, 1.0]) +def test_mup_embedding_init_matches_embedding(init_scale: float): + Vocab = hax.Axis("V", 8) + Embed = (hax.Axis("E", 4),) + + key = jrandom.PRNGKey(0) + + baseline = Embedding.init(Vocab, Embed, key=key, init_scale=init_scale) + mup = MupEmbedding.init(Vocab, Embed, key=key, init_scale=init_scale) + + assert mup.weight.axes == baseline.weight.axes + assert jnp.allclose(mup.weight.array, baseline.weight.array) + + +def test_mup_embedding_unembedding_scale(): + Vocab = hax.Axis("V", 6) + Embed = (hax.Axis("E", 3),) + + weight = hax.ones(hax.concat_axis_specs(Vocab, Embed)) + layer = MupEmbedding(weight=weight, Vocab=Vocab, Embed=Embed) + + assert layer.unembedding_mup_active_scale == pytest.approx(1.0 / Embed[0].size) + assert jnp.allclose(layer.unembedding_weight.array, weight.array * layer.unembedding_mup_active_scale) + + Batch = hax.Axis("B", 2) + inputs = hax.ones((Batch, *Embed)) + + logits = layer.unembed(inputs) + expected = hax.ones((Batch, Vocab)) + + assert logits.axes == expected.axes + assert jnp.allclose(logits.array, expected.array) + + +def test_mup_embedding_state_dict_adds_unembedding_weight(): + Vocab = hax.Axis("V", 5) + Embed = (hax.Axis("E", 2),) + + weight = hax.random.normal(jrandom.PRNGKey(1), hax.concat_axis_specs(Vocab, Embed)) + layer = MupEmbedding(weight=weight, Vocab=Vocab, Embed=Embed) + + state = layer.to_state_dict() + assert "unembedding_weight" in state + assert jnp.allclose(state["unembedding_weight"], layer.unembedding_weight.array) + + template = MupEmbedding.init(Vocab, Embed, key=jrandom.PRNGKey(2)) + restored = from_state_dict(template, state) + + assert jnp.allclose(restored.weight.array, layer.weight.array) + + +def test_mup_embedding_initializer_range_warns(): + Vocab = hax.Axis("V", 3) + Embed = (hax.Axis("E", 2),) + + with pytest.warns(DeprecationWarning): + MupEmbedding.init(Vocab, Embed, key=jrandom.PRNGKey(3), initializer_range=0.5) commit da6985099f1fc5bbc7dfa144cf92a7f4a940e506 Date: 2025-10-02T19:55:33-04:00 Lint diff --git a/src/haliax/nn/mup.py b/src/haliax/nn/mup.py index 1f98f03..5ee94ee 100644 --- a/src/haliax/nn/mup.py +++ b/src/haliax/nn/mup.py @@ -65,15 +65,9 @@ class MupLinear(Linear, MupMixin): dot_general: Callable: The dot_general function to use. Defaults to jax.lax.dot_general. init_scale: float: The scale to use for initialization. We scale init by 1/sqrt(Input.size)*init_scale """ - joint_spec = ( - hax.concat_axis_specs(Out, In) - if out_first - else hax.concat_axis_specs(In, Out) - ) + joint_spec = hax.concat_axis_specs(Out, In) if out_first else hax.concat_axis_specs(In, Out) - weight = hax.random.truncated_normal(key, joint_spec, -3, 3) * ( - init_scale * cls.mup_init_scale(In, Out) - ) + weight = hax.random.truncated_normal(key, joint_spec, -3, 3) * (init_scale * cls.mup_init_scale(In, Out)) bias = hax.zeros(Out) if use_bias else None if dot_general is None: @@ -106,13 +100,9 @@ class MupLinear(Linear, MupMixin): scaled = dataclasses.replace(self, weight=self.weight * self.mup_active_scale) return default_eqx_module_to_state_dict(scaled, prefix) - def from_state_dict( - self: Mod, state_dict: StateDict, prefix: Optional[str] = None - ) -> Mod: + def from_state_dict(self: Mod, state_dict: StateDict, prefix: Optional[str] = None) -> Mod: unscaled = default_eqx_module_from_state_dict(self, state_dict, prefix) - return dataclasses.replace( - unscaled, weight=unscaled.weight / self.mup_active_scale - ) + return dataclasses.replace(unscaled, weight=unscaled.weight / self.mup_active_scale) # Input Linear doesn't change ABC Parameters, but for clarity @@ -162,9 +152,9 @@ class MupEmbedding(Embedding, MupMixin): ) init_scale = initializer_range - weight = hax.random.truncated_normal( - key, hax.concat_axis_specs(Vocab, Embed), -3, 3 - ) * (init_scale * cls.mup_init_scale(Vocab, Embed)) + weight = hax.random.truncated_normal(key, hax.concat_axis_specs(Vocab, Embed), -3, 3) * ( + init_scale * cls.mup_init_scale(Vocab, Embed) + ) return cls(weight=weight, Vocab=Vocab, Embed=Embed) commit b9d73643535ca9023257c6e9f34967639de430fb Date: 2025-10-02T20:20:53-04:00 Coordinate Check for Stability diff --git a/tests/test_mup_coordinate_check.py b/tests/test_mup_coordinate_check.py new file mode 100644 index 0000000..25e1f51 --- /dev/null +++ b/tests/test_mup_coordinate_check.py @@ -0,0 +1,164 @@ +# Copyright 2025 The Levanter Authors +# +# SPDX-License-Identifier: Apache-2.0 + +"""Coordinate check for µP modules built on Haliax primitives.""" + +from __future__ import annotations + +import dataclasses +from typing import Any, Iterable + +import equinox as eqx +import jax +import jax.random as jrandom + +import haliax as hax +from haliax import Axis, NamedArray +from haliax.nn import Linear, activations +from haliax.nn.mup import HiddenLinear, InputLinear, OutputLinear + + +class TinyMLP(eqx.Module): + """Minimal 2-hidden-layer MLP composed of Haliax Linear variants.""" + + first: Linear + second: Linear + third: Linear + + @staticmethod + def init(width: int, *, key: jax.Array, use_mup: bool) -> TinyMLP: + in_axis = Axis("in", 2) + hidden = Axis("hidden", width) + hidden2 = hidden.alias("hidden2") + out_axis = Axis("out", 1) + + k1, k2, k3 = jrandom.split(key, 3) + + if use_mup: + first = InputLinear.init((in_axis,), hidden, key=k1) + second = HiddenLinear.init(hidden, hidden2, key=k2) + third = OutputLinear.init(hidden2, (out_axis,), key=k3) + else: + first = Linear.init((in_axis,), hidden, key=k1) + second = Linear.init(hidden, hidden2, key=k2) + third = Linear.init(hidden2, (out_axis,), key=k3) + + return TinyMLP(first=first, second=second, third=third) + + def __call__(self, x: NamedArray) -> NamedArray: + h = activations.relu(self.first(x)) + h = activations.relu(self.second(h)) + return self.third(h) + + +def _loss_fn(params: TinyMLP, x: NamedArray, y: NamedArray) -> jax.Array: + preds = params(x) + diff = preds - y + return hax.mean(diff * diff).scalar() + + +_loss_and_grad = eqx.filter_jit(eqx.filter_value_and_grad(_loss_fn)) +_loss_value = jax.jit(_loss_fn) + + +def _apply_sgd(module: TinyMLP, grads: TinyMLP, *, base_lr: float, use_mup: bool) -> TinyMLP: + def update_linear(layer: Linear, grad_layer: Linear) -> Linear: + lr_scale = getattr(layer, "mup_lr_scale", 1.0) if use_mup else 1.0 + new_weight = layer.weight - (base_lr * lr_scale) * grad_layer.weight + if layer.bias is None or grad_layer.bias is None: + new_bias = layer.bias + else: + new_bias = layer.bias - base_lr * grad_layer.bias + return dataclasses.replace(layer, weight=new_weight, bias=new_bias) + + return TinyMLP( + first=update_linear(module.first, grads.first), + second=update_linear(module.second, grads.second), + third=update_linear(module.third, grads.third), + ) + + +def _make_dataset(key: jax.Array, *, n_points: int = 2048) -> tuple[NamedArray, NamedArray]: + data_axis = Axis("data", n_points) + feature_axis = Axis("in", 2) + out_axis = Axis("out", 1) + + xy = jrandom.uniform(key, (n_points, 2), minval=-1.0, maxval=1.0) + inputs = hax.named(xy, (data_axis, feature_axis)) + targets = hax.named(xy[:, :1], (data_axis, out_axis)) + return inputs, targets + + +def _run_once( + key: jax.Array, + *, + width: int, + use_mup: bool, + steps: int = 120, + batch_size: int = 256, + base_lr: float = 3e-3, +) -> float: + data_key, model_key = jrandom.split(key) + inputs, targets = _make_dataset(data_key) + params = TinyMLP.init(width, key=model_key, use_mup=use_mup) + + def train_step(state: TinyMLP, xb: NamedArray, yb: NamedArray): + loss, grads = _loss_and_grad(state, xb, yb) + new_state = _apply_sgd(state, grads, base_lr=base_lr, use_mup=use_mup) + return new_state, loss + + data_axis = inputs.axes[0] + n = data_axis.size + + state = params + for t in range(steps): + start = (t * batch_size) % n + end = start + batch_size + batch_idx = (data_axis, slice(start, end)) + xb = inputs[batch_idx] + yb = targets[batch_idx] + state, _ = train_step(state, xb, yb) + + final_loss = _loss_value(state, inputs, targets) + return float(final_loss) + + +def _span(values: Iterable[float]) -> float: + seq = list(values) + return max(seq) - min(seq) + + +def coord_check( + widths: tuple[int, ...] = (32, 128, 512), + *, + steps: int = 120, + base_lr: float = 3e-3, +) -> dict[str, Any]: + seed = 0 + keys = jrandom.split(jrandom.PRNGKey(seed), len(widths)) + mup_losses = [ + _run_once(key, width=width, use_mup=True, steps=steps, base_lr=base_lr) for key, width in zip(keys, widths) + ] + ctrl_losses = [ + _run_once(key, width=width, use_mup=False, steps=steps, base_lr=base_lr) for key, width in zip(keys, widths) + ] + + return { + "widths": list(widths), + "mup_losses": mup_losses, + "ctrl_losses": ctrl_losses, + "mup_span": _span(mup_losses), + "ctrl_span": _span(ctrl_losses), + } + + +def test_mup_coordinate_check_is_width_invariant(): + result = coord_check(widths=(32, 128, 512), steps=120, base_lr=3e-3) + mup_span = result["mup_span"] + ctrl_span = result["ctrl_span"] + + if ctrl_span < 1e-5: + assert mup_span <= ctrl_span + 1e-6, f"μP not at least as invariant: {result}" + else: + assert mup_span <= 0.6 * ctrl_span, f"μP did not improve width invariance enough.\n{result}" commit dcb38633019ddbbf4fbefa6aa0e3cd10e629590b Date: 2025-10-02T21:59:13-04:00 Make Mup Abstract diff --git a/src/haliax/nn/mup.py b/src/haliax/nn/mup.py index 5ee94ee..4385f76 100644 --- a/src/haliax/nn/mup.py +++ b/src/haliax/nn/mup.py @@ -3,6 +3,7 @@ # SPDX-License-Identifier: Apache-2.0 +from abc import ABC, abstractmethod import dataclasses import math import warnings @@ -28,16 +29,16 @@ from .embedding import Embedding from .linear import Linear -class MupMixin: - @staticmethod +class MupMixin(ABC): + @abstractmethod def mup_init_scale(In: AxisSpec, Out: AxisSpec): return 1 - @property + @abstractmethod def mup_lr_scale(self): return 1 - @property + @abstractmethod def mup_active_scale(self): return 1 @@ -65,9 +66,15 @@ class MupLinear(Linear, MupMixin): dot_general: Callable: The dot_general function to use. Defaults to jax.lax.dot_general. init_scale: float: The scale to use for initialization. We scale init by 1/sqrt(Input.size)*init_scale """ - joint_spec = hax.concat_axis_specs(Out, In) if out_first else hax.concat_axis_specs(In, Out) + joint_spec = ( + hax.concat_axis_specs(Out, In) + if out_first + else hax.concat_axis_specs(In, Out) + ) - weight = hax.random.truncated_normal(key, joint_spec, -3, 3) * (init_scale * cls.mup_init_scale(In, Out)) + weight = hax.random.truncated_normal(key, joint_spec, -3, 3) * ( + init_scale * cls.mup_init_scale(In, Out) + ) bias = hax.zeros(Out) if use_bias else None if dot_general is None: @@ -100,14 +107,27 @@ class MupLinear(Linear, MupMixin): scaled = dataclasses.replace(self, weight=self.weight * self.mup_active_scale) return default_eqx_module_to_state_dict(scaled, prefix) - def from_state_dict(self: Mod, state_dict: StateDict, prefix: Optional[str] = None) -> Mod: + def from_state_dict( + self: Mod, state_dict: StateDict, prefix: Optional[str] = None + ) -> Mod: unscaled = default_eqx_module_from_state_dict(self, state_dict, prefix) - return dataclasses.replace(unscaled, weight=unscaled.weight / self.mup_active_scale) + return dataclasses.replace( + unscaled, weight=unscaled.weight / self.mup_active_scale + ) -# Input Linear doesn't change ABC Parameters, but for clarity class InputLinear(MupLinear): - pass + @property + def mup_active_scale(self): + return 1 + + @property + def mup_lr_scale(self): + return 1 + + @staticmethod + def mup_init_scale(In: AxisSpec, Out: AxisSpec): + return 1 class OutputLinear(MupLinear): @@ -115,8 +135,20 @@ class OutputLinear(MupLinear): def mup_active_scale(self): return 1 / hax.axis_size(self.In) + @property + def mup_lr_scale(self): + return 1 + + @staticmethod + def mup_init_scale(In: AxisSpec, Out: AxisSpec): + return 1 + class HiddenLinear(MupLinear): + @property + def mup_active_scale(self): + return 1 + @property def mup_lr_scale(self): return 1 / hax.axis_size(self.In) @@ -129,10 +161,6 @@ class HiddenLinear(MupLinear): class MupEmbedding(Embedding, MupMixin): """Embedding module with muP-aware scaling for tied embeddings.""" - @staticmethod - def mup_init_scale(In: AxisSpec, Out: AxisSpec): - return 1 / hax.axis_size(Out) - @classmethod def init( cls, @@ -152,30 +180,29 @@ class MupEmbedding(Embedding, MupMixin): ) init_scale = initializer_range - weight = hax.random.truncated_normal(key, hax.concat_axis_specs(Vocab, Embed), -3, 3) * ( - init_scale * cls.mup_init_scale(Vocab, Embed) - ) + weight = hax.random.truncated_normal( + key, hax.concat_axis_specs(Vocab, Embed), -3, 3 + ) * (init_scale * cls.mup_init_scale(Vocab, Embed)) return cls(weight=weight, Vocab=Vocab, Embed=Embed) @property - def unembedding_mup_active_scale(self) -> float: - """Scale factor applied to logits when using the weights for unembedding.""" - - return 1 / hax.axis_size(self.Embed) + def mup_active_scale(self): + return 1 @property - def unembedding_weight(self): - """Effective weight matrix used on the unembedding path.""" + def mup_lr_scale(self): + return 1 - return self.weight * self.unembedding_mup_active_scale + @staticmethod + def mup_init_scale(In: AxisSpec, Out: AxisSpec): + return 1 / hax.axis_size(Out) + + @property + def unembedding_mup_active_scale(self) -> float: + """Scale factor applied to logits when using the weights for unembedding.""" + return 1 / hax.axis_size(self.Embed) def unembed(self, input_embeds): logits = super().unembed(input_embeds) return logits * self.unembedding_mup_active_scale - - def to_state_dict(self, prefix: Optional[str] = None) -> StateDict: - state_dict = default_eqx_module_to_state_dict(self, prefix) - unembed_key = with_prefix(prefix, "unembedding_weight") - state_dict.update(_tree_to_state_dict(self.unembedding_weight, unembed_key)) - return state_dict commit 34f9a99286cfcef1b7ca7c396487131f6260d374 Date: 2025-10-02T22:04:55-04:00 Abstractify diff --git a/src/haliax/nn/mup.py b/src/haliax/nn/mup.py index 4385f76..b465953 100644 --- a/src/haliax/nn/mup.py +++ b/src/haliax/nn/mup.py @@ -18,8 +18,6 @@ from .._src.state_dict import ( StateDict, default_eqx_module_from_state_dict, default_eqx_module_to_state_dict, - to_state_dict as _tree_to_state_dict, - with_prefix, ) from ..axis import Axis, AxisSpec from ..jax_utils import named_call @@ -29,21 +27,21 @@ from .embedding import Embedding from .linear import Linear -class MupMixin(ABC): +class AbstractMupMixin(ABC): @abstractmethod def mup_init_scale(In: AxisSpec, Out: AxisSpec): - return 1 + raise NotImplementedError @abstractmethod def mup_lr_scale(self): - return 1 + raise NotImplementedError @abstractmethod def mup_active_scale(self): - return 1 + raise NotImplementedError -class MupLinear(Linear, MupMixin): +class AbstractMupLinear(Linear, AbstractMupMixin): @classmethod def init( cls, @@ -55,7 +53,7 @@ class MupLinear(Linear, MupMixin): out_first: bool = True, dot_general: Optional[DotGeneralOp] = None, init_scale: float = 1.0, - ) -> "MupLinear": + ) -> "AbstractMupLinear": """ Args: In: AxisSpec: The input axis spec @@ -116,7 +114,7 @@ class MupLinear(Linear, MupMixin): ) -class InputLinear(MupLinear): +class InputLinear(AbstractMupLinear): @property def mup_active_scale(self): return 1 @@ -130,7 +128,7 @@ class InputLinear(MupLinear): return 1 -class OutputLinear(MupLinear): +class OutputLinear(AbstractMupLinear): @property def mup_active_scale(self): return 1 / hax.axis_size(self.In) @@ -144,7 +142,7 @@ class OutputLinear(MupLinear): return 1 -class HiddenLinear(MupLinear): +class HiddenLinear(AbstractMupLinear): @property def mup_active_scale(self): return 1 @@ -158,7 +156,7 @@ class HiddenLinear(MupLinear): return 1 / math.sqrt(hax.axis_size(In)) -class MupEmbedding(Embedding, MupMixin): +class MupEmbedding(Embedding, AbstractMupMixin): """Embedding module with muP-aware scaling for tied embeddings.""" @classmethod commit 28be5c3416a035451d423bab6624b1e6b5a15fcd Date: 2025-10-03T00:02:20-04:00 Config Based Approach diff --git a/src/haliax/nn/linear.py b/src/haliax/nn/linear.py index cde11f7..72f6895 100644 --- a/src/haliax/nn/linear.py +++ b/src/haliax/nn/linear.py @@ -17,16 +17,23 @@ from jaxtyping import PRNGKeyArray import haliax as hax -from .._src.state_dict import Mod, ModuleWithStateDictSerialization +from .._src.state_dict import ( + Mod, + ModuleWithStateDictSerialization, + StateDict, + default_eqx_module_from_state_dict, + default_eqx_module_to_state_dict, +) from ..axis import Axis, AxisSpec from ..core import NamedArray from ..jax_utils import named_call +from ..mup import AbstractReparam, ReparamEnabled, LinearStandardParam from ..partitioning import ResourceAxis from ..quantization import DotGeneralOp from ..util import ensure_tuple -class Linear(ModuleWithStateDictSerialization): +class Linear(ModuleWithStateDictSerialization, ReparamEnabled): """A named Linear layer. This module allows you to specify multiple named axes for both input and output, which is occasionally useful.""" @@ -36,10 +43,10 @@ class Linear(ModuleWithStateDictSerialization): In: AxisSpec = eqx.field(static=True) Out: AxisSpec = eqx.field(static=True) dot_general: DotGeneralOp = eqx.field(default_factory=DotGeneralOp.default) + reparam: AbstractReparam = eqx.field(static=True) - @classmethod + @staticmethod def init( - cls, In: AxisSpec, Out: AxisSpec, *, @@ -48,6 +55,7 @@ class Linear(ModuleWithStateDictSerialization): out_first: bool = True, dot_general: DotGeneralOp | None = None, init_scale: float = 1.0, + reparam: AbstractReparam = LinearStandardParam, ) -> "Linear": """ Args: @@ -60,14 +68,13 @@ class Linear(ModuleWithStateDictSerialization): init_scale: float: The scale to use for initialization. We scale init by 1/sqrt(Input.size)*init_scale """ joint_spec = hax.concat_axis_specs(Out, In) if out_first else hax.concat_axis_specs(In, Out) - input_size = hax.axis_size(In) - weight = hax.random.truncated_normal(key, joint_spec, -3, 3) * (init_scale / math.sqrt(input_size)) + weight = hax.random.truncated_normal(key, joint_spec, -3, 3) * (init_scale * reparam.init_scale(In, Out)) bias = hax.zeros(Out) if use_bias else None if dot_general is None: dot_general = DotGeneralOp.default() - return Linear(weight, bias, In, Out, dot_general=dot_general) + return Linear(weight, bias, In, Out, dot_general=dot_general, reparam=reparam) @named_call def __call__(self, inputs, *, key: PRNGKeyArray | None = None): @@ -138,6 +145,14 @@ class Linear(ModuleWithStateDictSerialization): else: return self.weight.axes[-len(self.Out) :] != self.Out + def to_state_dict(self, prefix: Optional[str] = None) -> StateDict: + scaled = dataclasses.replace(self, weight=self.weight * self.reparam.active_scale) + return default_eqx_module_to_state_dict(scaled, prefix) + + def from_state_dict(self: Mod, state_dict: StateDict, prefix: Optional[str] = None) -> Mod: + unscaled = default_eqx_module_from_state_dict(self, state_dict, prefix) + return dataclasses.replace(unscaled, weight=unscaled.weight / self.reparam.active_scale) + class MoELinear(eqx.Module): """A named Linear layer for MoE. This module allows you to specify multiple named axes for both input diff --git a/src/haliax/nn/mup.py b/src/haliax/nn/mup.py index b465953..f42994b 100644 --- a/src/haliax/nn/mup.py +++ b/src/haliax/nn/mup.py @@ -4,203 +4,97 @@ from abc import ABC, abstractmethod -import dataclasses import math -import warnings -from typing import Optional - -from jax.random import PRNGKey import haliax as hax +import equinox as eqx -from .._src.state_dict import ( - Mod, - StateDict, - default_eqx_module_from_state_dict, - default_eqx_module_to_state_dict, -) -from ..axis import Axis, AxisSpec -from ..jax_utils import named_call -from ..quantization import DotGeneralOp - -from .embedding import Embedding -from .linear import Linear +from ..axis import AxisSpec -class AbstractMupMixin(ABC): +class AbstractReparam(ABC): + @staticmethod @abstractmethod - def mup_init_scale(In: AxisSpec, Out: AxisSpec): + def init_scale(In: AxisSpec, Out: AxisSpec): raise NotImplementedError @abstractmethod - def mup_lr_scale(self): + def lr_scale(self): raise NotImplementedError @abstractmethod - def mup_active_scale(self): + def active_scale(self): raise NotImplementedError -class AbstractMupLinear(Linear, AbstractMupMixin): - @classmethod - def init( - cls, - In: AxisSpec, - Out: AxisSpec, - *, - key: PRNGKey, - use_bias: bool = True, - out_first: bool = True, - dot_general: Optional[DotGeneralOp] = None, - init_scale: float = 1.0, - ) -> "AbstractMupLinear": - """ - Args: - In: AxisSpec: The input axis spec - Out: AxisSpec: The output axis spec - key: PRNGKeyArray: The PRNG key to use for initialization - use_bias: bool: Whether to use a bias term - out_first: bool: Whether to put output axes first in the weight matrix. out_first is how PyTorch does it. - dot_general: Callable: The dot_general function to use. Defaults to jax.lax.dot_general. - init_scale: float: The scale to use for initialization. We scale init by 1/sqrt(Input.size)*init_scale - """ - joint_spec = ( - hax.concat_axis_specs(Out, In) - if out_first - else hax.concat_axis_specs(In, Out) - ) - - weight = hax.random.truncated_normal(key, joint_spec, -3, 3) * ( - init_scale * cls.mup_init_scale(In, Out) - ) - bias = hax.zeros(Out) if use_bias else None - - if dot_general is None: - dot_general = DotGeneralOp.default() - - return cls(weight, bias, In, Out, dot_general=dot_general) - - @named_call - def __call__(self, inputs, *, key: Optional[PRNGKey] = None): - """ - Args: - inputs (NamedArray): Input array - key: Not used, but there for compat with other modules - """ - del key - q = inputs.dot( - self.weight * self.mup_active_scale, - axis=self.In, - dot_general=self.dot_general, - ) - q = hax.auto_sharded(q) - - if self.bias is not None: - q = q + self.bias - q = hax.auto_sharded(q) - - return q - - def to_state_dict(self, prefix: Optional[str] = None) -> StateDict: - scaled = dataclasses.replace(self, weight=self.weight * self.mup_active_scale) - return default_eqx_module_to_state_dict(scaled, prefix) - - def from_state_dict( - self: Mod, state_dict: StateDict, prefix: Optional[str] = None - ) -> Mod: - unscaled = default_eqx_module_from_state_dict(self, state_dict, prefix) - return dataclasses.replace( - unscaled, weight=unscaled.weight / self.mup_active_scale - ) - - -class InputLinear(AbstractMupLinear): - @property - def mup_active_scale(self): - return 1 +class AbstractLinearMup(AbstractReparam): + In: AxisSpec + Out: AxisSpec - @property - def mup_lr_scale(self): - return 1 - @staticmethod - def mup_init_scale(In: AxisSpec, Out: AxisSpec): - return 1 +class DefaultLinearMup(AbstractLinearMup): + In: AxisSpec + Out: AxisSpec + @staticmethod + def init_scale(In: AxisSpec, Out: AxisSpec): + return 1 / hax.axis_size(In) -class OutputLinear(AbstractMupLinear): - @property - def mup_active_scale(self): - return 1 / hax.axis_size(self.In) + @abstractmethod + def active_scale(self): + return 1 - @property - def mup_lr_scale(self): + @abstractmethod + def lr_scale(self): return 1 + +class StandardLinear(AbstractLinearMup): @staticmethod - def mup_init_scale(In: AxisSpec, Out: AxisSpec): + def init_scale(In: AxisSpec, Out: AxisSpec): return 1 + @abstractmethod + def active_scale(self): + return 1 -class HiddenLinear(AbstractMupLinear): - @property - def mup_active_scale(self): + @abstractmethod + def lr_scale(self): return 1 - @property - def mup_lr_scale(self): - return 1 / hax.axis_size(self.In) +class HiddenLinearMup(AbstractLinearMup): @staticmethod - def mup_init_scale(In: AxisSpec, Out: AxisSpec): + def init_scale(In: AxisSpec, Out: AxisSpec): return 1 / math.sqrt(hax.axis_size(In)) + @abstractmethod + def active_scale(self): + return 1 + + @abstractmethod + def lr_scale(self): + return 1 / hax.axis_size(self.In) + -class MupEmbedding(Embedding, AbstractMupMixin): - """Embedding module with muP-aware scaling for tied embeddings.""" - - @classmethod - def init( - cls, - Vocab: Axis, - Embed: AxisSpec, - *, - init_scale: float = 1.0, - key: PRNGKey, - initializer_range: Optional[float] = None, - ) -> "MupEmbedding": - """Initializes the embedding weights following µP scaling rules.""" - - if initializer_range is not None: - warnings.warn( - "initializer_range is deprecated. Use init_scale instead.", - DeprecationWarning, - ) - init_scale = initializer_range - - weight = hax.random.truncated_normal( - key, hax.concat_axis_specs(Vocab, Embed), -3, 3 - ) * (init_scale * cls.mup_init_scale(Vocab, Embed)) - - return cls(weight=weight, Vocab=Vocab, Embed=Embed) - - @property - def mup_active_scale(self): +class OutputLinearMup(AbstractLinearMup): + @staticmethod + def init_scale(In: AxisSpec, Out: AxisSpec): return 1 - @property - def mup_lr_scale(self): + @abstractmethod + def active_scale(self): + return 1 / hax.axis_size(self.In) + + @abstractmethod + def lr_scale(self): return 1 - @staticmethod - def mup_init_scale(In: AxisSpec, Out: AxisSpec): - return 1 / hax.axis_size(Out) - @property - def unembedding_mup_active_scale(self) -> float: - """Scale factor applied to logits when using the weights for unembedding.""" - return 1 / hax.axis_size(self.Embed) +class AbstractEmbeddingReparam(AbstractReparam): + Embed: AxisSpec + Vocab: AxisSpec + - def unembed(self, input_embeds): - logits = super().unembed(input_embeds) - return logits * self.unembedding_mup_active_scale +class ReparamEnabled(ABC): + mup_config: eqx.AbstractVar[AbstractReparam] diff --git a/tests/test_mup_linear.py b/tests/test_mup_linear.py index 63b42b7..3e3b459 100644 --- a/tests/test_mup_linear.py +++ b/tests/test_mup_linear.py @@ -11,7 +11,6 @@ import pytest import haliax as hax from haliax.nn import Linear -from haliax.nn.mup import HiddenLinear, InputLinear, MupLinear, OutputLinear @pytest.mark.parametrize("out_first", [True, False]) commit 840bf6eae1ce6e30d9abac0e73254cb488be4129 Date: 2025-10-03T01:06:11-04:00 Composable MuP diff --git a/src/haliax/nn/linear.py b/src/haliax/nn/linear.py index 72f6895..7f3f084 100644 --- a/src/haliax/nn/linear.py +++ b/src/haliax/nn/linear.py @@ -17,6 +17,8 @@ from jaxtyping import PRNGKeyArray import haliax as hax + +from .mup import AbstractLinearReparam, ReparamEnabled, LinearStandardParam from .._src.state_dict import ( Mod, ModuleWithStateDictSerialization, @@ -27,7 +29,6 @@ from .._src.state_dict import ( from ..axis import Axis, AxisSpec from ..core import NamedArray from ..jax_utils import named_call -from ..mup import AbstractReparam, ReparamEnabled, LinearStandardParam from ..partitioning import ResourceAxis from ..quantization import DotGeneralOp from ..util import ensure_tuple @@ -42,8 +43,8 @@ class Linear(ModuleWithStateDictSerialization, ReparamEnabled): In: AxisSpec = eqx.field(static=True) Out: AxisSpec = eqx.field(static=True) + reparam: AbstractLinearReparam = eqx.field(static=True) dot_general: DotGeneralOp = eqx.field(default_factory=DotGeneralOp.default) - reparam: AbstractReparam = eqx.field(static=True) @staticmethod def init( @@ -55,7 +56,7 @@ class Linear(ModuleWithStateDictSerialization, ReparamEnabled): out_first: bool = True, dot_general: DotGeneralOp | None = None, init_scale: float = 1.0, - reparam: AbstractReparam = LinearStandardParam, + reparam_cls: type[AbstractLinearReparam] = LinearStandardParam, ) -> "Linear": """ Args: @@ -68,13 +69,13 @@ class Linear(ModuleWithStateDictSerialization, ReparamEnabled): init_scale: float: The scale to use for initialization. We scale init by 1/sqrt(Input.size)*init_scale """ joint_spec = hax.concat_axis_specs(Out, In) if out_first else hax.concat_axis_specs(In, Out) - weight = hax.random.truncated_normal(key, joint_spec, -3, 3) * (init_scale * reparam.init_scale(In, Out)) + weight = hax.random.truncated_normal(key, joint_spec, -3, 3) * (init_scale * reparam_cls.init_scale(In, Out)) bias = hax.zeros(Out) if use_bias else None if dot_general is None: dot_general = DotGeneralOp.default() - return Linear(weight, bias, In, Out, dot_general=dot_general, reparam=reparam) + return Linear(weight, bias, In, Out, dot_general=dot_general, reparam=reparam_cls(In, Out)) @named_call def __call__(self, inputs, *, key: PRNGKeyArray | None = None): @@ -84,7 +85,11 @@ class Linear(ModuleWithStateDictSerialization, ReparamEnabled): key: Not used, but there for compat with other modules """ del key - q = inputs.dot(self.weight, axis=self.In, dot_general=self.dot_general) + q = inputs.dot( + self.weight * self.reparam.active_scale, + axis=self.In, + dot_general=self.dot_general, + ) q = hax.auto_sharded(q) if self.bias is not None: diff --git a/src/haliax/nn/mup.py b/src/haliax/nn/mup.py index f42994b..b46ebe9 100644 --- a/src/haliax/nn/mup.py +++ b/src/haliax/nn/mup.py @@ -3,8 +3,9 @@ # SPDX-License-Identifier: Apache-2.0 -from abc import ABC, abstractmethod import math +from abc import ABC, abstractmethod +from dataclasses import dataclass import haliax as hax import equinox as eqx @@ -18,83 +19,84 @@ class AbstractReparam(ABC): def init_scale(In: AxisSpec, Out: AxisSpec): raise NotImplementedError + @property @abstractmethod def lr_scale(self): raise NotImplementedError + @property @abstractmethod def active_scale(self): raise NotImplementedError -class AbstractLinearMup(AbstractReparam): +@dataclass +class AbstractLinearReparam(AbstractReparam): In: AxisSpec Out: AxisSpec -class DefaultLinearMup(AbstractLinearMup): - In: AxisSpec - Out: AxisSpec - +class LinearStandardParam(AbstractLinearReparam): @staticmethod def init_scale(In: AxisSpec, Out: AxisSpec): - return 1 / hax.axis_size(In) + return 1 / math.sqrt(hax.axis_size(In)) - @abstractmethod + @property def active_scale(self): return 1 - @abstractmethod + @property def lr_scale(self): return 1 -class StandardLinear(AbstractLinearMup): +class InputLinearMup(AbstractLinearReparam): @staticmethod def init_scale(In: AxisSpec, Out: AxisSpec): return 1 - @abstractmethod + @property def active_scale(self): return 1 - @abstractmethod + @property def lr_scale(self): return 1 -class HiddenLinearMup(AbstractLinearMup): +class HiddenLinearMup(AbstractLinearReparam): @staticmethod def init_scale(In: AxisSpec, Out: AxisSpec): return 1 / math.sqrt(hax.axis_size(In)) - @abstractmethod + @property def active_scale(self): return 1 - @abstractmethod + @property def lr_scale(self): return 1 / hax.axis_size(self.In) -class OutputLinearMup(AbstractLinearMup): +class OutputLinearMup(AbstractLinearReparam): @staticmethod def init_scale(In: AxisSpec, Out: AxisSpec): return 1 - @abstractmethod + @property def active_scale(self): return 1 / hax.axis_size(self.In) - @abstractmethod + @property def lr_scale(self): return 1 +@dataclass class AbstractEmbeddingReparam(AbstractReparam): Embed: AxisSpec Vocab: AxisSpec class ReparamEnabled(ABC): - mup_config: eqx.AbstractVar[AbstractReparam] + reparam: eqx.AbstractVar[AbstractReparam] diff --git a/tests/test_mup_coordinate_check.py b/tests/test_mup_coordinate_check.py index 25e1f51..41d3994 100644 --- a/tests/test_mup_coordinate_check.py +++ b/tests/test_mup_coordinate_check.py @@ -16,7 +16,7 @@ import jax.random as jrandom import haliax as hax from haliax import Axis, NamedArray from haliax.nn import Linear, activations -from haliax.nn.mup import HiddenLinear, InputLinear, OutputLinear +from haliax.nn.mup import InputLinearMup, HiddenLinearMup, OutputLinearMup class TinyMLP(eqx.Module): @@ -36,9 +36,9 @@ class TinyMLP(eqx.Module): k1, k2, k3 = jrandom.split(key, 3) if use_mup: - first = InputLinear.init((in_axis,), hidden, key=k1) - second = HiddenLinear.init(hidden, hidden2, key=k2) - third = OutputLinear.init(hidden2, (out_axis,), key=k3) + first = Linear.init((in_axis,), hidden, key=k1, reparam_cls=InputLinearMup) + second = Linear.init(hidden, hidden2, key=k2, reparam_cls=HiddenLinearMup) + third = Linear.init(hidden2, (out_axis,), key=k3, reparam_cls=OutputLinearMup) else: first = Linear.init((in_axis,), hidden, key=k1) second = Linear.init(hidden, hidden2, key=k2) @@ -64,7 +64,7 @@ _loss_value = jax.jit(_loss_fn) def _apply_sgd(module: TinyMLP, grads: TinyMLP, *, base_lr: float, use_mup: bool) -> TinyMLP: def update_linear(layer: Linear, grad_layer: Linear) -> Linear: - lr_scale = getattr(layer, "mup_lr_scale", 1.0) if use_mup else 1.0 + lr_scale = layer.reparam.lr_scale new_weight = layer.weight - (base_lr * lr_scale) * grad_layer.weight if layer.bias is None or grad_layer.bias is None: new_bias = layer.bias diff --git a/tests/test_mup_linear.py b/tests/test_mup_linear.py index 3e3b459..db8ffea 100644 --- a/tests/test_mup_linear.py +++ b/tests/test_mup_linear.py @@ -11,6 +11,7 @@ import pytest import haliax as hax from haliax.nn import Linear +from haliax.nn.mup import InputLinearMup, HiddenLinearMup, OutputLinearMup @pytest.mark.parametrize("out_first", [True, False]) @@ -20,7 +21,7 @@ def test_mup_linear_init_matches_linear_axes(out_first: bool): key_linear, key_mup = jrandom.split(jrandom.PRNGKey(0)) linear = Linear.init(In, Out, key=key_linear, out_first=out_first) - mup = MupLinear.init(In, Out, key=key_mup, out_first=out_first) + mup = Linear.init(In, Out, key=key_mup, out_first=out_first, reparam_cls=InputLinearMup) assert linear.weight.axes == mup.weight.axes if linear.bias is not None: @@ -28,13 +29,6 @@ def test_mup_linear_init_matches_linear_axes(out_first: bool): assert linear.bias.axes == mup.bias.axes -def test_mup_linear_respects_bias_flag(): - In = hax.Axis("I", 4) - Out = hax.Axis("O", 3) - layer = MupLinear.init(In, Out, key=jrandom.PRNGKey(1), use_bias=False) - assert layer.bias is None - - def test_mup_linear_call_matches_linear(): Batch = hax.Axis("B", 2) In = (hax.Axis("I", 3),) @@ -44,7 +38,7 @@ def test_mup_linear_call_matches_linear(): bias = hax.full(Out, 0.25) linear = Linear(weight, bias, In, Out) - mup = MupLinear(weight, bias, In, Out) + mup = Linear(weight, bias, In, Out, reparam_cls=InputLinearMup) inputs = hax.full(hax.concat_axis_specs(Batch, In), 2.0) @@ -62,7 +56,14 @@ def test_hidden_linear_init_matches_linear_scaling(out_first: bool): key = jrandom.PRNGKey(0) linear = Linear.init(In, Out, key=key, use_bias=False, out_first=out_first) - hidden = HiddenLinear.init(In, Out, key=key, use_bias=False, out_first=out_first) + hidden = Linear.init( + In, + Out, + key=key, + use_bias=False, + out_first=out_first, + reparam_cls=HiddenLinearMup, + ) assert jnp.allclose(hidden.weight.array, linear.weight.array) @@ -72,7 +73,7 @@ def test_output_linear_scales_activation_by_input_size(): In = hax.Axis("I", 3) Out = hax.Axis("O", 2) - layer = OutputLinear.init(In, Out, key=jrandom.PRNGKey(2), use_bias=False) + layer = Linear.init(In, Out, key=jrandom.PRNGKey(2), use_bias=False, reparam_cls=OutputLinearMup) layer = dataclasses.replace(layer, weight=hax.ones(layer.weight.axes)) inputs = hax.full((Batch, In), 2.0) @@ -88,13 +89,13 @@ def test_output_linear_state_dict_scales_weight(): In = hax.Axis("I", 4) Out = hax.Axis("O", 3) - layer = OutputLinear.init(In, Out, key=jrandom.PRNGKey(3), use_bias=False) + layer = Linear.init(In, Out, key=jrandom.PRNGKey(3), use_bias=False, reparam_cls=OutputLinearMup) layer = dataclasses.replace(layer, weight=hax.ones(layer.weight.axes)) state = layer.to_state_dict() assert jnp.allclose(state["weight"], layer.weight.array * layer.mup_active_scale) - template = OutputLinear.init(In, Out, key=jrandom.PRNGKey(4), use_bias=False) + template = Linear.init(In, Out, key=jrandom.PRNGKey(4), use_bias=False, reparam_cls=OutputLinearMup) restored = template.from_state_dict(state) assert jnp.allclose(restored.weight.array, layer.weight.array) @@ -109,7 +110,7 @@ def test_input_linear_behaves_like_base_linear(): bias = hax.zeros(Out) linear = Linear(weight, bias, In, Out) - input_linear = InputLinear(weight, bias, In, Out) + input_linear = Linear(weight, bias, In, Out, reparam_cls=InputLinearMup) inputs = hax.random.normal(jrandom.PRNGKey(5), (Batch, In)) commit 7c4800b28e131be97736a077ff836be5121a5310 Date: 2025-10-03T01:29:25-04:00 Many Fixes diff --git a/src/haliax/nn/embedding.py b/src/haliax/nn/embedding.py index 3f4d899..086531a 100644 --- a/src/haliax/nn/embedding.py +++ b/src/haliax/nn/embedding.py @@ -11,21 +11,31 @@ from jaxtyping import PRNGKeyArray import haliax as hax +from .mup import AbstractEmbeddingReparam, ReparamEnabled, EmbeddingStandardParam from ..axis import Axis, AxisSpec, concat_axes from ..core import NamedArray from ..jax_utils import named_call from ..tree_util import resize_axis -class Embedding(eqx.Module): +class Embedding(eqx.Module, ReparamEnabled): weight: NamedArray # axes Vocab: Axis = eqx.field(static=True) Embed: AxisSpec = eqx.field(static=True) + reparam: AbstractEmbeddingReparam = eqx.field(static=True) @staticmethod - def init(Vocab: Axis, Embed: AxisSpec, *, init_scale: float = 1, key, initializer_range: float | None = None): + def init( + Vocab: Axis, + Embed: AxisSpec, + *, + init_scale: float = 1, + key, + initializer_range: float | None = None, + reparam_cls: type[AbstractEmbeddingReparam] = EmbeddingStandardParam, + ): """ Initialize an Embedding module. @@ -41,13 +51,17 @@ class Embedding(eqx.Module): initializer_range: Deprecated. Use init_scale instead. """ if initializer_range is not None: - warnings.warn("initializer_range is deprecated. Use init_std instead.", DeprecationWarning) + warnings.warn( + "initializer_range is deprecated. Use init_std instead.", + DeprecationWarning, + ) init_scale = initializer_range all_axes = concat_axes(Vocab, Embed) - output_size = hax.axis_size(Embed) - weight = hax.random.truncated_normal(key, all_axes, -3, 3) * (init_scale / output_size) - return Embedding(weight=weight, Vocab=Vocab, Embed=Embed) + weight = hax.random.truncated_normal(key, all_axes, -3, 3) * ( + init_scale * reparam_cls.init_scale(Vocab, Embed) + ) + return Embedding(weight=weight, Vocab=Vocab, Embed=Embed, reparam=reparam_cls(Vocab, Embed)) def __call__(self, input_ids: NamedArray, *, key: PRNGKeyArray | None = None): """Alias for `embed`. key is ignored.""" @@ -60,7 +74,7 @@ class Embedding(eqx.Module): input_ids: token IDs with shape > {Vocab} """ input_embeds = self.weight.take(self.Vocab, input_ids) - return input_embeds + return input_embeds * self.reparam.active_scale def unembed(self, input_embeds: NamedArray): """ @@ -68,7 +82,7 @@ class Embedding(eqx.Module): Equivalent to `input_embeds.dot(self.weight, axis=self.Embed)`. """ - return input_embeds.dot(self.weight, axis=self.Embed) + return input_embeds.dot(self.weight, axis=self.Embed) * self.reparam.unembed_active_scale def resize_embeddings(self, new_size: int, key: PRNGKeyArray | None = None): """ diff --git a/src/haliax/nn/linear.py b/src/haliax/nn/linear.py index 7f3f084..553d4fb 100644 --- a/src/haliax/nn/linear.py +++ b/src/haliax/nn/linear.py @@ -6,6 +6,7 @@ import dataclasses import math from functools import partial +from typing import Optional import equinox as eqx import jax diff --git a/src/haliax/nn/mup.py b/src/haliax/nn/mup.py index b46ebe9..48ac268 100644 --- a/src/haliax/nn/mup.py +++ b/src/haliax/nn/mup.py @@ -97,6 +97,47 @@ class AbstractEmbeddingReparam(AbstractReparam): Embed: AxisSpec Vocab: AxisSpec + @property + @abstractmethod + def unembed_active_scale(self): + raise NotImplementedError + + +class EmbeddingStandardParam(AbstractEmbeddingReparam): + @staticmethod + def init_scale(In: AxisSpec, Out: AxisSpec): + return 1 / hax.axis_size(Out) + + @property + def active_scale(self): + return 1 + + @property + def lr_scale(self): + return 1 + + @property + def unembed_active_scale(self): + return 1 / hax.axis_size(self.Embed) + + +class EmbeddingMup(AbstractEmbeddingReparam): + @staticmethod + def init_scale(In: AxisSpec, Out: AxisSpec): + return 1 + + @property + def active_scale(self): + return 1 + + @property + def lr_scale(self): + return 1 + + @property + def unembed_active_scale(self): + return 1 / hax.axis_size(self.Embed) + class ReparamEnabled(ABC): reparam: eqx.AbstractVar[AbstractReparam] diff --git a/tests/test_mup_embedding.py b/tests/test_mup_embedding.py index ab8335c..ccc2e72 100644 --- a/tests/test_mup_embedding.py +++ b/tests/test_mup_embedding.py @@ -8,8 +8,7 @@ import pytest import haliax as hax from haliax.nn import Embedding -from haliax.nn.mup import MupEmbedding -from haliax.state_dict import from_state_dict +from haliax.nn.mup import EmbeddingMup @pytest.mark.parametrize("init_scale", [0.5, 1.0]) @@ -20,7 +19,7 @@ def test_mup_embedding_init_matches_embedding(init_scale: float): key = jrandom.PRNGKey(0) baseline = Embedding.init(Vocab, Embed, key=key, init_scale=init_scale) - mup = MupEmbedding.init(Vocab, Embed, key=key, init_scale=init_scale) + mup = Embedding.init(Vocab, Embed, key=key, init_scale=init_scale, reparam_cls=EmbeddingMup) assert mup.weight.axes == baseline.weight.axes assert jnp.allclose(mup.weight.array, baseline.weight.array) @@ -31,10 +30,13 @@ def test_mup_embedding_unembedding_scale(): Embed = (hax.Axis("E", 3),) weight = hax.ones(hax.concat_axis_specs(Vocab, Embed)) - layer = MupEmbedding(weight=weight, Vocab=Vocab, Embed=Embed) + layer = Embedding(weight=weight, Vocab=Vocab, Embed=Embed, reparam=EmbeddingMup(Embed, Vocab)) assert layer.unembedding_mup_active_scale == pytest.approx(1.0 / Embed[0].size) - assert jnp.allclose(layer.unembedding_weight.array, weight.array * layer.unembedding_mup_active_scale) + assert jnp.allclose( + layer.unembedding_weight.array, + weight.array * layer.unembedding_mup_active_scale, + ) Batch = hax.Axis("B", 2) inputs = hax.ones((Batch, *Embed)) @@ -44,28 +46,3 @@ def test_mup_embedding_unembedding_scale(): assert logits.axes == expected.axes assert jnp.allclose(logits.array, expected.array) - - -def test_mup_embedding_state_dict_adds_unembedding_weight(): - Vocab = hax.Axis("V", 5) - Embed = (hax.Axis("E", 2),) - - weight = hax.random.normal(jrandom.PRNGKey(1), hax.concat_axis_specs(Vocab, Embed)) - layer = MupEmbedding(weight=weight, Vocab=Vocab, Embed=Embed) - - state = layer.to_state_dict() - assert "unembedding_weight" in state - assert jnp.allclose(state["unembedding_weight"], layer.unembedding_weight.array) - - template = MupEmbedding.init(Vocab, Embed, key=jrandom.PRNGKey(2)) - restored = from_state_dict(template, state) - - assert jnp.allclose(restored.weight.array, layer.weight.array) - - -def test_mup_embedding_initializer_range_warns(): - Vocab = hax.Axis("V", 3) - Embed = (hax.Axis("E", 2),) - - with pytest.warns(DeprecationWarning): - MupEmbedding.init(Vocab, Embed, key=jrandom.PRNGKey(3), initializer_range=0.5) commit 63187ff28503c7bbf1aa9f5b6e9721914d91a5bf Date: 2025-10-03T01:38:19-04:00 Wrong Order diff --git a/src/haliax/nn/embedding.py b/src/haliax/nn/embedding.py index 086531a..384823c 100644 --- a/src/haliax/nn/embedding.py +++ b/src/haliax/nn/embedding.py @@ -61,7 +61,7 @@ class Embedding(eqx.Module, ReparamEnabled): weight = hax.random.truncated_normal(key, all_axes, -3, 3) * ( init_scale * reparam_cls.init_scale(Vocab, Embed) ) - return Embedding(weight=weight, Vocab=Vocab, Embed=Embed, reparam=reparam_cls(Vocab, Embed)) + return Embedding(weight=weight, Vocab=Vocab, Embed=Embed, reparam=reparam_cls(Embed, Vocab)) def __call__(self, input_ids: NamedArray, *, key: PRNGKeyArray | None = None): """Alias for `embed`. key is ignored.""" commit da6c1145e11b50d14575ca31a1037b60f07668ae Date: 2025-10-03T01:52:23-04:00 Mup diff --git a/tests/test_mup_embedding.py b/tests/test_mup_embedding.py index ccc2e72..a0ccc17 100644 --- a/tests/test_mup_embedding.py +++ b/tests/test_mup_embedding.py @@ -22,7 +22,8 @@ def test_mup_embedding_init_matches_embedding(init_scale: float): mup = Embedding.init(Vocab, Embed, key=key, init_scale=init_scale, reparam_cls=EmbeddingMup) assert mup.weight.axes == baseline.weight.axes - assert jnp.allclose(mup.weight.array, baseline.weight.array) + scale_factor = hax.axis_size(Embed) + assert jnp.allclose(mup.weight.array, baseline.weight.array * scale_factor) def test_mup_embedding_unembedding_scale(): @@ -32,11 +33,10 @@ def test_mup_embedding_unembedding_scale(): weight = hax.ones(hax.concat_axis_specs(Vocab, Embed)) layer = Embedding(weight=weight, Vocab=Vocab, Embed=Embed, reparam=EmbeddingMup(Embed, Vocab)) - assert layer.unembedding_mup_active_scale == pytest.approx(1.0 / Embed[0].size) - assert jnp.allclose( - layer.unembedding_weight.array, - weight.array * layer.unembedding_mup_active_scale, - ) + scale = layer.reparam.unembed_active_scale + assert scale == pytest.approx(1.0 / hax.axis_size(Embed)) + assert layer.reparam.active_scale == pytest.approx(1.0) + assert jnp.allclose((layer.weight * scale).array, weight.array * scale) Batch = hax.Axis("B", 2) inputs = hax.ones((Batch, *Embed)) diff --git a/tests/test_mup_linear.py b/tests/test_mup_linear.py index db8ffea..4739be2 100644 --- a/tests/test_mup_linear.py +++ b/tests/test_mup_linear.py @@ -11,7 +11,7 @@ import pytest import haliax as hax from haliax.nn import Linear -from haliax.nn.mup import InputLinearMup, HiddenLinearMup, OutputLinearMup +from haliax.nn.mup import InputLinearMup, LinearStandardParam, HiddenLinearMup, OutputLinearMup @pytest.mark.parametrize("out_first", [True, False]) @@ -37,8 +37,8 @@ def test_mup_linear_call_matches_linear(): weight = hax.ones(hax.concat_axis_specs(Out, In)) * 0.5 bias = hax.full(Out, 0.25) - linear = Linear(weight, bias, In, Out) - mup = Linear(weight, bias, In, Out, reparam_cls=InputLinearMup) + linear = Linear(weight, bias, In, Out, reparam=LinearStandardParam(In, Out)) + mup = Linear(weight, bias, In, Out, reparam=InputLinearMup(In, Out)) inputs = hax.full(hax.concat_axis_specs(Batch, In), 2.0) @@ -93,7 +93,7 @@ def test_output_linear_state_dict_scales_weight(): layer = dataclasses.replace(layer, weight=hax.ones(layer.weight.axes)) state = layer.to_state_dict() - assert jnp.allclose(state["weight"], layer.weight.array * layer.mup_active_scale) + assert jnp.allclose(state["weight"], layer.weight.array * layer.reparam.active_scale) template = Linear.init(In, Out, key=jrandom.PRNGKey(4), use_bias=False, reparam_cls=OutputLinearMup) restored = template.from_state_dict(state) @@ -109,8 +109,8 @@ def test_input_linear_behaves_like_base_linear(): weight = hax.ones((Out, In)) * 0.1 bias = hax.zeros(Out) - linear = Linear(weight, bias, In, Out) - input_linear = Linear(weight, bias, In, Out, reparam_cls=InputLinearMup) + linear = Linear(weight, bias, In, Out, reparam=LinearStandardParam(In, Out)) + input_linear = Linear(weight, bias, In, Out, reparam=InputLinearMup(In, Out)) inputs = hax.random.normal(jrandom.PRNGKey(5), (Batch, In)) commit 774168dc448d03835df38b870634d494801b5cd9 Date: 2025-10-06T17:30:11-04:00 DocString diff --git a/src/haliax/nn/mup.py b/src/haliax/nn/mup.py index 48ac268..8048529 100644 --- a/src/haliax/nn/mup.py +++ b/src/haliax/nn/mup.py @@ -2,7 +2,6 @@ # # SPDX-License-Identifier: Apache-2.0 - import math from abc import ABC, abstractmethod from dataclasses import dataclass @@ -14,29 +13,53 @@ from ..axis import AxisSpec class AbstractReparam(ABC): + """Abstract base class for abc-parameterization rules. + + Defines the interface for active scaling of parameters (a), + computing initialization scales (b), and learning rate scaling (c) + + See: https://arxiv.org/abs/2011.14522 + """ + @staticmethod @abstractmethod def init_scale(In: AxisSpec, Out: AxisSpec): + """Return the scaling factor for initializing weights + given input and output axes.""" raise NotImplementedError @property @abstractmethod def lr_scale(self): + """Return the learning-rate scaling factor.""" raise NotImplementedError @property @abstractmethod def active_scale(self): + """Return the scaling applied to activations.""" raise NotImplementedError @dataclass class AbstractLinearReparam(AbstractReparam): + """Base class for linear-layer reparameterizations. + + Stores input and output axis specifications, and inherits + the reparameterization interface. + """ + In: AxisSpec Out: AxisSpec class LinearStandardParam(AbstractLinearReparam): + """Standard (non-muP) parameterization for linear layers. + + Uses the usual fan-in scaling for initialization and + leaves learning rate and activation scaling unchanged. + """ + @staticmethod def init_scale(In: AxisSpec, Out: AxisSpec): return 1 / math.sqrt(hax.axis_size(In)) @@ -51,6 +74,12 @@ class LinearStandardParam(AbstractLinearReparam): class InputLinearMup(AbstractLinearReparam): + """muP-style parameterization for input linear layers. + + Uses no scaling on initialization or learning rate. + See: https://arxiv.org/abs/2011.14522 (Maximal Update Parametrization) + """ + @staticmethod def init_scale(In: AxisSpec, Out: AxisSpec): return 1 @@ -65,6 +94,12 @@ class InputLinearMup(AbstractLinearReparam): class HiddenLinearMup(AbstractLinearReparam): + """muP-style parameterization for hidden linear layers. + + Applies fan-in scaling at initialization and scales + learning rate inversely with layer width. + """ + @staticmethod def init_scale(In: AxisSpec, Out: AxisSpec): return 1 / math.sqrt(hax.axis_size(In)) @@ -79,6 +114,12 @@ class HiddenLinearMup(AbstractLinearReparam): class OutputLinearMup(AbstractLinearReparam): + """muP-style parameterization for output linear layers. + + Uses unit initialization and applies inverse-width + scaling to the output activations. + """ + @staticmethod def init_scale(In: AxisSpec, Out: AxisSpec): return 1 @@ -94,16 +135,25 @@ class OutputLinearMup(AbstractLinearReparam): @dataclass class AbstractEmbeddingReparam(AbstractReparam): + """Base class for embedding-layer reparameterizations. + + Defines the interface for both embedding and unembedding + scaling rules. + """ + Embed: AxisSpec Vocab: AxisSpec @property @abstractmethod def unembed_active_scale(self): + """Scaling factor applied when unembedding embeddings.""" raise NotImplementedError class EmbeddingStandardParam(AbstractEmbeddingReparam): + """Standard embedding parameterization.""" + @staticmethod def init_scale(In: AxisSpec, Out: AxisSpec): return 1 / hax.axis_size(Out) @@ -122,6 +172,13 @@ class EmbeddingStandardParam(AbstractEmbeddingReparam): class EmbeddingMup(AbstractEmbeddingReparam): + """muP-style parameterization for embeddings. + + Keeps initialization and learning-rate scaling neutral, + but applies inverse-width scaling to unembedding outputs for tied weights. + See: https://www.cerebras.ai/blog/the-practitioners-guide-to-the-maximal-update-parameterization + """ + @staticmethod def init_scale(In: AxisSpec, Out: AxisSpec): return 1 @@ -140,4 +197,10 @@ class EmbeddingMup(AbstractEmbeddingReparam): class ReparamEnabled(ABC): + """Mixin for modules that support reparameterization. + + Stores an abstract `reparam` attribute that specifies + how initialization and scaling are handled. + """ + reparam: eqx.AbstractVar[AbstractReparam] commit eee5987484c9b2ec5b1d474508095e0763e641a8 Date: 2025-10-06T17:45:33-04:00 Utilities diff --git a/src/haliax/nn/linear.py b/src/haliax/nn/linear.py index 553d4fb..747ac1b 100644 --- a/src/haliax/nn/linear.py +++ b/src/haliax/nn/linear.py @@ -19,6 +19,7 @@ from jaxtyping import PRNGKeyArray import haliax as hax +from . import mup from .mup import AbstractLinearReparam, ReparamEnabled, LinearStandardParam from .._src.state_dict import ( Mod, @@ -315,3 +316,21 @@ def gmm_sharded(lhs_: jnp.ndarray, rhs_: jnp.ndarray, group_sizes_: jnp.ndarray, out = out[: hs_shape[0]] return out + + +def input(use_mup: bool = True) -> type[AbstractLinearReparam]: + """Return the reparameterization class for an input linear layer.""" + + return mup.InputLinearMup if use_mup else mup.LinearStandardParam + + +def hidden(use_mup: bool = True) -> type[AbstractLinearReparam]: + """Return the reparameterization class for a hidden linear layer.""" + + return mup.HiddenLinearMup if use_mup else mup.LinearStandardParam + + +def output(use_mup: bool = True) -> type[AbstractLinearReparam]: + """Return the reparameterization class for an output linear layer.""" + + return mup.OutputLinearMup if use_mup else mup.LinearStandardParam commit 6cf13b832d6f5b55426bf75f4017f2f02ca0d1a2 Date: 2025-10-06T18:47:17-04:00 Naming diff --git a/src/haliax/nn/linear.py b/src/haliax/nn/linear.py index 747ac1b..38865c2 100644 --- a/src/haliax/nn/linear.py +++ b/src/haliax/nn/linear.py @@ -318,19 +318,19 @@ def gmm_sharded(lhs_: jnp.ndarray, rhs_: jnp.ndarray, group_sizes_: jnp.ndarray, return out -def input(use_mup: bool = True) -> type[AbstractLinearReparam]: +def input_reparam(use_mup: bool = True) -> type[AbstractLinearReparam]: """Return the reparameterization class for an input linear layer.""" return mup.InputLinearMup if use_mup else mup.LinearStandardParam -def hidden(use_mup: bool = True) -> type[AbstractLinearReparam]: +def hidden_reparam(use_mup: bool = True) -> type[AbstractLinearReparam]: """Return the reparameterization class for a hidden linear layer.""" return mup.HiddenLinearMup if use_mup else mup.LinearStandardParam -def output(use_mup: bool = True) -> type[AbstractLinearReparam]: +def output_reparam(use_mup: bool = True) -> type[AbstractLinearReparam]: """Return the reparameterization class for an output linear layer.""" return mup.OutputLinearMup if use_mup else mup.LinearStandardParam commit 58c8de0524f65dbb29ad67c1d0a7d75db73b07ab Date: 2025-10-06T18:50:32-04:00 Static class fns diff --git a/src/haliax/nn/linear.py b/src/haliax/nn/linear.py index 38865c2..58b7d59 100644 --- a/src/haliax/nn/linear.py +++ b/src/haliax/nn/linear.py @@ -160,6 +160,24 @@ class Linear(ModuleWithStateDictSerialization, ReparamEnabled): unscaled = default_eqx_module_from_state_dict(self, state_dict, prefix) return dataclasses.replace(unscaled, weight=unscaled.weight / self.reparam.active_scale) + @staticmethod + def input_reparam(use_mup: bool = True) -> type[AbstractLinearReparam]: + """Return the reparameterization class for an input linear layer.""" + + return mup.InputLinearMup if use_mup else mup.LinearStandardParam + + @staticmethod + def hidden_reparam(use_mup: bool = True) -> type[AbstractLinearReparam]: + """Return the reparameterization class for a hidden linear layer.""" + + return mup.HiddenLinearMup if use_mup else mup.LinearStandardParam + + @staticmethod + def output_reparam(use_mup: bool = True) -> type[AbstractLinearReparam]: + """Return the reparameterization class for an output linear layer.""" + + return mup.OutputLinearMup if use_mup else mup.LinearStandardParam + class MoELinear(eqx.Module): """A named Linear layer for MoE. This module allows you to specify multiple named axes for both input @@ -316,21 +334,3 @@ def gmm_sharded(lhs_: jnp.ndarray, rhs_: jnp.ndarray, group_sizes_: jnp.ndarray, out = out[: hs_shape[0]] return out - - -def input_reparam(use_mup: bool = True) -> type[AbstractLinearReparam]: - """Return the reparameterization class for an input linear layer.""" - - return mup.InputLinearMup if use_mup else mup.LinearStandardParam - - -def hidden_reparam(use_mup: bool = True) -> type[AbstractLinearReparam]: - """Return the reparameterization class for a hidden linear layer.""" - - return mup.HiddenLinearMup if use_mup else mup.LinearStandardParam - - -def output_reparam(use_mup: bool = True) -> type[AbstractLinearReparam]: - """Return the reparameterization class for an output linear layer.""" - - return mup.OutputLinearMup if use_mup else mup.LinearStandardParam commit 75ce4e592788083ae4b708cf696c705c397b1b55 Date: 2025-10-07T13:16:15-04:00 Merge pull request #219 from marin-community/will/mupiax MuP Layer Support in Haliax commit 00026e2869cf0a79176f3293eba18baed6c08b54 Date: 2025-10-08T14:07:14-07:00 Clarify scan-aware tree map docs (#220) diff --git a/docs/api.md b/docs/api.md index 77e1577..e404157 100644 --- a/docs/api.md +++ b/docs/api.md @@ -4,6 +4,37 @@ that we use names (either strings or [haliax.Axis][] objects) to specify axes in arrays (see [haliax.zeros][] and [haliax.ones][]) as well as things like reductions (see [haliax.sum][] and [haliax.mean][]). +## PyTree Helpers + +PyTrees are the lingua franca for composing state in JAX ecosystems. Haliax provides drop-in replacements for the +[`jax.tree`][] helpers that are aware of [`NamedArray`][haliax.NamedArray] semantics. They preserve axis metadata across +transformations while interoperating with standard JAX containers, so you can use them anywhere you would have reached +for JAX's versions. + +Use these helpers whenever you need to map, flatten, or rebuild PyTrees that might include `NamedArray` instances: + +* [`haliax.tree.map`][] mirrors [`jax.tree.map`][] but forwards to Haliax's [`haliax.tree_util.tree_map`][] so axis names remain + intact. +* [`haliax.tree.scan_aware_map`][] descends into [`haliax.nn.Stacked`][haliax.nn.Stacked] modules so that each layer is + transformed individually, effectively treating them as if they were unrolled when applying + [`haliax.tree_util.scan_aware_tree_map`][]. +* [`haliax.tree.flatten`][] / [`haliax.tree.unflatten`][] match the familiar flattening API while handling `NamedArray` + payloads safely. +* [`haliax.tree.leaves`][] and [`haliax.tree.structure`][] provide direct access to the leaves and PyTree structure. + +All of these helpers accept the same `is_leaf` hook you might already use with JAX's utilities. They should be the first +tools you reach for when you need deterministic tree transforms that understand named axes. + +::: haliax.tree.map +::: haliax.tree.scan_aware_map +::: haliax.tree.flatten +::: haliax.tree.unflatten +::: haliax.tree.leaves +::: haliax.tree.structure + +[`jax.tree`]: https://jax.readthedocs.io/en/latest/_autosummary/jax.tree.html +[`jax.tree.map`]: https://jax.readthedocs.io/en/latest/_autosummary/jax.tree.map.html + ## Axis Types If you already speak NumPy or `jax.numpy`, think of Haliax as swapping positional axes (`axis=0`) for named axes diff --git a/src/haliax/__init__.py b/src/haliax/__init__.py index ebab498..a44a86b 100644 --- a/src/haliax/__init__.py +++ b/src/haliax/__init__.py @@ -16,6 +16,7 @@ import haliax.nn as nn import haliax.quantization as quantization import haliax.random as random import haliax.state_dict as state_dict +import haliax.tree as tree # noqa: F401 import haliax.tree_util as tree_util import haliax.util as util from .field import field diff --git a/src/haliax/tree.py b/src/haliax/tree.py new file mode 100644 index 0000000..a95715c --- /dev/null +++ b/src/haliax/tree.py @@ -0,0 +1,59 @@ +# Copyright 2025 The Levanter Authors +# +# SPDX-License-Identifier: Apache-2.0 + +"""Convenience wrappers for :mod:`haliax.tree_util` that mirror :mod:`jax.tree`.""" + +from __future__ import annotations + +from typing import Any, Callable, Iterable, Sequence, TypeVar + +from . import tree_util + +T = TypeVar("T") + + +def map(fn: Callable[..., T], tree: Any, *rest: Any, is_leaf: Callable[[Any], bool] | None = None) -> Any: + """Alias for :func:`haliax.tree_util.tree_map` matching :func:`jax.tree.map`.""" + + return tree_util.tree_map(fn, tree, *rest, is_leaf=is_leaf) + + +def scan_aware_map(fn: Callable[..., T], tree: Any, *rest: Any, is_leaf: Callable[[Any], bool] | None = None) -> Any: + """Alias for :func:`haliax.tree_util.scan_aware_tree_map` with :mod:`jax.tree` style naming.""" + + return tree_util.scan_aware_tree_map(fn, tree, *rest, is_leaf=is_leaf) + + +def flatten(tree: Any, *, is_leaf: Callable[[Any], bool] | None = None) -> tuple[Sequence[Any], Any]: + """Alias for :func:`haliax.tree_util.tree_flatten` matching :func:`jax.tree.flatten`.""" + + return tree_util.tree_flatten(tree, is_leaf=is_leaf) + + +def unflatten(treedef: Any, leaves: Iterable[Any]) -> Any: + """Alias for :func:`haliax.tree_util.tree_unflatten` matching :func:`jax.tree.unflatten`.""" + + return tree_util.tree_unflatten(treedef, leaves) + + +def leaves(tree: Any, *, is_leaf: Callable[[Any], bool] | None = None) -> Sequence[Any]: + """Alias for :func:`haliax.tree_util.tree_leaves` matching :func:`jax.tree.leaves`.""" + + return tree_util.tree_leaves(tree, is_leaf=is_leaf) + + +def structure(tree: Any, *, is_leaf: Callable[[Any], bool] | None = None) -> Any: + """Alias for :func:`haliax.tree_util.tree_structure` matching :func:`jax.tree.structure`.""" + + return tree_util.tree_structure(tree, is_leaf=is_leaf) + + +__all__ = [ + "map", + "scan_aware_map", + "flatten", + "unflatten", + "leaves", + "structure", +] commit b0f20293f189ed45d96b77162a5257dbfac45915 Date: 2025-10-09T00:13:24-04:00 Standard Parameterization Doesn't Scale Output Logits diff --git a/src/haliax/nn/mup.py b/src/haliax/nn/mup.py index 8048529..2804fdb 100644 --- a/src/haliax/nn/mup.py +++ b/src/haliax/nn/mup.py @@ -168,7 +168,7 @@ class EmbeddingStandardParam(AbstractEmbeddingReparam): @property def unembed_active_scale(self): - return 1 / hax.axis_size(self.Embed) + return 1 class EmbeddingMup(AbstractEmbeddingReparam): commit 6bd74df66294f4c28485a5f88b0d39d75dfec86a Date: 2025-10-09T00:17:17-04:00 Merge pull request #222 from marin-community/will/tied-bug Standard Parameterization Doesn't Scale Output Logits commit 0e408f40d053b81ccd67d7b967cee05ca34efdf8 Date: 2025-10-09T01:38:15-04:00 Default to Standard Parameterization diff --git a/src/haliax/nn/embedding.py b/src/haliax/nn/embedding.py index 384823c..7c66768 100644 --- a/src/haliax/nn/embedding.py +++ b/src/haliax/nn/embedding.py @@ -24,7 +24,12 @@ class Embedding(eqx.Module, ReparamEnabled): # axes Vocab: Axis = eqx.field(static=True) Embed: AxisSpec = eqx.field(static=True) - reparam: AbstractEmbeddingReparam = eqx.field(static=True) + + _reparam_cls: type[AbstractEmbeddingReparam] = eqx.field(static=True, default=EmbeddingStandardParam) + + @property + def reparam(self) -> AbstractEmbeddingReparam: + return self._reparam_cls(self.Embed, self.Vocab) @staticmethod def init( @@ -61,7 +66,7 @@ class Embedding(eqx.Module, ReparamEnabled): weight = hax.random.truncated_normal(key, all_axes, -3, 3) * ( init_scale * reparam_cls.init_scale(Vocab, Embed) ) - return Embedding(weight=weight, Vocab=Vocab, Embed=Embed, reparam=reparam_cls(Embed, Vocab)) + return Embedding(weight=weight, Vocab=Vocab, Embed=Embed, _reparam_cls=reparam_cls) def __call__(self, input_ids: NamedArray, *, key: PRNGKeyArray | None = None): """Alias for `embed`. key is ignored.""" diff --git a/src/haliax/nn/linear.py b/src/haliax/nn/linear.py index 58b7d59..e9c4781 100644 --- a/src/haliax/nn/linear.py +++ b/src/haliax/nn/linear.py @@ -45,9 +45,14 @@ class Linear(ModuleWithStateDictSerialization, ReparamEnabled): In: AxisSpec = eqx.field(static=True) Out: AxisSpec = eqx.field(static=True) - reparam: AbstractLinearReparam = eqx.field(static=True) dot_general: DotGeneralOp = eqx.field(default_factory=DotGeneralOp.default) + _reparam_cls: type[AbstractLinearReparam] = eqx.field(static=True, default=LinearStandardParam) + + @property + def reparam(self) -> AbstractLinearReparam: + return self._reparam_cls(self.In, self.Out) + @staticmethod def init( In: AxisSpec, @@ -77,7 +82,7 @@ class Linear(ModuleWithStateDictSerialization, ReparamEnabled): if dot_general is None: dot_general = DotGeneralOp.default() - return Linear(weight, bias, In, Out, dot_general=dot_general, reparam=reparam_cls(In, Out)) + return Linear(weight, bias, In, Out, dot_general=dot_general, _reparam_cls=reparam_cls) @named_call def __call__(self, inputs, *, key: PRNGKeyArray | None = None): diff --git a/tests/test_mup_embedding.py b/tests/test_mup_embedding.py index a0ccc17..f3b1c41 100644 --- a/tests/test_mup_embedding.py +++ b/tests/test_mup_embedding.py @@ -31,7 +31,7 @@ def test_mup_embedding_unembedding_scale(): Embed = (hax.Axis("E", 3),) weight = hax.ones(hax.concat_axis_specs(Vocab, Embed)) - layer = Embedding(weight=weight, Vocab=Vocab, Embed=Embed, reparam=EmbeddingMup(Embed, Vocab)) + layer = Embedding(weight=weight, Vocab=Vocab, Embed=Embed, _reparam_cls=EmbeddingMup) scale = layer.reparam.unembed_active_scale assert scale == pytest.approx(1.0 / hax.axis_size(Embed)) diff --git a/tests/test_mup_linear.py b/tests/test_mup_linear.py index 4739be2..cb08ab4 100644 --- a/tests/test_mup_linear.py +++ b/tests/test_mup_linear.py @@ -11,7 +11,12 @@ import pytest import haliax as hax from haliax.nn import Linear -from haliax.nn.mup import InputLinearMup, LinearStandardParam, HiddenLinearMup, OutputLinearMup +from haliax.nn.mup import ( + InputLinearMup, + LinearStandardParam, + HiddenLinearMup, + OutputLinearMup, +) @pytest.mark.parametrize("out_first", [True, False]) @@ -37,8 +42,8 @@ def test_mup_linear_call_matches_linear(): weight = hax.ones(hax.concat_axis_specs(Out, In)) * 0.5 bias = hax.full(Out, 0.25) - linear = Linear(weight, bias, In, Out, reparam=LinearStandardParam(In, Out)) - mup = Linear(weight, bias, In, Out, reparam=InputLinearMup(In, Out)) + linear = Linear(weight, bias, In, Out, _reparam_cls=LinearStandardParam) + mup = Linear(weight, bias, In, Out, _reparam_cls=InputLinearMup) inputs = hax.full(hax.concat_axis_specs(Batch, In), 2.0) @@ -109,8 +114,8 @@ def test_input_linear_behaves_like_base_linear(): weight = hax.ones((Out, In)) * 0.1 bias = hax.zeros(Out) - linear = Linear(weight, bias, In, Out, reparam=LinearStandardParam(In, Out)) - input_linear = Linear(weight, bias, In, Out, reparam=InputLinearMup(In, Out)) + linear = Linear(weight, bias, In, Out, _reparam_cls=LinearStandardParam) + input_linear = Linear(weight, bias, In, Out, _reparam_cls=InputLinearMup) inputs = hax.random.normal(jrandom.PRNGKey(5), (Batch, In)) commit 8a99a01c54e070014b8b19c3f5dd62001c7ed907 Date: 2025-10-09T03:23:26-04:00 Merge pull request #223 from marin-community/will/mup_default_improve Default to Standard Parameterization commit 44ad10cb52f303a37cbe4619a0c7c2ced95265a9 Date: 2025-10-09T17:38:11-07:00 Add unroll kwarg support to BlockFoldable helpers (#221) * Add unroll support to BlockFoldable interfaces * Allow boolean unroll settings and silence BlockSeq warnings * Pass through boolean unroll values diff --git a/src/haliax/nn/scan.py b/src/haliax/nn/scan.py index fdc642e..be67176 100644 --- a/src/haliax/nn/scan.py +++ b/src/haliax/nn/scan.py @@ -62,6 +62,22 @@ class ModuleInit(Protocol[M_co]): def __call__(self, *args, **kwargs) -> M_co: ... +def _normalize_unroll(unroll: int | bool | None, block_size: int) -> int | bool: + """Convert user-provided ``unroll`` values into something understood by ``jax.lax.scan``.""" + + if unroll is None: + return 1 + + if isinstance(unroll, bool): + return unroll + + resolved = int(unroll) + if resolved < 1: + raise ValueError(f"unroll must be >= 1; got {resolved}.") + + return resolved + + class BlockFoldable(Protocol[M]): """Common interface for :class:`~haliax.nn.Stacked` and :class:`~haliax.nn.BlockSeq`. @@ -84,29 +100,40 @@ class BlockFoldable(Protocol[M]): prevent_cse: bool = False, ) -> ModuleInit[S]: ... - def scan(self, init: T, *extra_args, **extra_kwargs): ... + def scan(self, init: T, *extra_args, unroll: int | bool | None = None, **extra_kwargs): ... - def fold(self, init: T, *args, **kwargs) -> T: ... + def fold(self, init: T, *args, unroll: int | bool | None = None, **kwargs) -> T: ... @overload - def fold_via(self, fn: FoldFunction[M, P, CarryT]) -> Callable[Concatenate[CarryT, P], CarryT]: ... + def fold_via( + self, fn: FoldFunction[M, P, CarryT], *, unroll: int | bool | None = None + ) -> Callable[Concatenate[CarryT, P], CarryT]: ... @overload - def fold_via(self, fn: Callable[[M, CarryT], CarryT]) -> Callable[[CarryT], CarryT]: ... + def fold_via( + self, fn: Callable[[M, CarryT], CarryT], *, unroll: int | bool | None = None + ) -> Callable[[CarryT], CarryT]: ... - def fold_via(self, fn: Callable[..., CarryT]) -> Callable[Concatenate[CarryT, P], CarryT]: ... + def fold_via( + self, fn: Callable[..., CarryT], *, unroll: int | bool | None = None + ) -> Callable[Concatenate[CarryT, P], CarryT]: ... @overload def scan_via( - self, fn: ScanFunction[M, CarryT, P, OutputT_co] + self, fn: ScanFunction[M, CarryT, P, OutputT_co], *, unroll: int | bool | None = None ) -> Callable[Concatenate[CarryT, P], tuple[CarryT, OutputT_co]]: ... @overload def scan_via( - self, fn: Callable[[M, CarryT], tuple[CarryT, OutputT_co]] + self, + fn: Callable[[M, CarryT], tuple[CarryT, OutputT_co]], + *, + unroll: int | bool | None = None, ) -> Callable[[CarryT], tuple[CarryT, OutputT_co]]: ... - def scan_via(self, fn: Callable[..., tuple[CarryT, OutputT_co]]) -> Callable[P, tuple[CarryT, OutputT_co]]: ... + def scan_via( + self, fn: Callable[..., tuple[CarryT, OutputT_co]], *, unroll: int | bool | None = None + ) -> Callable[P, tuple[CarryT, OutputT_co]]: ... @overload def vmap_via(self, fn: VmapFunction[M, P, OutputT_co]) -> Callable[P, OutputT_co]: ... @@ -181,15 +208,15 @@ class BlockSeq(ModuleWithStateDictSerialization, Generic[M]): return fn - def scan(self, init: T, *extra_args, **extra_kwargs): + def scan(self, init: T, *extra_args, unroll: int | bool | None = None, **extra_kwargs): def do_scan(init, *extra_args, **extra_kwargs): out = [] carry = init for i, block in enumerate(self.blocks): - (block_args, block_kwargs) = haliax.tree_util.tree_map( - functools.partial(BlockSeq._slice_out, self.Block, i), (extra_args, extra_kwargs) + functools.partial(BlockSeq._slice_out, self.Block, i), + (extra_args, extra_kwargs), ) block_result = block(carry, *block_args, **block_kwargs) @@ -210,12 +237,13 @@ class BlockSeq(ModuleWithStateDictSerialization, Generic[M]): return do_scan(init, *extra_args, **extra_kwargs) - def fold(self, init: T, *args, **kwargs) -> T: + def fold(self, init: T, *args, unroll: int | bool | None = None, **kwargs) -> T: def do_fold(init, *args, **kwargs): carry = init for i, block in enumerate(self.blocks): (block_args, block_kwargs) = haliax.tree_util.tree_map( - functools.partial(BlockSeq._slice_out, self.Block, i), (args, kwargs) + functools.partial(BlockSeq._slice_out, self.Block, i), + (args, kwargs), ) carry = block(carry, *block_args, **block_kwargs) carry = tree_checkpoint_name(carry, self._carry_ckpt_name) @@ -224,12 +252,16 @@ class BlockSeq(ModuleWithStateDictSerialization, Generic[M]): return do_fold(init, *args, **kwargs) @overload - def fold_via(self, fn: FoldFunction[M, P, CarryT]) -> Callable[Concatenate[CarryT, P], CarryT]: ... + def fold_via( + self, fn: FoldFunction[M, P, CarryT], *, unroll: int | bool | None = None + ) -> Callable[Concatenate[CarryT, P], CarryT]: ... @overload - def fold_via(self, fn: Callable[[M, CarryT], CarryT]) -> Callable[[CarryT], CarryT]: ... + def fold_via( + self, fn: Callable[[M, CarryT], CarryT], *, unroll: int | bool | None = None + ) -> Callable[[CarryT], CarryT]: ... - def fold_via(self, fn: Callable[..., CarryT]): + def fold_via(self, fn: Callable[..., CarryT], *, unroll: int | bool | None = None): """Return a function that folds over the sequence using ``fn``. ``fn`` should take a block and a carry and return a new carry. The @@ -247,15 +279,18 @@ class BlockSeq(ModuleWithStateDictSerialization, Generic[M]): @overload def scan_via( - self, fn: ScanFunction[M, CarryT, P, OutputT_co] + self, fn: ScanFunction[M, CarryT, P, OutputT_co], *, unroll: int | bool | None = None ) -> Callable[Concatenate[CarryT, P], tuple[CarryT, OutputT_co]]: ... @overload def scan_via( - self, fn: Callable[[M, CarryT], tuple[CarryT, OutputT_co]] + self, + fn: Callable[[M, CarryT], tuple[CarryT, OutputT_co]], + *, + unroll: int | bool | None = None, ) -> Callable[[CarryT], tuple[CarryT, OutputT_co]]: ... - def scan_via(self, fn: Callable[..., tuple[CarryT, OutputT_co]]): + def scan_via(self, fn: Callable[..., tuple[CarryT, OutputT_co]], *, unroll: int | bool | None = None): """Return a function that scans over the sequence using ``fn``. ``fn`` should take a block and a carry and return ``(carry, output)``. @@ -447,7 +482,7 @@ class Stacked(ModuleWithStateDictSerialization, Generic[M]): return fn - def scan(self, init, *extra_args, **extra_kwargs): + def scan(self, init, *extra_args, unroll: int | bool | None = None, **extra_kwargs): """ Scan over the stacked module. This is the same as a for loop that applies each instance of the module in sequence to the input, passing the output of one instance to the next instance. It returns a stack of outputs as @@ -475,19 +510,24 @@ class Stacked(ModuleWithStateDictSerialization, Generic[M]): """ + resolved_unroll = _normalize_unroll(unroll, self.Block.size) + def do_block(carry, block, *args, **kwargs): carry, out = block(carry, *args, **kwargs) return carry, out def do_scan(init, *extra_args, **extra_kwargs): - carry, out = haliax.scan(do_block, self.Block, remat=self.gradient_checkpointing)( - init, self.stacked, *extra_args, **extra_kwargs - ) + carry, out = haliax.scan( + do_block, + self.Block, + remat=self.gradient_checkpointing, + unroll=resolved_unroll, + )(init, self.stacked, *extra_args, **extra_kwargs) return carry, out return do_scan(init, *extra_args, **extra_kwargs) - def fold(self, init, *args, **kwargs): + def fold(self, init, *args, unroll: int | bool | None = None, **kwargs): """ Fold over the stacked module. This is the same as a for loop that applies each instance of the module in sequence to the input, passing the output of one instance to the next instance. @@ -510,66 +550,88 @@ class Stacked(ModuleWithStateDictSerialization, Generic[M]): """ + resolved_unroll = _normalize_unroll(unroll, self.Block.size) + def do_block(carry, block, *args, **kwargs): carry = block(carry, *args, **kwargs) return carry def do_fold(init, *extra_args, **extra_kwargs): - carry = haliax.fold(do_block, self.Block, remat=self.gradient_checkpointing)( - init, self.stacked, *extra_args, **extra_kwargs - ) + carry = haliax.fold( + do_block, + self.Block, + remat=self.gradient_checkpointing, + unroll=resolved_unroll, + )(init, self.stacked, *extra_args, **extra_kwargs) return carry return do_fold(init, *args, **kwargs) @overload - def fold_via(self, fn: FoldFunction[M, P, CarryT]) -> Callable[Concatenate[CarryT, P], CarryT]: ... + def fold_via( + self, fn: FoldFunction[M, P, CarryT], *, unroll: int | bool | None = None + ) -> Callable[Concatenate[CarryT, P], CarryT]: ... @overload - def fold_via(self, fn: Callable[[M, CarryT], CarryT]) -> Callable[[CarryT], CarryT]: ... + def fold_via( + self, fn: Callable[[M, CarryT], CarryT], *, unroll: int | bool | None = None + ) -> Callable[[CarryT], CarryT]: ... - def fold_via(self, fn: Callable[..., CarryT]): + def fold_via(self, fn: Callable[..., CarryT], *, unroll: int | bool | None = None): """Return a function that folds over the stack using ``fn``. ``fn`` should take a block and a carry and return a new carry. The returned function mirrors :func:`haliax.fold` over the block axis. """ + resolved_unroll = _normalize_unroll(unroll, self.Block.size) + def do_block(carry: CarryT, block: M, *args, **kwargs) -> CarryT: return fn(block, carry, *args, **kwargs) def do_fold(init: CarryT, *args, **kwargs) -> CarryT: - return haliax.fold(do_block, self.Block, remat=self.gradient_checkpointing)( - init, self.stacked, *args, **kwargs - ) + return haliax.fold( + do_block, + self.Block, + remat=self.gradient_checkpointing, + unroll=resolved_unroll, + )(init, self.stacked, *args, **kwargs) return do_fold @overload def scan_via( - self, fn: ScanFunction[M, CarryT, P, OutputT_co] + self, fn: ScanFunction[M, CarryT, P, OutputT_co], *, unroll: int | bool | None = None ) -> Callable[Concatenate[CarryT, P], tuple[CarryT, OutputT_co]]: ... @overload def scan_via( - self, fn: Callable[[M, CarryT], tuple[CarryT, OutputT_co]] + self, + fn: Callable[[M, CarryT], tuple[CarryT, OutputT_co]], + *, + unroll: int | bool | None = None, ) -> Callable[[CarryT], tuple[CarryT, OutputT_co]]: ... - def scan_via(self, fn: Callable[..., tuple[CarryT, OutputT_co]]): + def scan_via(self, fn: Callable[..., tuple[CarryT, OutputT_co]], *, unroll: int | bool | None = None): """Return a function that scans over the stack using ``fn``. ``fn`` should take a block and a carry and return ``(carry, output)``. Semantics match :func:`haliax.scan` over the block axis. """ + resolved_unroll = _normalize_unroll(unroll, self.Block.size) + def do_block(carry: CarryT, block: M, *args, **kwargs) -> tuple[CarryT, OutputT_co]: carry, output = fn(block, carry, *args, **kwargs) return carry, output def do_scan(init: CarryT, *args, **kwargs) -> tuple[CarryT, OutputT_co]: - return haliax.scan(do_block, self.Block, remat=self.gradient_checkpointing)( - init, self.stacked, *args, **kwargs - ) + return haliax.scan( + do_block, + self.Block, + remat=self.gradient_checkpointing, + unroll=resolved_unroll, + )(init, self.stacked, *args, **kwargs) return do_scan @@ -707,7 +769,7 @@ def _unstack_state_dict(state_dict: StateDict, prefix: str | None = None) -> Sta for k, v in state_dict.items(): if k.startswith(prefix) and is_jax_or_hax_array_like(v): for i, v_i in enumerate(v): - new_dict[f"{prefix}{i}.{k[len(prefix):]}"] = v_i + new_dict[f"{prefix}{i}.{k[len(prefix) :]}"] = v_i else: new_dict[k] = v diff --git a/tests/test_scan.py b/tests/test_scan.py index 6503842..85256a1 100644 --- a/tests/test_scan.py +++ b/tests/test_scan.py @@ -6,6 +6,7 @@ import equinox as eqx import jax import pytest +import warnings from equinox import filter_grad import haliax as hax @@ -164,6 +165,59 @@ def test_scan_with_aux_named_args(): assert hax.all(hax.isclose(z_scan, z_seq_scan, atol=1e-5)) +def test_blockseq_unroll_never_warns(): + class FoldModule(eqx.Module): + weight: hax.NamedArray + + def __call__(self, carry: hax.NamedArray) -> hax.NamedArray: + return carry + self.weight + + @staticmethod + def init(weight): + return FoldModule(weight=weight) + + class ScanModule(eqx.Module): + weight: hax.NamedArray + + def __call__(self, carry: hax.NamedArray) -> tuple[hax.NamedArray, hax.NamedArray]: + updated = carry + self.weight + return updated, updated + + @staticmethod + def init(weight): + return ScanModule(weight=weight) + + Block = hax.Axis("block", 3) + Value = hax.Axis("value", 2) + weights = hax.random.uniform(jax.random.PRNGKey(0), (Block, Value)) + + fold_seq = BlockSeq.init(Block, FoldModule)(weight=weights) + scan_seq = BlockSeq.init(Block, ScanModule)(weight=weights) + + init_carry = hax.zeros(Value) + + def fold_step(block: FoldModule, carry: hax.NamedArray) -> hax.NamedArray: + return block(carry) + + def scan_step(block: ScanModule, carry: hax.NamedArray) -> tuple[hax.NamedArray, hax.NamedArray]: + return block(carry) + + with warnings.catch_warnings(record=True) as caught: + warnings.simplefilter("always") + _ = fold_seq.fold(init_carry, unroll=2) + _ = fold_seq.fold(init_carry, unroll=True) + _ = fold_seq.fold(init_carry, unroll=False) + _ = fold_seq.fold_via(fold_step, unroll=True)(init_carry) + _ = fold_seq.fold_via(fold_step, unroll=False)(init_carry) + _ = scan_seq.scan(init_carry, unroll=2) + _ = scan_seq.scan(init_carry, unroll=True) + _ = scan_seq.scan(init_carry, unroll=False) + _ = scan_seq.scan_via(scan_step, unroll=True)(init_carry) + _ = scan_seq.scan_via(scan_step, unroll=False)(init_carry) + + assert not caught + + def test_stacked_to_state_dict(): class Module(eqx.Module): named: hax.NamedArray @@ -239,8 +293,18 @@ E = hax.Axis("E", 10) [(E.size,), (Block.size, E.size), (Block.size, E.size)], None, ), - ("simple", ScanCheckpointPolicy(simple=True), [(E.size,), (Block.size, E.size)], None), - ("nested", ScanCheckpointPolicy(simple=True, nested=2), [(E.size,), (2, E.size)], None), + ( + "simple", + ScanCheckpointPolicy(simple=True), + [(E.size,), (Block.size, E.size)], + None, + ), + ( + "nested", + ScanCheckpointPolicy(simple=True, nested=2), + [(E.size,), (2, E.size)], + None, + ), ( "sin_offload", ScanCheckpointPolicy(save_carries=True, offload_block_internals=["sin"]), @@ -371,6 +435,97 @@ def test_scan_via(): assert hax.all(hax.isclose(outs, expected_outs)) +def test_scan_via_with_unroll(): + class Module(eqx.Module): + w: hax.NamedArray + + def with_output(self, x): + out = x + self.w + return out, 2 * self.w + + def __call__(self, carry): + return carry + self.w, 2 * self.w + + @staticmethod + def init(named): + return Module(w=named) + + Block = hax.Axis("block", 4) + E = hax.Axis("E", 6) + + named = hax.random.uniform(jax.random.PRNGKey(0), (Block, E)) + m = Stacked.init(Block, Module)(named=named) + + x = hax.random.uniform(jax.random.PRNGKey(1), (E,)) + + default_carry, default_outs = m.scan_via(Module.with_output)(x) + carry, outs = m.scan_via(Module.with_output, unroll=2)(x) + + assert hax.all(hax.isclose(carry, default_carry)) + assert hax.all(hax.isclose(outs, default_outs)) + + default_carry_direct, default_outs_direct = m.scan(x) + carry_direct, outs_direct = m.scan(x, unroll=2) + + assert hax.all(hax.isclose(carry_direct, default_carry_direct)) + assert hax.all(hax.isclose(outs_direct, default_outs_direct)) + + +def test_scan_via_with_bool_unroll(monkeypatch): + class Module(eqx.Module): + w: hax.NamedArray + + def with_output(self, x): + out = x + self.w + return out, 2 * self.w + + def __call__(self, carry): + return carry + self.w, 2 * self.w + + @staticmethod + def init(named): + return Module(w=named) + + Block = hax.Axis("block", 4) + E = hax.Axis("E", 6) + + named = hax.random.uniform(jax.random.PRNGKey(0), (Block, E)) + m = Stacked.init(Block, Module)(named=named) + + x = hax.random.uniform(jax.random.PRNGKey(1), (E,)) + + default_carry_via, default_outs_via = m.scan_via(Module.with_output)(x) + default_carry_direct, default_outs_direct = m.scan(x) + + import haliax.nn.scan as hnn_scan + + scan_calls: list[int | None] = [] + original_scan = hnn_scan.haliax.scan + + def wrapped_scan(*args, **kwargs): + scan_calls.append(kwargs.get("unroll")) + return original_scan(*args, **kwargs) + + monkeypatch.setattr(hnn_scan.haliax, "scan", wrapped_scan) + + carry_true, outs_true = m.scan_via(Module.with_output, unroll=True)(x) + carry_false, outs_false = m.scan_via(Module.with_output, unroll=False)(x) + carry_true_direct, outs_true_direct = m.scan(x, unroll=True) + carry_false_direct, outs_false_direct = m.scan(x, unroll=False) + + assert scan_calls == [True, False, True, False] + + assert hax.all(hax.isclose(carry_true, default_carry_via)) + assert hax.all(hax.isclose(outs_true, default_outs_via)) + assert hax.all(hax.isclose(carry_false, default_carry_via)) + assert hax.all(hax.isclose(outs_false, default_outs_via)) + + assert hax.all(hax.isclose(carry_true_direct, default_carry_direct)) + assert hax.all(hax.isclose(outs_true_direct, default_outs_direct)) + assert hax.all(hax.isclose(carry_false_direct, default_carry_direct)) + assert hax.all(hax.isclose(outs_false_direct, default_outs_direct)) + + def test_scan_via_multi_args(): class Module(eqx.Module): w: hax.NamedArray @@ -513,6 +668,88 @@ def test_fold_via_multi_args(): assert hax.all(hax.isclose(result, expected)) +def test_fold_via_with_unroll(): + class Module(eqx.Module): + w: hax.NamedArray + + def intermediate(self, x): + return x + 2 * self.w + + def __call__(self, carry): + return carry + self.w + + @staticmethod + def init(named): + return Module(w=named) + + Block = hax.Axis("block", 3) + E = hax.Axis("E", 5) + + named = hax.random.uniform(jax.random.PRNGKey(0), (Block, E)) + m = Stacked.init(Block, Module)(named=named) + + x = hax.random.uniform(jax.random.PRNGKey(1), (E,)) + + default_result = m.fold_via(Module.intermediate)(x) + result_unroll = m.fold_via(Module.intermediate, unroll=2)(x) + + assert hax.all(hax.isclose(result_unroll, default_result)) + + default_fold = m.fold(x) + fold_unroll = m.fold(x, unroll=2) + + assert hax.all(hax.isclose(fold_unroll, default_fold)) + + +def test_fold_with_bool_unroll(monkeypatch): + class Module(eqx.Module): + w: hax.NamedArray + + def __call__(self, x): + return x + self.w + + def intermediate(self, x): + return x + 2 * self.w + + @staticmethod + def init(named): + return Module(w=named) + + Block = hax.Axis("block", 3) + E = hax.Axis("E", 5) + + named = hax.random.uniform(jax.random.PRNGKey(0), (Block, E)) + m = Stacked.init(Block, Module)(named=named) + + x = hax.random.uniform(jax.random.PRNGKey(1), (E,)) + + default_fold = m.fold(x) + default_fold_via = m.fold_via(Module.intermediate)(x) + + import haliax.nn.scan as hnn_scan + + fold_calls: list[int | None] = [] + original_fold = hnn_scan.haliax.fold + + def wrapped_fold(*args, **kwargs): + fold_calls.append(kwargs.get("unroll")) + return original_fold(*args, **kwargs) + + monkeypatch.setattr(hnn_scan.haliax, "fold", wrapped_fold) + + fold_true = m.fold(x, unroll=True) + fold_false = m.fold(x, unroll=False) + via_true = m.fold_via(Module.intermediate, unroll=True)(x) + via_false = m.fold_via(Module.intermediate, unroll=False)(x) + + assert fold_calls == [True, False, True, False] + + assert hax.all(hax.isclose(fold_true, default_fold)) + assert hax.all(hax.isclose(fold_false, default_fold)) + assert hax.all(hax.isclose(via_true, default_fold_via)) + assert hax.all(hax.isclose(via_false, default_fold_via)) + + def test_fold_via_static_args(): class Module(eqx.Module): w: hax.NamedArray commit 4ca12622bcceebdd5e61a11c5f4a7ed638767ce3 Date: 2025-10-10T15:23:20-04:00 Haliax Needs Jax Sync Workaround (#225) diff --git a/src/haliax/_src/state_dict.py b/src/haliax/_src/state_dict.py index 8eeffd1..6e1ddf0 100644 --- a/src/haliax/_src/state_dict.py +++ b/src/haliax/_src/state_dict.py @@ -13,7 +13,7 @@ import jax import jax.numpy as jnp import numpy as np from jax import ShapeDtypeStruct -from jax.experimental.multihost_utils import sync_global_devices +from haliax.jax_utils import sync_global_devices from jax.sharding import Mesh, NamedSharding, PartitionSpec from jax.tree_util import DictKey, FlattenedIndexKey, GetAttrKey, SequenceKey from jaxtyping import PyTree @@ -68,7 +68,11 @@ def flatten_modules_for_export(t: T) -> T: ) return module - return scan_aware_tree_map(_flatten_module, t, is_leaf=lambda x: isinstance(x, ModuleWithStateDictSerialization)) + return scan_aware_tree_map( + _flatten_module, + t, + is_leaf=lambda x: isinstance(x, ModuleWithStateDictSerialization), + ) def unflatten_modules_from_export(t: T, template: T) -> T: @@ -88,7 +92,10 @@ def unflatten_modules_from_export(t: T, template: T) -> T: return module return scan_aware_tree_map( - _unflatten_module, t, template, is_leaf=lambda x: isinstance(x, ModuleWithStateDictSerialization) + _unflatten_module, + t, + template, + is_leaf=lambda x: isinstance(x, ModuleWithStateDictSerialization), ) @@ -187,9 +194,13 @@ def from_state_dict(tree: T, state_dict: StateDict, prefix: str | None = None) - else: return default_eqx_module_from_state_dict(tree, state_dict, prefix) elif isinstance(tree, list): - return [from_state_dict(item, state_dict, with_prefix(prefix, str(i))) for i, item in enumerate(tree)] # type: ignore + return [ + from_state_dict(item, state_dict, with_prefix(prefix, str(i))) for i, item in enumerate(tree) + ] # type: ignore elif isinstance(tree, dict): - return {k: from_state_dict(v, state_dict, prefix=with_prefix(prefix, k)) for k, v in tree.items()} # type: ignore + return { + k: from_state_dict(v, state_dict, prefix=with_prefix(prefix, k)) for k, v in tree.items() + } # type: ignore elif isinstance(tree, NamedArray): if prefix is None: raise ValueError("Cannot extract a leaf value from a torch dict without a prefix") @@ -383,7 +394,8 @@ def to_numpy_state_dict(model, prefix: str | None = None) -> StateDict: # TODO: ensure that this mesh arranges devices correctly # (jax seems to do this internally itself, so we should be fine?) process_mesh = Mesh( - np.array(jax.devices()).reshape((jax.process_count(), -1)), ("process", "device") + np.array(jax.devices()).reshape((jax.process_count(), -1)), + ("process", "device"), ) # now we need to find an axis along which we can shard the array. @@ -391,7 +403,8 @@ def to_numpy_state_dict(model, prefix: str | None = None) -> StateDict: try: axis_to_shard = index_where( - lambda axis_size: axis_size % process_mesh.devices.size == 0, arr.shape + lambda axis_size: axis_size % process_mesh.devices.size == 0, + arr.shape, ) except ValueError: return np.array(arr) diff --git a/src/haliax/jax_utils.py b/src/haliax/jax_utils.py index 6334b3f..00c2077 100644 --- a/src/haliax/jax_utils.py +++ b/src/haliax/jax_utils.py @@ -6,6 +6,7 @@ import functools as ft import typing import warnings +import zlib from typing import Any, Callable, Sequence import equinox as eqx @@ -14,6 +15,8 @@ import numpy as np from jax import Array from jax import numpy as jnp from jax import random as jrandom +from jax.experimental.multihost_utils import host_local_array_to_global_array +from jax.sharding import PartitionSpec from jax.ad_checkpoint import checkpoint_name from jax.typing import DTypeLike from jaxtyping import PRNGKeyArray @@ -39,6 +42,71 @@ class Static(eqx.Module): value: Any = eqx.field(static=True) +# Non-busted version of broadcast_one_to_all from jax.multihost_utils. (The issue is that if you use a non-contiguous +# mesh, their utility blows up because it makes a contiguous mesh.) + + +def _psum(xs: Any) -> Any: + return jax.tree.map(lambda x: jnp.sum(x, dtype=x.dtype, axis=0), xs) + + +def broadcast_one_to_all(in_tree: Any, is_source: bool | None = None) -> Any: + """Broadcast data from a source host (host 0 by default) to all other hosts. + + Args: + in_tree: pytree of arrays - each array *must* have the same shape across the + hosts. + is_source: optional bool denoting whether the caller is the source. Only + 'source host' will contribute the data for the broadcast. If None, then + host 0 is used. + + Returns: + A pytree matching in_tree where the leaves now all contain the data from the + first host. + """ + if jax.process_count() == 1: + return jax.tree.map(np.asarray, in_tree) + + if is_source is None: + is_source = jax.process_index() == 0 + + devices: np.ndarray = np.array(jax.devices()).reshape(jax.process_count(), jax.local_device_count()) + global_mesh = jax.sharding.Mesh(devices, ("processes", "local_devices")) + pspec = PartitionSpec("processes") + + def pre_jit(x): + if is_source: + inp = x + else: + inp = np.zeros_like(x) + inp = np.expand_dims(inp, axis=0) + return host_local_array_to_global_array(inp, global_mesh, pspec) + + def post_jit(x): + return jax.device_get(x.addressable_data(0)) + + with haliax.partitioning.set_mesh(global_mesh): + in_tree = jax.tree.map(pre_jit, in_tree) + out_tree = jax.jit( + _psum, + out_shardings=jax.sharding.NamedSharding(global_mesh, PartitionSpec()), + )(in_tree) + return jax.tree.map(post_jit, out_tree) + + +def assert_equal(in_tree, fail_message: str = ""): + """Verifies that all the hosts have the same tree of values.""" + expected = broadcast_one_to_all(in_tree) + if not jax.tree_util.tree_all(jax.tree_util.tree_map(lambda *x: np.all(np.equal(*x)), in_tree, expected)): + raise AssertionError(f"{fail_message} Expected: {expected}; got: {in_tree}.") + + +def sync_global_devices(name: str): + """Creates a barrier across all hosts/devices.""" + h = np.uint32(zlib.crc32(name.encode())) + assert_equal(h, f"sync_global_devices name mismatch ('{name}')") + + def shaped_rng_split(key, split_shape: int | Sequence[int] = 2) -> PRNGKeyArray: if isinstance(split_shape, int): num_splits = split_shape @@ -69,14 +137,25 @@ def maybe_rng_split(key: PRNGKeyArray | None, num: int = 2): def filter_eval_shape(*args, **kwargs): import warnings - warnings.warn("filter_eval_shape is deprecated, use eqx.filter_eval_shape instead", DeprecationWarning) + warnings.warn( + "filter_eval_shape is deprecated, use eqx.filter_eval_shape instead", + DeprecationWarning, + ) return eqx.filter_eval_shape(*args, **kwargs) -def filter_checkpoint(fun: Callable, *, prevent_cse: bool = True, policy: Callable[..., bool] | None = None): +def filter_checkpoint( + fun: Callable, + *, + prevent_cse: bool = True, + policy: Callable[..., bool] | None = None, +): """As `jax.checkpoint`, but allows any Python object as inputs and outputs""" - warnings.warn("filter_checkpoint is deprecated, use eqx.filter_checkpoint instead", DeprecationWarning) + warnings.warn( + "filter_checkpoint is deprecated, use eqx.filter_checkpoint instead", + DeprecationWarning, + ) return eqx.filter_checkpoint(fun, prevent_cse=prevent_cse, policy=policy) commit 380a791566692d7e1a2072b25fc09df02db27711 Date: 2025-10-10T14:34:33-07:00 Add get_layer helper to BlockFoldable implementations (#224) diff --git a/src/haliax/nn/scan.py b/src/haliax/nn/scan.py index be67176..a5afb33 100644 --- a/src/haliax/nn/scan.py +++ b/src/haliax/nn/scan.py @@ -150,6 +150,11 @@ class BlockFoldable(Protocol[M]): """ ... + def get_layer(self, index: int) -> M: + """Return the ``index``th layer of the folded module.""" + + ... + class BlockSeq(ModuleWithStateDictSerialization, Generic[M]): """ @@ -377,6 +382,11 @@ class BlockSeq(ModuleWithStateDictSerialization, Generic[M]): return state_dict + def get_layer(self, index: int) -> M: + """Return the ``index``th block in this sequential container.""" + + return self.blocks[index] + @property def _output_ckpt_name(self): return f"BlockSeq[{self.Block}, {self.blocks[0].__class__.__name__}].outputs" @@ -442,6 +452,12 @@ class Stacked(ModuleWithStateDictSerialization, Generic[M]): Block: Axis = eqx.field(static=True) gradient_checkpointing: ScanCheckpointPolicy = eqx.field(static=True) + @property + def Layers(self) -> Axis: + """Alias for :attr:`Block` used by some downstream code.""" + + return self.Block + @classmethod def init( cls, @@ -700,6 +716,23 @@ class Stacked(ModuleWithStateDictSerialization, Generic[M]): unstacked_leaves = tuple(zip(*unstacked_leaves)) return tuple(map(lambda x: jax.tree_util.tree_unflatten(structure, x), unstacked_leaves)) + def get_layer(self, index: int) -> M: + """Return the ``index``th layer of this stacked module.""" + + def select_leaf(leaf): + if isinstance(leaf, haliax.NamedArray): + if haliax.selects_axis(leaf.axes, self.Block): + return leaf[self.Block, index] + else: + return leaf + if is_jax_or_hax_array_like(leaf): + if getattr(leaf, "shape", ()) and leaf.shape[0] == self.Block.size: + return leaf[index] + return leaf + return leaf + + return haliax.tree_util.tree_map(select_leaf, self.stacked) + def to_state_dict(self, prefix: str | None = None) -> StateDict: # this method needs to "devectorize" the blocks, so that we have a list of blocks h.0.FOO, h.1.FOO, etc. # first just do the normal thing with our own dict, which we'll post-process diff --git a/tests/test_scan.py b/tests/test_scan.py index 85256a1..6e25eb7 100644 --- a/tests/test_scan.py +++ b/tests/test_scan.py @@ -51,6 +51,65 @@ def test_unstacked(): assert hax.all(module.array == m.stacked.array[i]) +def test_get_layer_stacked(): + class Module(eqx.Module): + named: hax.NamedArray + array: jax.Array + static: int = eqx.static_field() + + def __call__(self, x, *, key): # pragma: no cover - unused in this test + return x + self.array + self.static + + @staticmethod + def init(named, array, static): + return Module(named=named, array=array, static=static) + + Block = hax.Axis("block", 3) + E = hax.Axis("E", 4) + + initial_named = hax.random.uniform(jax.random.PRNGKey(0), (Block, E)) + arrays = jax.numpy.arange(Block.size) + + stacked = Stacked.init(Block, Module)(named=initial_named, array=arrays, static=2) + + layer = stacked.get_layer(1) + + assert isinstance(layer, Module) + assert layer.static == 2 + assert layer.named.axes == (E,) + assert hax.all(layer.named == initial_named["block", 1]) + assert hax.all(layer.array == arrays[1]) + + +def test_get_layer_blockseq(): + class Module(eqx.Module): + named: hax.NamedArray + array: jax.Array + static: int = eqx.static_field() + + def __call__(self, x, *, key): # pragma: no cover - unused in this test + return x + self.array + self.static + + @staticmethod + def init(named, array, static): + return Module(named=named, array=array, static=static) + + Block = hax.Axis("block", 3) + E = hax.Axis("E", 4) + + initial_named = hax.random.uniform(jax.random.PRNGKey(0), (Block, E)) + arrays = jax.numpy.arange(Block.size) + + seq = BlockSeq.init(Block, Module)(named=initial_named, array=arrays, static=2) + + layer = seq.get_layer(2) + + assert isinstance(layer, Module) + assert layer.static == 2 + assert hax.all(layer.named == initial_named["block", 2]) + assert hax.all(layer.array == arrays[2]) + + def test_vmap(): class Module(eqx.Module): weight: hax.NamedArray commit f3a2ec18046930b7af9011b79a179fe13ca4f901 Date: 2025-10-11T23:35:36-07:00 Named Refs (#226) * refs! * fix slcied ref freezing * pre-commit * cleanup * cleaner * a little cleaner * ok good enough * grad works! diff --git a/.agents/refs.md b/.agents/refs.md new file mode 100644 index 0000000..b42d5fd --- /dev/null +++ b/.agents/refs.md @@ -0,0 +1,50 @@ +# NamedRef & SliceRef Plan + +## Goals +- Provide a `NamedRef` abstraction mirroring `jax.Ref` while preserving Haliax axis metadata. +- Offer helper APIs (`hax.new_ref`, `hax.freeze`, `hax.ref.get/swap`) that operate on named refs and enforce shape/axis compatibility. +- Enable "slice refs" that partially apply named indexers so subsequent operations only supply the remaining indices, including composing multiple slice refs. + +## Architectural Outline +1. **Core data model** + - Introduce `NamedRef` in `src/haliax/core.py` (or a focused `src/haliax/ref.py` module) as a thin wrapper around `jax.Ref` plus axis metadata (likely reuse `NamedArray` named shape helpers). + - Register `NamedRef` as a PyTree node: treat the underlying `jax.Ref` handle as a leaf to avoid unwanted tracing semantics. + - Expose properties: `.axes`, `.named_shape`, `.shape`, `.dtype`, and `.value` (reads through `ref[...]`). + +2. **Creation and conversion helpers** + - Implement `haliax.new_ref(value, axes|named_shape)` returning `NamedRef`; allow existing `NamedArray` inputs to propagate their axis info. + - Add `haliax.freeze(ref)` returning a `NamedArray` while invalidating the underlying `jax.Ref`, preserving metadata. + - Provide `haliax.ref.get(ref, index)` / `haliax.ref.swap(ref, index, value)` that accept named indexers and return/require `NamedArray` values. + +3. **Indexing semantics** + - Reuse the existing NamedArray indexing utilities (`axis_spec_to_tuple`, `_normalize_indexers`, `_NamedIndexUpdateRef`) so `NamedRef.__getitem__` returns `NamedArray` views and `__setitem__` / `.set` accept either `NamedArray` or raw arrays (with shape checks). + - Enforce error messaging consistent with NamedArray when axes mismatch or out-of-bounds indices occur. + +4. **Slice refs** + - Add a `NamedSliceRef` (or similar) that wraps a base `NamedRef` plus a frozen partial index mapping. + - Support construction via `NamedRef.slice(selector)` where `selector` is any named index expression (dict, `Axis`, tuple, etc.). + - On read/write, merge the stored selector with the new selector: the stored selector is applied first, and new selectors can further index the result. Implement logic to resolve nested slices (e.g. range then integer index) by normalizing everything to positional indices via helper utilities. + - Ensure composition is associative: calling `.slice()` on a `NamedSliceRef` should produce another `NamedSliceRef` that collapses selectors appropriately. + - Preserve dynamic slice selectors (Haliax `dslice` or `pallas.dslice`) so their static size information is retained during trace-time shape inference. + - Provide an `unsliced()` helper to recover the original reference when staged selectors are no longer needed. + - Handle ellipsis and implicit axes; ensure merging respects axis ordering and catches conflicting assignments. + +5. **Integration & ergonomics** + - Audit parts of the codebase that manipulate mutable state (e.g. caching layers, training loops) to expose the new API where appropriate. Initially, surface `NamedRef` under the `haliax.ref` namespace without retrofitting all call sites. + - Provide a `NamedRef.unsafe_buffer_pointer()` passthrough for parity with `jax.Ref` diagnostics. + +6. **Testing strategy** + - Add `tests/test_named_ref.py` covering: creation from arrays, indexing/assignment (scalar, slices, advanced), `jit` usage, vmap plumbing, and ensuring restrictions (e.g. returning refs from jit) raise clear errors. + - Include dedicated tests for slice refs verifying merged indexing (simple axis, slices-of-slices, dict updates, ellipsis) and interactions under `jit`. + - Validate that gradients through pure functions using NamedRef internally behave like the array equivalents. + +7. **Documentation & guidelines** + - Document the new API in `docs/api.md` (table entry and short section) and, if needed, add a primer example in `docs/primer.md` showing plumbing state with NamedRef. + - Update contributor notes that future ref-based utilities must keep numerical tolerances intact (no relaxed tolerances), aligning with the existing testing guidelines. + - Call out any additional guidelines discovered during implementation (e.g., keeping dslice selectors intact for static shapes). + - Consider a `.playbooks/` entry if ref plumbing becomes a common flow after initial implementation. + +## Open Questions / Follow-ups +- Confirm whether `NamedRef` needs to support asynchronous dispatch or pytree flattening beyond leaf behavior. +- Decide if we want implicit conversion between `NamedRef` and `NamedArray` in certain helpers or require explicit `.value` reads for clarity. +- Explore caching strategies or wrappers for `foreach`-style utilities once the base `NamedRef` and slice refs land. diff --git a/docs/api.md b/docs/api.md index e404157..1fa4b3f 100644 --- a/docs/api.md +++ b/docs/api.md @@ -179,6 +179,42 @@ See also the section on [Indexing and Slicing](indexing.md). ::: haliax.take ::: haliax.updated_slice +## Mutable References + +See also the section on [Mutable References](mutable-refs.md). + +JAX provides [`jax.Ref`][], a mutable array reference that can be read or written in place while remaining compatible +with transformations such as `jax.jit` or `jax.grad`. Haliax mirrors that API with [`haliax.NamedRef`][haliax.NamedRef], +which carries axis metadata so you can keep using named indexing when plumbing state through your programs. + +You introduce a new reference with [`haliax.new_ref`][haliax.new_ref]. The returned object behaves much like a +[`NamedArray`][haliax.NamedArray] for indexing purposes: `ref[{"batch": 0}]` reads a slice, and assignments like +`ref[{"token": slice(1, 3)}] = update` perform in-place updates on the underlying buffer. If you need to stage part of a +reference for repeated use, call [`NamedRef.slice`][haliax.NamedRef.slice] to create a *slice ref*. Slice refs remember a +partial indexing expression so you only supply the remaining axes during reads or writes: + +```python +Cache = hax.Axis("layers", 24) +Head = hax.Axis("head", 8) +cache = hax.zeros((Cache, Head)) +cache_ref = hax.new_ref(cache) + +# Pin the layer axis once so subsequent lookups only specify the head coordinate. +layer_ref = cache_ref.slice({"layers": slice(4, 8)}) +layer_ref[{"layers": 0, "head": 3}] = 1.0 # updates layer 4, head 3 in the original cache +``` + +When you are done mutating a reference, call [`haliax.freeze`][haliax.freeze] to invalidate it and recover a final +`NamedArray` snapshot. You can also perform atomic-style updates with [`haliax.swap`][haliax.swap] (or the functional +helpers under `haliax.ref`). + +::: haliax.NamedRef +::: haliax.new_ref +::: haliax.freeze +::: haliax.swap + +[`jax.Ref`]: https://docs.jax.dev/en/latest/array_refs.html + #### Dynamic Slicing ::: haliax.dslice diff --git a/docs/mutable-refs.md b/docs/mutable-refs.md new file mode 100644 index 0000000..d41b12a --- /dev/null +++ b/docs/mutable-refs.md @@ -0,0 +1,133 @@ +# Mutable References + +JAX now exposes [`jax.Ref`](https://jax.readthedocs.io/en/latest/notebooks/refs.html), a mutable buffer that +remains compatible with transformations such as `jax.jit`, `jax.grad`, and friends. Haliax mirrors that idea with +[`haliax.NamedRef`][haliax.NamedRef], preserving axis metadata so you can keep using named indexing while wiring state +through pure computations. + +This page walks through the common idioms you will encounter when working with named references, including ways to +slice references, compose partial selectors, and freeze or swap out the underlying data when you are done. + +## Creating a `NamedRef` + +Use [`haliax.new_ref`][haliax.new_ref] to wrap an existing tensor. The helper accepts either a +[`NamedArray`][haliax.NamedArray] or a raw JAX array plus an axis specification. + +```python +import haliax as hax +import jax + +Batch, Feature = hax.make_axes(Batch=4, Feature=8) +weights = hax.random.normal(jax.random.PRNGKey(0), (Batch, Feature)) +weights_ref = hax.new_ref(weights) + +# You can still inspect the named shape. +assert weights_ref.axes == weights.axes +assert weights_ref.shape == {"Batch": 4, "Feature": 8} +``` + +Inside a pure function you can allocate fresh references to stage intermediate results: + +```python +@jax.jit +def normalize(x: hax.NamedArray) -> hax.NamedArray: + ref = hax.new_ref(x) + ref[{"Batch": slice(None)}] = ref[{"Batch": slice(None)}] - hax.mean(x, axis=Batch) + return ref[...] +``` + +References follow JAX's rules: you may not return the ref itself from inside a transformed function, pass the same ref +argument multiple times, or close over a ref that is also passed as a parameter. Those restrictions keep aliasing under +control so transformations can reason about side effects. + +## Reading and writing + +`NamedRef` behaves like a lightweight view of the underlying buffer. Reading always returns a `NamedArray`, while writing +accepts either bare scalars/JAX arrays or another `NamedArray` with matching axes. + +```python +logits_ref = hax.new_ref(hax.zeros((Batch, Feature))) + +# Read a slice. +logits = logits_ref[{"Batch": 0}] + +# Write back in-place. +logits_ref[{"Batch": 0}] = hax.random.uniform(jax.random.PRNGKey(1), logits.axes) + +# Mutations are visible through other aliasing refs. +assert logits_ref[{"Batch": 0}].array is not None +``` + +If you prefer a functional style, use [`haliax.ref.get`][haliax.ref.get] or [`haliax.swap`][haliax.swap]. The latter +swaps in a new value and returns the previous contents, similar to `dict.setdefault`. + +## Slice references + +Plumbing state often requires staging a subset of the axes. `NamedRef.slice` lets you pre-apply a named indexer to a +reference and reuse it later without repeating the prefix. We call the result a *slice ref*. + +```python +Cache = hax.Axis("layer", 24) +Head = hax.Axis("head", 8) +cache = hax.zeros((Cache, Head)) +cache_ref = hax.new_ref(cache) + +# Focus on a subset of layers. +window = cache_ref.slice({"layer": slice(4, 8)}) + +# Indexing the slice ref automatically splices the prefix into the base ref. +window[{"layer": 0, "head": 3}] = 1.0 # updates layer 4, head 3 in the original buffer +# `.value()` reads the staged slice. +window_value = window.value() +``` + +Slice refs compose. Applying `.slice(...)` to an existing slice ref merges the new selection with the previous one, so +`cache_ref.slice({"layer": slice(1, 4)}).slice({"layer": 0})` updates the second layer of the original cache. Integer and +slice prefixes are supported; advanced indexing still needs to happen at call time (`slice` with `NamedArray` selectors or +lists is not yet folded into the prefix). + +If you need to recover the original reference (without any staged prefixes), call [`NamedRef.unsliced`][haliax.NamedRef.unsliced]. + +The merging logic mirrors `NamedArray.__getitem__`: ellipses expand to the remaining axes, implicit dimensions are +filled in order, and conflicting assignments raise errors. See [Indexing and Slicing](indexing.md) for a refresher. + +## Working with transformations + +Because `NamedRef` is registered as a PyTree node, you can nest it inside larger pytree structures or pass it through +`jax.tree_map` for bookkeeping. Only the underlying `jax.Ref` is considered a leaf, so axis metadata is treated as static +structure and does not trigger recompilation. + +Keep in mind the JAX restrictions on mutable functions: + +- Do not return a ref from inside `jax.jit`, `jax.grad`, `jax.vmap`, `jax.lax.scan`, etc. +- Avoid closing over a ref you also pass into the function (JAX disallows those aliasing patterns). +- Use `jax.lax.stop_gradient` if you are plumbing values that should not affect differentiation. + +Pure functions that create refs internally continue to compose normally with autodiff and vectorization. If your ref is +only used for bookkeeping (e.g., collecting auxiliary statistics), stop gradients before writing into it: + +```python +def collect_metrics(x, stats_ref): + y = hax.sin(x) + stats_ref[{"Batch": slice(None)}] += jax.lax.stop_gradient(y) + return y +``` + +## Freezing and swapping + +When you are done mutating a reference, call [`haliax.freeze`][haliax.freeze] to convert it back into an immutable +`NamedArray`. + +```python +final = hax.freeze(cache_ref) +assert isinstance(final, hax.NamedArray) +``` + +[`haliax.swap`][haliax.swap] provides an atomic-style update: it returns the previous value while storing the new one. +The helper integrates with slice refs, so you can swap just a subset of the buffer. + +```python +prev = hax.swap(cache_ref, {"layer": slice(0, 2)}, hax.ones((Cache.resize(2), Head))) +``` + +See [`tests/test_named_ref.py`](tests/test_named_ref.py) for runnable examples that exercise the API. diff --git a/mkdocs.yml b/mkdocs.yml index 97f5c07..e41175b 100644 --- a/mkdocs.yml +++ b/mkdocs.yml @@ -88,6 +88,7 @@ nav: - Named Arrays: - Broadcasting: 'broadcasting.md' - Indexing and Slicing: 'indexing.md' + - Mutable References: 'mutable-refs.md' - Rearrange: 'rearrange.md' - Matrix Multiplication: 'matmul.md' - Type Annotations: 'typing.md' diff --git a/src/haliax/__init__.py b/src/haliax/__init__.py index a44a86b..1302f12 100644 --- a/src/haliax/__init__.py +++ b/src/haliax/__init__.py @@ -16,6 +16,7 @@ import haliax.nn as nn import haliax.quantization as quantization import haliax.random as random import haliax.state_dict as state_dict +import haliax.ref as ref # noqa: F401 import haliax.tree as tree # noqa: F401 import haliax.tree_util as tree_util import haliax.util as util @@ -68,6 +69,7 @@ from .core import ( unflatten_axis, updated_slice, ) +from .ref import NamedRef, freeze, get, new_ref, swap from .haxtyping import Named from .hof import fold, map, scan, vmap from .jax_utils import tree_checkpoint_name @@ -1350,5 +1352,10 @@ __all__ = [ "NamedArrayAxes", "NamedArrayAxesSpec", "Named", + "NamedRef", + "new_ref", + "freeze", + "swap", + "get", "set_mesh", ] diff --git a/src/haliax/jax_utils.py b/src/haliax/jax_utils.py index 00c2077..390b800 100644 --- a/src/haliax/jax_utils.py +++ b/src/haliax/jax_utils.py @@ -17,6 +17,7 @@ from jax import numpy as jnp from jax import random as jrandom from jax.experimental.multihost_utils import host_local_array_to_global_array from jax.sharding import PartitionSpec +from jax._src.state.indexing import Slice from jax.ad_checkpoint import checkpoint_name from jax.typing import DTypeLike from jaxtyping import PRNGKeyArray @@ -218,13 +219,7 @@ def is_in_jit(): def is_pallas_dslice(x: object) -> bool: - try: - from jax.experimental.pallas import dslice as pdslice - except ImportError: - return False - - _PALLAS_DSLICE_TYPE = type(pdslice(0, 1)) - return isinstance(x, _PALLAS_DSLICE_TYPE) + return isinstance(x, Slice) def is_scalarish(x): diff --git a/src/haliax/ref.py b/src/haliax/ref.py new file mode 100644 index 0000000..577aa76 --- /dev/null +++ b/src/haliax/ref.py @@ -0,0 +1,429 @@ +# Copyright 2025 The Levanter Authors +# +# SPDX-License-Identifier: Apache-2.0 + +from __future__ import annotations + +import functools +from dataclasses import dataclass, replace +from typing import Any, Mapping, Sequence +from types import EllipsisType + +import jax +import jax.numpy as jnp + +from .axis import Axis, AxisSelector, axis_name, axis_spec_to_tuple, dslice as HaliaxDSlice +from .core import ( + NamedArray, + NamedOrNumeric, + SliceSpec, + _compute_new_axes_and_slices_for_index, + _convert_index_expr_to_dict, + named, +) +from .jax_utils import is_pallas_dslice + +from jax.experimental.pallas import dslice + + +class _AxisMetadata: + """Minimal structure supplying just axis metadata for index helpers.""" + + def __init__(self, axes: Sequence[Axis]): + self.axes = tuple(axes) + + def axis_indices(self, axis: AxisSelector) -> int | None: + name = axis_name(axis) + for i, ax in enumerate(self.axes): + if ax.name == name: + return i + return None + + +def _is_trivial_index(idx: Any) -> bool: + return isinstance(idx, slice) and idx.start is None and idx.stop is None and idx.step is None + + +def _slice_length(start: int, stop: int, step: int) -> int: + if step == 0: + raise ValueError("slice step cannot be zero") + if step > 0: + if start >= stop: + return 0 + return (stop - start + step - 1) // step + if start <= stop: + return 0 + step_abs = -step + return (start - stop - step - 1) // step_abs + + +def _is_slice_like(value: Any) -> bool: + return isinstance(value, (slice, range, HaliaxDSlice)) or is_pallas_dslice(value) + + +def _normalize_slice_value(value: Any, axis: Axis) -> Any: + if not _is_slice_like(value): + return value + + if isinstance(value, range): + # return slice(value.start, value.stop, value.step) + value = slice(value.start, value.stop, value.step) + + if isinstance(value, slice): + start, stop, step = value.indices(axis.size) + length = _slice_length(start, stop, step) + return dslice(start, length, step) + + if isinstance(value, HaliaxDSlice): + return _to_pallas_dslice(value) + + if is_pallas_dslice(value): + return value + + raise ValueError("Should not reach here") + + +def _dslice_params(value: Any) -> tuple[Any, int, Any] | None: + """ + For slice like objects, return (start, size, step). + """ + if isinstance(value, HaliaxDSlice): + return value.start, value.size, 1 + if is_pallas_dslice(value): + start = value.start + size = value.size + step = value.stride + return start, size, step + + return None + + +def _axes_after_prefix(axes: Sequence[Axis], indices: Sequence[Any]) -> tuple[Axis, ...]: + view_axes: list[Axis] = [] + for axis, sel in zip(axes, indices): + if isinstance(sel, int): + continue + if isinstance(sel, slice): + start, stop, step = sel.indices(axis.size) + length = _slice_length(start, stop, step) + view_axes.append(Axis(axis.name, length)) + else: + params = _dslice_params(sel) + if params is not None: + _start, size, _step = params + if not isinstance(size, int): + size = int(size) + view_axes.append(Axis(axis.name, size)) + continue + else: + raise NotImplementedError( + "Slice references currently only support integer or slice prefixes; " + f"got {type(sel)} for axis {axis}" + ) + return tuple(view_axes) + + +def _combine_index( + current: slice | int, + new: Any, + *, + base_axis: Axis, + view_axis: Axis, +) -> Any: + if isinstance(current, int): + raise ValueError(f"Axis {base_axis.name} is already fixed by the slice reference") + + if _is_slice_like(current): + current = _normalize_slice_value(current, axis=base_axis) + else: + raise NotImplementedError("Slice references currently only support simple integer/slice prefixes") + + ds_params = _dslice_params(current) + assert ds_params is not None + + start0, size0, step0 = ds_params + view_length = size0 + + if _is_slice_like(new): + new = _normalize_slice_value(new, axis=view_axis) + + if _is_slice_like(new): + n_params = _dslice_params(new) + assert n_params is not None + start1, size1, step1 = n_params + start = start0 + start1 * step0 + step = step0 * step1 + return dslice(start, size1, step) + + if isinstance(new, int): + if new < -view_length or new >= view_length: + raise IndexError(f"Index {new} out of bounds for axis {view_axis.name}") + if new < 0: + new += view_length + return start0 + new * step0 + + if isinstance(new, NamedArray): + data = jnp.where(new.array < 0, new.array + view_length, new.array) + transformed = data * step0 + start0 + return NamedArray(transformed, new.axes) + + if isinstance(new, jnp.ndarray): + data = jnp.where(new < 0, new + view_length, new) + return data * step0 + start0 + + if isinstance(new, (list, tuple)): + converted_list: list[int] = [] + for item in new: + if not isinstance(item, int): + raise TypeError("Only integer lists/tuples are supported for slice references") + if item < -view_length or item >= view_length: + raise IndexError(f"Index {item} out of bounds for axis {view_axis.name}") + if item < 0: + item += view_length + converted_list.append(start0 + item * step0) + return converted_list + + raise TypeError( + "Slice references only support integers, slices, dslice, NamedArray, jnp.ndarray, or lists/tuples thereof" + f"; got {type(new)}" + ) + + +def _combine_indices( + axes: Sequence[Axis], + prefix: Sequence[Any], + selectors: Mapping[AxisSelector, Any], +) -> tuple[Any, ...]: + if not selectors: + return tuple(prefix) + + current = list(prefix) + view_axes = _axes_after_prefix(axes, prefix) + view_positions = {ax.name: i for i, ax in enumerate(view_axes)} + mapping = [i for i, sel in enumerate(prefix) if not isinstance(sel, int)] + + for axis_sel, new_value in selectors.items(): + name = axis_name(axis_sel) + view_pos = view_positions.get(name) + if view_pos is None: + raise ValueError(f"Axis {name} is not available in this slice reference") + base_pos = mapping[view_pos] + base_axis = axes[base_pos] + view_axis = view_axes[view_pos] + combined = _combine_index(current[base_pos], new_value, base_axis=base_axis, view_axis=view_axis) + current[base_pos] = combined + + return tuple(current) + + +def _indices_to_selector(axes: Sequence[Axis], indices: Sequence[Any]) -> dict[AxisSelector, Any]: + selector: dict[AxisSelector, Any] = {} + for axis, idx in zip(axes, indices): + if _is_trivial_index(idx): + continue + selector[axis] = idx + return selector + + +def _to_pallas_dslice(value): + if is_pallas_dslice(value): + return value + if isinstance(value, HaliaxDSlice): + return dslice(value.start, value.size) + raise TypeError("Expected a haliax.dslice or pallas.dslice") + + +def _is_supported_prefix(idx: Any) -> bool: + if isinstance(idx, (slice, int, HaliaxDSlice)) or is_pallas_dslice(idx): + return True + if isinstance(idx, list) and all(isinstance(it, int) for it in idx): + return True + if isinstance(idx, (jnp.ndarray, jax.Array)): + return idx.ndim <= 1 and jnp.issubdtype(idx.dtype, jnp.integer) + if isinstance(idx, NamedArray): + return idx.ndim <= 1 and jnp.issubdtype(idx.array.dtype, jnp.integer) + if jnp.isscalar(idx): + dtype = idx.dtype + if dtype is None: + dtype = jnp.asarray(idx).dtype + return jnp.issubdtype(dtype, jnp.integer) + return False + + # >>> @partial(jax.tree_util.register_dataclass, + # ... data_fields=['x', 'y'], + # ... meta_fields=['op']) + + +@functools.partial( + jax.tree_util.register_dataclass, + # TODO: prefix should be a data field, but it can't until we make all _prefix members Slice or other arrays + # data_fields=["_ref", "_prefix"], + # meta_fields=["_axes"], + data_fields=["_ref"], + meta_fields=["_axes", "_prefix"], +) +@dataclass(frozen=True) +class NamedRef: + """Named wrapper around :class:`jax.Ref` that preserves axis metadata.""" + + _ref: jax.Ref + _axes: tuple[Axis, ...] + _prefix: tuple[Any, ...] + + def __post_init__(self): + if len(self._axes) != len(self._prefix): + raise ValueError("Prefix entries must align with axes") + + @property + def dtype(self): + """Return the dtype of the underlying reference.""" + return self._ref.dtype + + @property + def axes(self) -> tuple[Axis, ...]: + """Axes visible from this view after applying staged selectors.""" + return _axes_after_prefix(self._axes, self._prefix) + + @property + def shape(self) -> Mapping[str, int]: + """Mapping from axis name to size for the current view.""" + return {ax.name: ax.size for ax in self.axes} + + @property + def named_shape(self) -> Mapping[str, int]: + return self.shape + + @property + def ndim(self) -> int: + """Number of axes in the current view.""" + return len(self.axes) + + def value(self) -> NamedArray: + """Materialize this reference view as a `NamedArray`.""" + _, axes_spec, index_tuple = self._prepare(Ellipsis) + result = self._ref[tuple(index_tuple)] + return named(result, axes_spec) + + def unsliced(self) -> "NamedRef": + """Return a view of the original reference without staged selectors.""" + full_prefix = tuple(slice(None) for _ in self._axes) + if self._prefix == full_prefix: + return self + return NamedRef(self._ref, self._axes, full_prefix) + + def _prepare( + self, idx: SliceSpec | EllipsisType | None + ) -> tuple[tuple[Any, ...], tuple[AxisSelector, ...], list[Any]]: + """Combine existing prefixes with a new index expression and produce raw JAX indexers.""" + if idx is Ellipsis or idx is None: + selectors: Mapping[AxisSelector, Any] = {} + else: + selectors = _convert_index_expr_to_dict(idx) + + combined = _combine_indices(self._axes, self._prefix, selectors) + selector_dict = _indices_to_selector(self._axes, combined) + array_info = _AxisMetadata(self._axes) + new_axes, ordered = _compute_new_axes_and_slices_for_index(array_info, selector_dict) + normalized_spec = axis_spec_to_tuple(new_axes) + index_tuple: list[Any] = [] + for axis, item in zip(self._axes, ordered): + selector_value = selector_dict.get(axis) + if selector_value is not None and ( + isinstance(selector_value, HaliaxDSlice) or is_pallas_dslice(selector_value) + ): + index_tuple.append(_to_pallas_dslice(selector_value)) + else: + index_tuple.append(item.array if isinstance(item, NamedArray) else item) + return combined, normalized_spec, index_tuple + + def __getitem__(self, idx: SliceSpec | EllipsisType = Ellipsis) -> NamedArray: + """Read from the reference using named indexing semantics.""" + _, axes_spec, index_tuple = self._prepare(idx) + result = self._ref[tuple(index_tuple)] + return named(result, axes_spec) + + def __setitem__(self, idx: SliceSpec | EllipsisType, value: NamedOrNumeric) -> None: + """Write to the reference using named indexing semantics.""" + _, axes_spec, index_tuple = self._prepare(idx) + if isinstance(value, NamedArray): + desired = axes_spec + desired_tuple = axis_spec_to_tuple(desired) + desired_names = tuple(axis_name(ax) for ax in desired_tuple) + current_names = tuple(axis_name(ax) for ax in value.axes) + if set(current_names) != set(desired_names): + raise ValueError( + f"Value axes {current_names} do not match target axes {desired_names}; broadcasting is not yet supported" + ) + if current_names != desired_names: + value = value.rearrange(desired_tuple) + payload = value.array + else: + payload = jnp.asarray(value) + self._ref[tuple(index_tuple)] = payload + + def resolve_axis(self, axis: AxisSelector) -> Axis: + """Resolve an axis selector to the corresponding axis in the current view.""" + name = axis_name(axis) + for ax in self.axes: + if ax.name == name: + return ax + raise ValueError(f"Axis {name} is not present in this reference view") + + def slice(self, selector: Mapping[AxisSelector, Any]) -> "NamedRef": + """Return a new view with the provided selector staged for future operations.""" + normalized = {key: _normalize_slice_value(val, self.resolve_axis(key)) for key, val in selector.items()} + combined = _combine_indices(self._axes, self._prefix, normalized) + for idx in combined: + if not _is_supported_prefix(idx): + raise TypeError("Slice references only support simple integer/slice prefixes") + return replace(self, _prefix=combined) + + def unsafe_buffer_pointer(self): # pragma: no cover + return self._ref.unsafe_buffer_pointer() + + +def new_ref(value: NamedArray) -> NamedRef: + """Construct a `NamedRef` from a `NamedArray`.""" + if isinstance(value, NamedArray): + base_axes = value.axes + impl = jax.new_ref(value.array) + else: + raise TypeError("new_ref only supports NamedArray inputs") + + prefix = tuple(slice(None) for _ in base_axes) + return NamedRef(impl, base_axes, prefix) + + +def freeze(ref: NamedRef) -> NamedArray: + """Freeze the reference and return its current contents.""" + return ref.value() + + +def get(ref: NamedRef, idx: SliceSpec | EllipsisType = Ellipsis) -> NamedArray: + """Functional helper equivalent to `ref[idx]`.""" + return ref[idx] + + +def swap(ref: NamedRef, idx: SliceSpec | EllipsisType, value: NamedOrNumeric) -> NamedArray: + """Swap the value at `idx`, returning the previous contents as a `NamedArray`.""" + _, axes_spec, index_tuple = ref._prepare(idx) + if isinstance(value, NamedArray): + desired = axes_spec + desired_tuple = axis_spec_to_tuple(desired) + desired_names = tuple(axis_name(ax) for ax in desired_tuple) + current_names = tuple(axis_name(ax) for ax in value.axes) + if set(current_names) != set(desired_names): + raise ValueError( + f"Value axes {current_names} do not match target axes {desired_names}; broadcasting is not yet supported" + ) + if current_names != desired_names: + value = value.rearrange(desired_tuple) + payload = value.array + else: + payload = jnp.asarray(value) + + out = jax.ref.swap(ref._ref, tuple(index_tuple), payload, _function_name="haliax.ref.swap") + return named(out, axes_spec) + + +__all__ = ["NamedRef", "new_ref", "freeze", "get", "swap"] diff --git a/tests/test_named_ref.py b/tests/test_named_ref.py new file mode 100644 index 0000000..7a36d8d --- /dev/null +++ b/tests/test_named_ref.py @@ -0,0 +1,253 @@ +# Copyright 2025 The Levanter Authors +# +# SPDX-License-Identifier: Apache-2.0 + +import jax +import jax.numpy as jnp +import pytest +from jax.experimental.pallas import dslice + +import haliax as hax + + +@pytest.fixture +def key(): + return jax.random.PRNGKey(0) + + +def test_named_ref_basic_get_set(key): + X = hax.Axis("x", 4) + Y = hax.Axis("y", 3) + array = hax.random.uniform(key, (X, Y)) + ref = hax.new_ref(array) + + assert ref.shape == array.shape + assert ref.axes == array.axes + + slice_val = ref[{"x": slice(1, 3)}] + assert slice_val.axes == (X.resize(2), Y) + + new_block = hax.ones_like(slice_val) * 2.0 + ref[{"x": slice(1, 3)}] = new_block + updated = ref.value() + assert jnp.allclose(updated[{"x": slice(1, 3)}].array, jnp.asarray(new_block.array)) + + +def test_named_ref_scalar_update(): + X = hax.Axis("x", 5) + ref = hax.new_ref(hax.zeros(X)) + ref[{"x": 2}] = 3.14 + assert pytest.approx(ref.value()[{"x": 2}].array.item()) == 3.14 + + +def test_slice_ref_composition(): + Layer = hax.Axis("layer", 6) + Head = hax.Axis("head", 8) + cache = hax.zeros((Layer, Head)) + cache_ref = hax.new_ref(cache) + + layers_1_4 = cache_ref.slice({"layer": slice(1, 4)}) + assert layers_1_4.axes == (Layer.resize(3), Head) + + layers_1_4[{"layer": 0}] = hax.arange(Head).astype(jnp.float32) + value = cache_ref.value() + expected_row = jnp.arange(Head.size, dtype=jnp.float32) + assert jnp.allclose(value[{"layer": 1}].array, expected_row) + + single_layer = layers_1_4.slice({"layer": 0}) + assert single_layer.axes == (Head,) + single_layer[{"head": 0}] = 7.0 + updated = cache_ref.value() + assert updated[{"layer": 1, "head": 0}].array == pytest.approx(7.0) + + +def test_slice_ref_with_dslice(): + Layer = hax.Axis("layer", 10) + Head = hax.Axis("head", 4) + cache_ref = hax.new_ref(hax.zeros((Layer, Head))) + + sub = cache_ref.slice({"layer": hax.ds(3, 3)}) + assert sub.axes == (Layer.resize(3), Head) + + sub[{"layer": 1, "head": slice(None)}] = hax.ones(Head) + + value = cache_ref.value() + assert jnp.allclose(value[{"layer": 4}].array, jnp.ones((Head.size,), dtype=jnp.float32)) + assert isinstance(sub._prefix[0], type(dslice(0, 1))) + + +def test_dslice_combination_branches(): + X = hax.Axis("x", 10) + base = hax.new_ref(hax.arange(X)) + + ds_ref = base.slice({"x": hax.ds(2, 5)}) + + ds_plus_slice = ds_ref.slice({"x": slice(1, 3)}) + prefix = ds_plus_slice._prefix[0] + assert isinstance(prefix, type(dslice(0, 1))) + assert prefix.start == 3 and prefix.size == 2 + + ds_plus_ds = ds_ref.slice({"x": hax.ds(1, 2)}) + prefix = ds_plus_ds._prefix[0] + assert prefix.start == 3 and prefix.size == 2 + + single = ds_ref.slice({"x": 1}) + assert single._prefix[0] == 3 + + neg = ds_ref.slice({"x": -1}) + assert neg._prefix[0] == 6 + + list_ref = ds_ref.slice({"x": [0, 2]}) + assert list_ref._prefix[0] == [2, 4] + + array_ref = ds_ref.slice({"x": jnp.array([0, 1], dtype=jnp.int32)}) + assert jnp.array_equal(array_ref._prefix[0], jnp.array([2, 3])) + + try: + array_reslice = array_ref.slice({"x": jnp.array([0], dtype=jnp.int32)}) + assert array_reslice._prefix[0] == jnp.array([2], dtype=jnp.int32) + except NotImplementedError: + # Advanced indexing on advanced indexing is not supported yet. + pass + + Sel = hax.Axis("sel", 2) + named_idx = hax.arange(Sel).astype(jnp.int32) + named_ref = ds_ref.slice({"x": named_idx}) + assert isinstance(named_ref._prefix[0], hax.NamedArray) + assert jnp.array_equal(named_ref._prefix[0].array, jnp.array([2, 3])) + + try: + named_reslice = named_ref.slice({"x": hax.NamedArray(jnp.array([1], dtype=jnp.int32), (Sel.resize(1),))}) + assert isinstance(named_reslice._prefix[0], hax.NamedArray) + assert jnp.array_equal(named_reslice._prefix[0].array, jnp.array([3])) + except NotImplementedError: + # Advanced indexing on advanced indexing is not supported yet. + pass + + strided = base.slice({"x": slice(1, 9, 2)}) + strided_sub = strided.slice({"x": slice(1, 3)}) + strided_prefix = strided_sub._prefix[0] + assert (strided_prefix.start, strided_prefix.size, strided_prefix.stride) == (3, 2, 2) + + strided_list = strided.slice({"x": [0, 1]}) + assert strided_list._prefix[0] == [1, 3] + + strided_array = strided.slice({"x": jnp.array([0, 1], dtype=jnp.int32)}) + assert jnp.array_equal(strided_array._prefix[0], jnp.array([1, 3])) + + Sel2 = hax.Axis("sel2", 2) + named_idx2 = hax.arange(Sel2).astype(jnp.int32) + strided_named = strided.slice({"x": named_idx2}) + assert isinstance(strided_named._prefix[0], hax.NamedArray) + assert jnp.array_equal(strided_named._prefix[0].array, jnp.array([1, 3])) + + +def test_slice_value_and_unsliced(): + X = hax.Axis("x", 6) + Y = hax.Axis("y", 3) + base = hax.new_ref(hax.arange((X, Y))) + + slice_ref = base.slice({"x": slice(2, 5)}) + slice_value = slice_ref.value() + expected = base.value()[{"x": slice(2, 5)}] + assert jnp.allclose(slice_value.array, expected.array) + assert slice_value.axes == expected.axes + + slice_ref[{"x": 0}] = hax.zeros(Y).astype(slice_ref.dtype) + assert jnp.allclose(base.value()[{"x": 2}].array, hax.zeros(Y).array) + + unsliced = slice_ref.unsliced() + assert unsliced is not slice_ref + assert unsliced.axes == base.axes + assert jnp.allclose(unsliced.value().array, base.value().array) + assert unsliced._prefix == tuple(slice(None) for _ in base.axes) + assert unsliced._ref is base._ref + + +def test_freeze_returns_named_array(): + X = hax.Axis("x", 3) + ref = hax.new_ref(hax.arange(X)) + frozen = hax.freeze(ref) + assert isinstance(frozen, hax.NamedArray) + assert frozen.axes == ref.axes + assert jnp.allclose(frozen.array, ref.value().array) + + +def test_swap_returns_previous_value(): + X = hax.Axis("x", 4) + ref = hax.new_ref(hax.zeros(X)) + prev = hax.swap(ref, {"x": slice(1, 3)}, hax.ones(X.resize(2))) + assert isinstance(prev, hax.NamedArray) + assert prev.axes == (X.resize(2),) + assert jnp.allclose(prev.array, 0.0) + assert jnp.allclose(ref.value()[{"x": slice(1, 3)}].array, jnp.ones((2,), dtype=jnp.float32)) + + +def test_named_ref_jit_plumbing(): + X = hax.Axis("x", 5) + ref = hax.new_ref(hax.zeros(X)) + + @jax.jit + def write_and_read(ref): + ref[{"x": 1}] = 4.2 + return ref[{"x": 1}] + + out = write_and_read(ref) + assert isinstance(out, hax.NamedArray) + assert out.axes == () + assert pytest.approx(out.array.item()) == 4.2 + assert jnp.allclose(ref.value()[{"x": 1}].array, jnp.asarray(4.2)) + + +def test_named_ref_is_pytree_leaf(): + X = hax.Axis("x", 3) + ref = hax.new_ref(hax.zeros(X)) + + leaves = jax.tree_util.tree_leaves(ref) + assert len(leaves) == 1 + assert leaves[0] is ref._ref + + structure = jax.tree_util.tree_structure(ref) + rebuilt = jax.tree_util.tree_unflatten(structure, leaves) + + assert isinstance(rebuilt, hax.NamedRef) + assert rebuilt.axes == ref.axes + assert rebuilt._prefix == ref._prefix + + +def test_with_scan(): + X = hax.Axis("x", 5) + ref = hax.new_ref(hax.zeros(X)) + + @jax.jit + def foo(ref, xs): + def scan_fn(_, x): + ref_slice = ref.slice({"x": x}) + ref_slice[...] = (x * x).astype(ref_slice.dtype) + return None, x * 2 + + return hax.scan(scan_fn, X)(None, xs)[1] + + out = foo(ref, jnp.arange(X.size)) + + assert jnp.all(ref.value().array == jnp.arange(X.size) ** 2) + + assert jnp.all(out == jnp.arange(X.size) * 2) + + +def test_grad_scan(): + X = hax.Axis("x", 4) + + def f(x): + x_ref = hax.new_ref(hax.zeros(X)) + + def scan_fn(_, i): + slice = x_ref.slice({"x": i}) + slice[...] = jnp.sin(x * i) + return None, None + + hax.scan(scan_fn, X)(None, jnp.arange(X.size)) + return x_ref[...].sum().scalar() + + df = jax.grad(f)(1.0) + assert pytest.approx(df) == jnp.sum(jnp.cos(jnp.arange(X.size)) * jnp.arange(X.size)) commit 7e96b90f61c252c88f1aa623e43a180782b08762 Date: 2025-10-17T21:26:55-07:00 fix imports for newer safetensors diff --git a/src/haliax/_src/state_dict.py b/src/haliax/_src/state_dict.py index 6e1ddf0..e58bbc1 100644 --- a/src/haliax/_src/state_dict.py +++ b/src/haliax/_src/state_dict.py @@ -26,8 +26,10 @@ from haliax.tree_util import scan_aware_tree_map try: import safetensors + import safetensors.numpy as safetensors_numpy except ImportError: safetensors = None + safetensors_numpy = None StateDict = dict[str, Any] @@ -436,7 +438,9 @@ def save_state_dict(state_dict: StateDict, path): state_dict = {k: v for k, v in state_dict.items() if v is not None} if jax.process_index() == 0: # the "pt" is a lie but it doesn't seem to actually matter and HF demands it - safetensors.numpy.save_file(state_dict, path, metadata={"format": "pt"}) + if safetensors_numpy is None: + raise ImportError("safetensors_numpy is not installed") + safetensors_numpy.save_file(state_dict, path, metadata={"format": "pt"}) global _GLOBAL_SAVE_COUNT sync_global_devices(f"save_state_dict {_GLOBAL_SAVE_COUNT}") _GLOBAL_SAVE_COUNT += 1 @@ -447,5 +451,7 @@ def load_state_dict(path): Load a model's state dict from a file, bringing all tensors to the CPU first and then converting to numpy. This will load using safetensors format """ - state_dict = safetensors.numpy.load_file(path) + if safetensors_numpy is None: + raise ImportError("safetensors_numpy is not installed") + state_dict = safetensors_numpy.load_file(path) return state_dict commit 968ea2a6360d5c351c8cfcd2dfbafd6a6238cf84 Date: 2025-10-17T21:37:02-07:00 update safetensors reference diff --git a/pyproject.toml b/pyproject.toml index d0b694e..bc14a9b 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -45,6 +45,7 @@ dev = [ "pymdown-extensions", "pygments", "chex>=0.1.86", + "safetensors>=0.4.3", "pre-commit", ] diff --git a/tests/test_state_dict.py b/tests/test_state_dict.py index c72df79..d565542 100644 --- a/tests/test_state_dict.py +++ b/tests/test_state_dict.py @@ -9,13 +9,14 @@ from typing import Any import equinox as eqx import jax import jax.numpy as jnp +import numpy as np import pytest import haliax as hax from haliax._src.state_dict import flatten_modules_for_export, unflatten_modules_from_export from haliax.nn import Linear from haliax.nn.scan import Stacked, _stack_state_dict, _unstack_state_dict -from haliax.state_dict import from_state_dict, to_state_dict +from haliax.state_dict import from_state_dict, load_state_dict, save_state_dict, to_state_dict @pytest.mark.parametrize("out_dims_first", [True, False]) @@ -159,6 +160,44 @@ def test_export_layer_norm(): assert layer_norm == new_layer_norm +def test_save_state_dict_roundtrip(tmp_path): + pytest.importorskip("safetensors.numpy") + state_dict = { + "weight": np.arange(6, dtype=np.float32).reshape(2, 3), + "bias": np.linspace(0.0, 1.0, 3, dtype=np.float32), + } + path = tmp_path / "state.safetensors" + + save_state_dict(state_dict, path) + + assert path.exists() + loaded = load_state_dict(path) + + assert set(loaded.keys()) == {"weight", "bias"} + np.testing.assert_array_equal(loaded["weight"], state_dict["weight"]) + np.testing.assert_array_equal(loaded["bias"], state_dict["bias"]) + + +def test_save_state_dict_filters_none_and_sets_metadata(tmp_path): + safetensors = pytest.importorskip("safetensors") + + state_dict = { + "weight": np.ones((4,), dtype=np.float32), + "optional": None, + } + path = tmp_path / "state.safetensors" + + save_state_dict(state_dict, path) + + with safetensors.safe_open(str(path), framework="numpy") as f: + keys = list(f.keys()) + + assert "weight" in keys + assert "optional" not in keys + np.testing.assert_array_equal(f.get_tensor("weight"), state_dict["weight"]) + assert f.metadata().get("format") == "pt" + + def test_stacked_layer_norm(): L = hax.Axis("L", 4) D = hax.Axis("D", 10) diff --git a/uv.lock b/uv.lock index ccb4dcf..63cafc6 100644 --- a/uv.lock +++ b/uv.lock @@ -315,6 +315,7 @@ dev = [ { name = "pygments" }, { name = "pymdown-extensions" }, { name = "pytest" }, + { name = "safetensors" }, ] [package.metadata] @@ -342,6 +343,7 @@ dev = [ { name = "pygments" }, { name = "pymdown-extensions" }, { name = "pytest", specifier = ">=7.4.0" }, + { name = "safetensors", specifier = ">=0.4.3" }, ] [[package]] commit 4de419c5773eb91a62838f8a460c7ddfb08474a1 Date: 2025-10-18T00:09:28-07:00 fix None in Linear diff --git a/src/haliax/nn/linear.py b/src/haliax/nn/linear.py index e9c4781..346ca42 100644 --- a/src/haliax/nn/linear.py +++ b/src/haliax/nn/linear.py @@ -158,12 +158,15 @@ class Linear(ModuleWithStateDictSerialization, ReparamEnabled): return self.weight.axes[-len(self.Out) :] != self.Out def to_state_dict(self, prefix: Optional[str] = None) -> StateDict: - scaled = dataclasses.replace(self, weight=self.weight * self.reparam.active_scale) + # weight can be None for certain filtering things like LoRA + scaled = dataclasses.replace(self, weight=self.weight * self.reparam.active_scale if self.weight is not None else None) return default_eqx_module_to_state_dict(scaled, prefix) def from_state_dict(self: Mod, state_dict: StateDict, prefix: Optional[str] = None) -> Mod: unscaled = default_eqx_module_from_state_dict(self, state_dict, prefix) - return dataclasses.replace(unscaled, weight=unscaled.weight / self.reparam.active_scale) + if unscaled.weight is not None: + unscaled = dataclasses.replace(unscaled, weight=unscaled.weight / self.reparam.active_scale) + return unscaled @staticmethod def input_reparam(use_mup: bool = True) -> type[AbstractLinearReparam]: commit 90cf1a26d9269c770421956a454b4ee9338ea147 Date: 2025-11-08T11:04:00-05:00 `pre-commit` lint fixes diff --git a/src/haliax/nn/linear.py b/src/haliax/nn/linear.py index 346ca42..d91292b 100644 --- a/src/haliax/nn/linear.py +++ b/src/haliax/nn/linear.py @@ -159,12 +159,14 @@ class Linear(ModuleWithStateDictSerialization, ReparamEnabled): def to_state_dict(self, prefix: Optional[str] = None) -> StateDict: # weight can be None for certain filtering things like LoRA - scaled = dataclasses.replace(self, weight=self.weight * self.reparam.active_scale if self.weight is not None else None) + scaled = dataclasses.replace( + self, weight=self.weight * self.reparam.active_scale if self.weight is not None else None + ) return default_eqx_module_to_state_dict(scaled, prefix) def from_state_dict(self: Mod, state_dict: StateDict, prefix: Optional[str] = None) -> Mod: unscaled = default_eqx_module_from_state_dict(self, state_dict, prefix) - if unscaled.weight is not None: + if unscaled.weight is not None: unscaled = dataclasses.replace(unscaled, weight=unscaled.weight / self.reparam.active_scale) return unscaled commit 280f49fb560f488063efd483b704172ca05b6476 Date: 2025-11-08T08:38:36-08:00 Merge pull request #227 from marin-community/rw/lint `pre-commit` lint fixes