Coverage for src/bartz/_jaxext/_jaxext.py: 98%
373 statements
« prev ^ index » next coverage.py v7.17.0, created at 2026-11-30 12:50 +0000
« prev ^ index » next coverage.py v7.17.0, created at 2026-11-30 12:50 +0000
1# bartz/src/bartz/_jaxext/_jaxext.py
2#
3# Copyright (c) 2024-2026, The Bartz Contributors
4#
5# This file is part of bartz.
6#
7# Permission is hereby granted, free of charge, to any person obtaining a copy
8# of this software and associated documentation files (the "Software"), to deal
9# in the Software without restriction, including without limitation the rights
10# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
11# copies of the Software, and to permit persons to whom the Software is
12# furnished to do so, subject to the following conditions:
13#
14# The above copyright notice and this permission notice shall be included in all
15# copies or substantial portions of the Software.
16#
17# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
18# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
19# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
20# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
21# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
22# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
23# SOFTWARE.
25"""Implementation of miscellaneous jax extension utilities."""
27import inspect
28import math
29import os
30import re
31import sys
32from collections.abc import Callable, Generator, Sequence
33from contextlib import AbstractContextManager, contextmanager, nullcontext
34from functools import partial, wraps
35from pathlib import Path
36from typing import Any, NamedTuple, ParamSpec, TypeVar
38import jax
39from equinox import tree_at
40from jax import (
41 Device,
42 ShapeDtypeStruct,
43 ensure_compile_time_eval,
44 eval_shape,
45 lax,
46 random,
47 shard_map,
48 tree,
49 vmap,
50)
51from jax import numpy as jnp
52from jax.custom_batching import custom_vmap
53from jax.dtypes import prng_key
54from jax.extend.backend import backends
55from jax.scipy.special import ndtr, ndtri
56from jax.sharding import PartitionSpec
57from jax.tree_util import keystr
58from jax.typing import DTypeLike
59from jaxtyping import (
60 Array,
61 Bool,
62 Float32,
63 Int32,
64 Integer,
65 Key,
66 PyTree,
67 Scalar,
68 ScalarLike,
69 Shaped,
70 UInt,
71)
72from jaxtyping import config as jaxtyping_config
74from bartz._jaxext._autobatch import vary, varying_axes
75from bartz._jaxext._equinox import Module
76from bartz._jaxext._jit import jit
78if sys.version_info >= (3, 13):
79 from typing import TypeIs
80else: # WORKAROUND(python<3.13): typing.TypeIs was added in 3.13
81 from typing_extensions import TypeIs
83# the private context manager sets the flag per thread, while the public
84# `jax.config.update` sets it globally, so a context manager built on the
85# latter would not be thread-safe
86try:
87 from jax._src.config import explicit_x64_dtypes
88except ImportError: # private jax API, used only as a safety net in `forbid_x64`
90 def explicit_x64_dtypes(_mode: str) -> AbstractContextManager[None]:
91 """Do nothing in place of the missing jax context manager."""
92 return nullcontext()
95_P = ParamSpec('_P')
96_R = TypeVar('_R')
97_T = TypeVar('_T')
98C = TypeVar('C')
99S = TypeVar('S')
100X = TypeVar('X')
101Y = TypeVar('Y')
104@contextmanager
105def jaxtyping_disabled() -> Generator[None, None, None]:
106 """Temporarily disable jaxtyping runtime type-checking.
108 This also disables `beartype`, because the jaxtyping import hook applies it
109 as ``jaxtyped(typechecker=beartype)`` and `jaxtyped` short-circuits to the
110 undecorated function when type-checking is disabled. Used to park
111 deliberately wrong-typed intermediates (e.g. `_LazyArray` leaves) in an
112 `equinox.Module` during construction.
113 """
114 old = jaxtyping_config.jaxtyping_disable
115 jaxtyping_config.update('jaxtyping_disable', True)
116 try:
117 yield
118 finally:
119 jaxtyping_config.update('jaxtyping_disable', old)
122def float32_matmuls(fun: Callable[_P, _R]) -> Callable[_P, _R]:
123 """Run/trace `fun` under full-float32 matmul precision."""
125 @wraps(fun)
126 def wrapper(*args: _P.args, **kw: _P.kwargs) -> _R:
127 with jax.default_matmul_precision('float32'):
128 return fun(*args, **kw)
130 return wrapper
133_X64_DTYPES = frozenset(
134 map(jnp.dtype, (jnp.float64, jnp.int64, jnp.uint64, jnp.complex128))
135)
138def forbid_x64(fun: Callable[_P, _R]) -> Callable[_P, _R]:
139 """Make `fun` raise an error on 64-bit types.
141 Raises if ``jax_enable_x64`` is set or an argument contains a 64-bit jax
142 array, and runs/traces `fun` with ``jax_explicit_x64_dtypes='error'``, so
143 that jax raises on most operations involving 64-bit arrays. Combined with
144 `jit`, put it inside, to keep the methods of the jitted function.
146 User code called by `fun` can still use 64-bit types within
147 ``jax.enable_x64(True)``; the error raised by jax gets a note saying so.
148 """
149 signature = inspect.signature(fun)
151 @wraps(fun)
152 def wrapper(*args: _P.args, **kw: _P.kwargs) -> _R:
153 if jax.config.jax_enable_x64:
154 msg = (
155 'bartz does not support 64-bit types, but `jax_enable_x64` is '
156 'set. Disable it, or call bartz within `with jax.enable_x64(False):`.'
157 )
158 raise RuntimeError(msg)
159 for name, value in signature.bind(*args, **kw).arguments.items():
160 for path, x in tree.leaves_with_path(value):
161 if isinstance(x, jax.Array) and x.dtype in _X64_DTYPES:
162 msg = (
163 'bartz does not support 64-bit types, but '
164 f'`{name}{keystr(path)}` has dtype {x.dtype}. '
165 'Convert it to 32 bit.'
166 )
167 raise TypeError(msg)
168 with explicit_x64_dtypes('error'):
169 try:
170 return fun(*args, **kw)
171 except ValueError as exc:
172 note = (
173 'bartz does not support 64-bit types. To use them in your '
174 'own code called by bartz, e.g., a callback, wrap it in '
175 '`with jax.enable_x64(True):` and convert the results to 32 '
176 'bit within the block.'
177 )
178 notes = getattr(exc, '__notes__', ())
179 if 'Explicitly requested dtype' in str(exc) and note not in notes:
180 exc.add_note(note)
181 raise
183 return wrapper
186def sliced_map(
187 f: Callable[[PyTree[Array, ' I']], PyTree[Array, ' O']],
188 xs: PyTree[Array, ' I'],
189 *,
190 batch_size: int,
191) -> PyTree[Array, ' O']:
192 """
193 Like `jax.lax.map` with `batch_size`, but read `xs` by slicing.
195 The scan body slices each batch out of the closed-over `xs` with
196 `lax.dynamic_slice_in_dim` instead of consuming `xs` reshaped into scan xs.
197 Under `vmap`, the batching rule for values closed over by a scan moves the
198 batch axes to the front, so leading batch axes in the leaves of `xs` are
199 consumed in place, while `lax.map` would transpose them to sit after the
200 scanned and `batch_size` axes.
202 Parameters
203 ----------
204 f
205 The function to apply elementwise, taking and returning pytrees of
206 arrays.
207 xs
208 A pytree of arrays to map over along their first axes.
209 batch_size
210 The number of elements to process at a time, vectorized. The remainder
211 of the division of the number of elements by `batch_size` is processed
212 as one additional smaller batch.
214 Returns
215 -------
216 A pytree of stacked outputs of `f`, like `jax.lax.map`.
217 """
218 (num_el,) = {x.shape[0] for x in tree.leaves(xs)}
220 # shortcut if no batching needed
221 if batch_size >= num_el:
222 return vmap(f)(xs)
224 num_batches, remainder = divmod(num_el, batch_size)
226 def apply_batch(start: Integer[Array, ''] | int, size: int) -> PyTree[Array, ' O']:
227 def slice_batch(
228 x: Shaped[Array, ' num_el *shape'],
229 ) -> Shaped[Array, ' size *shape']:
230 return lax.dynamic_slice_in_dim(x, start, size, axis=0)
232 return vmap(f)(tree.map(slice_batch, xs))
234 def loop(_: None, start: Integer[Array, '']) -> tuple[None, PyTree[Array, ' O']]:
235 return None, apply_batch(start, batch_size)
237 _, out = lax.scan(loop, None, batch_size * jnp.arange(num_batches))
238 out = tree.map(lambda x: x.reshape(num_batches * batch_size, *x.shape[2:]), out)
239 if remainder:
240 start = num_batches * batch_size
241 # WORKAROUND(jax<0.12.1): with more cpu devices, a program loaded from
242 # the compilation cache may run the collectives in the loop and in the
243 # remainder at the same time, and crash. The barrier does not order
244 # them, it only changes what xla compiles, to a program that did not
245 # crash in the cases tried.
246 # WORKAROUND(jax<0.11.1): the outputs of a barrier vary over the manual
247 # axes of all its operands, which changes the type of `out`, so do
248 # without; once unsupported, drop the condition
249 if jax.__version_info__ >= (0, 11, 1):
250 out, start = lax.optimization_barrier((out, start))
251 rest = apply_batch(start, remainder)
252 out = tree.map(lambda x, y: jnp.concatenate([x, y], axis=0), out, rest)
253 return out
256def minimal_unsigned_dtype(value: int) -> DTypeLike:
257 """Return the smallest unsigned integer dtype that can represent `value`."""
258 if value < 2**8:
259 return jnp.uint8
260 if value < 2**16:
261 return jnp.uint16
262 if value < 2**32: 262 ↛ 264line 262 didn't jump to line 264 because the condition on line 262 was always true
263 return jnp.uint32
264 return jnp.uint64
267def minimal_unsigned_arange(size: int) -> UInt[Array, ' {size}']:
268 """Return the integers below `size` in the smallest unsigned integer dtype."""
269 return jnp.arange(size, dtype=minimal_unsigned_dtype(size - 1))
272@jit(static_argnums=(1,))
273def unique(
274 x: Shaped[Array, ' _'], size: int, fill_value: ScalarLike
275) -> tuple[Shaped[Array, ' {size}'], int | Integer[Array, '']]:
276 """
277 Restricted version of `jax.numpy.unique` that uses less memory.
279 Parameters
280 ----------
281 x
282 The input array.
283 size
284 The length of the output.
285 fill_value
286 The value to fill the output with if `size` is greater than the number
287 of unique values in `x`.
289 Returns
290 -------
291 out : Shaped[Array, '{size}']
292 The unique values in `x`, sorted, and right-padded with `fill_value`.
293 actual_length : int
294 The number of used values in `out`.
295 """
296 if x.size == 0:
297 return jnp.full(size, fill_value, x.dtype), 0
298 if size == 0:
299 return jnp.empty(0, x.dtype), 0
300 x = jnp.sort(x)
302 def loop(
303 carry: tuple[Scalar, Scalar, Shaped[Array, ' size']], x: Scalar
304 ) -> tuple[tuple[Scalar, Scalar, Shaped[Array, ' size']], None]:
305 i_out, last, out = carry
306 i_out = jnp.where(x == last, i_out, i_out + 1)
307 out = out.at[i_out].set(x)
308 return (i_out, x, out), None
310 carry = jnp.array(0), x[0], jnp.full(size, fill_value, x.dtype)
312 def run(unroll: int) -> tuple[Shaped[Array, ' size'], Scalar]:
313 (actual_length, _, out), _ = lax.scan(loop, carry, x[:size], unroll=unroll)
314 return out, actual_length + 1
316 # The optimal scan unroll is opposite on cpu and gpu (benchmarked):
317 # - gpu: the loop is dominated by per-step overhead, so a large unroll is up
318 # to ~6x faster; the run time plateaus by ~32 while compile time then grows
319 # steeply, so 32 is the sweet spot.
320 # - cpu: past ~6 the backend stops aliasing `out` in place and copies the
321 # size-`size` buffer each step (O(size**2), ~100x slower), so 2 is safest.
322 # `default` (cpu, tpu, untested backends) takes the conservative value.
323 return lax.platform_dependent(
324 cuda=partial(run, 32), rocm=partial(run, 32), default=partial(run, 2)
325 )
328class split:
329 """
330 Split a key into `num` keys.
332 Parameters
333 ----------
334 key
335 The key to split.
336 num
337 The number of keys to split into.
338 """
340 _keys: tuple[Key[Array, ''], ...]
341 _num_used: int
343 def __init__(self, key: Key[Array, ''], num: int = 2) -> None:
344 self._keys = _split_unpack(key, num)
345 self._num_used = 0
347 def __len__(self) -> int:
348 return len(self._keys) - self._num_used
350 def pop(self, shape: int | tuple[int, ...] = ()) -> Key[Array, ' *shape']:
351 """
352 Pop one or more keys from the list.
354 Parameters
355 ----------
356 shape
357 The shape of the keys to pop. If empty (default), a single key is
358 popped and returned. If not empty, the popped key is split and
359 reshaped to the target shape.
361 Returns
362 -------
363 The popped keys as a jax array with the requested shape.
365 Raises
366 ------
367 IndexError
368 If the list is empty.
369 """
370 if len(self) == 0:
371 msg = 'No keys left to pop'
372 raise IndexError(msg)
373 if not isinstance(shape, tuple):
374 shape = (shape,)
375 key = self._keys[self._num_used]
376 self._num_used += 1
377 if shape:
378 key = _split_shaped(key, shape)
379 return key
382@jit(static_argnums=(1,))
383def _split_unpack(key: Key[Array, ''], num: int) -> tuple[Key[Array, ''], ...]:
384 keys = random.split(key, num)
385 return tuple(keys)
388@jit(static_argnums=(1,))
389def _split_shaped(key: Key[Array, ''], shape: tuple[int, ...]) -> Key[Array, ' *shape']:
390 num = math.prod(shape)
391 keys = random.split(key, num)
392 return keys.reshape(shape)
395def truncated_normal_onesided(
396 key: Key[Array, ''],
397 shape: Sequence[int],
398 upper: Bool[Array, '...'],
399 bound: Float32[Array, '...'],
400 *,
401 clip: bool = True,
402) -> Float32[Array, '...']:
403 """
404 Sample from a one-sided truncated standard normal distribution.
406 Parameters
407 ----------
408 key
409 JAX random key.
410 shape
411 Shape of output array, broadcasted with other inputs.
412 upper
413 True for (-∞, bound], False for [bound, ∞).
414 bound
415 The truncation boundary.
416 clip
417 Whether to clip the samples to keep them finite and within the
418 truncation region. Leave on, off only for debugging.
420 Returns
421 -------
422 Array of samples from the truncated normal distribution.
423 """
424 # Pseudocode:
425 # | if upper:
426 # | if bound < 0:
427 # | ndtri(uniform(0, ndtr(bound))) =
428 # | ndtri(ndtr(bound) * u)
429 # | if bound > 0:
430 # | -ndtri(uniform(ndtr(-bound), 1)) =
431 # | -ndtri(ndtr(-bound) + ndtr(bound) * (1 - u))
432 # | if not upper:
433 # | if bound < 0:
434 # | ndtri(uniform(ndtr(bound), 1)) =
435 # | ndtri(ndtr(bound) + ndtr(-bound) * (1 - u))
436 # | if bound > 0:
437 # | -ndtri(uniform(0, ndtr(-bound))) =
438 # | -ndtri(ndtr(-bound) * u)
439 shape = jnp.broadcast_shapes(shape, upper.shape, bound.shape)
440 bound_pos = bound > 0
441 ndtr_bound = ndtr(bound)
442 ndtr_neg_bound = ndtr(-bound)
443 scale = jnp.where(upper, ndtr_bound, ndtr_neg_bound)
444 shift = jnp.where(upper, ndtr_neg_bound, ndtr_bound)
445 u = random.uniform(key, shape)
446 left_u = scale * (1 - u) # ~ uniform in (0, ndtr(±bound)]
447 right_u = shift + scale * u # ~ uniform in [ndtr(∓bound), 1)
448 truncated_u = jnp.where(upper ^ bound_pos, left_u, right_u)
449 if clip:
450 # `truncated_u` can reach 0 or 1, where ndtri is infinite: ndtr(±bound)
451 # underflows for extreme bounds, u can come out exactly 0, and on gpu the
452 # accuracy is lower. The lower target is the smallest normal number rather
453 # than the smallest subnormal one because xla flushes subnormals to zero on
454 # cpu, and ndtri is -inf on subnormals anyway.
455 zero = jnp.zeros((), truncated_u.dtype)
456 one = jnp.ones((), truncated_u.dtype)
457 smallest_normal = jnp.finfo(truncated_u.dtype).smallest_normal
458 truncated_u = jnp.clip(truncated_u, smallest_normal, jnp.nextafter(one, zero))
459 truncated_norm = ndtri(truncated_u)
460 sample = jnp.where(bound_pos, -truncated_norm, truncated_norm)
461 if clip:
462 # the clip above caps |sample| at ndtri of the target, ~12.9 in float32,
463 # which for extreme bounds falls short of the truncation region, and
464 # rounding can put the sample a ulp on the wrong side anyway. Move it onto
465 # the boundary, where the distribution concentrates for such bounds (its
466 # mean is bound + 1/bound).
467 sample = jnp.where(
468 upper, jnp.minimum(sample, bound), jnp.maximum(sample, bound)
469 )
470 return sample
473def get_default_device() -> Device:
474 """Get the current default JAX device."""
475 with ensure_compile_time_eval():
476 return jnp.empty(0).device
479def get_default_devices() -> list[Device]:
480 """Get all JAX devices on the default platform."""
481 return jax.devices(get_default_device().platform)
484def get_device_count() -> int:
485 """Get the number of available devices on the default platform."""
486 return len(get_default_devices())
489def get_cpu_thread_count() -> int | None:
490 """Get the number of threads xla uses on cpu, `None` without a cpu backend.
492 Xla does not expose the count, so this replicates how xla sets it.
493 """
494 # the first of these environment variables that is an integer replaces the
495 # number of cpus available to the process
496 env = (os.environ.get(name, '') for name in ('PJRT_NPROC', 'NPROC'))
497 env = [int(value) for value in env if re.fullmatch(r'\s*[+-]?\d+\s*', value)]
498 if env:
499 count = env[0]
500 elif hasattr(os, 'sched_getaffinity'): 500 ↛ 503line 500 didn't jump to line 503 because the condition on line 500 was always true
501 count = len(os.sched_getaffinity(0))
502 else:
503 count = os.cpu_count() or 1
504 if 'cpu' in backends():
505 # there is at least one thread per device
506 return max(count, jax.local_device_count('cpu'))
507 else:
508 return None
511def get_available_cpu_count() -> int:
512 """Get the number of cpus the process can use, accounting for cgroup quotas."""
513 # WORKAROUND(python<3.13): keep only the `os.process_cpu_count()` branch
514 if sys.version_info >= (3, 13):
515 count = os.process_cpu_count()
516 elif hasattr(os, 'sched_getaffinity'): 516 ↛ 519line 516 didn't jump to line 519 because the condition on line 516 was always true
517 count = len(os.sched_getaffinity(0))
518 else:
519 count = os.cpu_count()
520 count = count or 1
521 quota = get_cgroup_cpu_quota()
522 if quota is not None:
523 count = min(count, math.ceil(quota))
524 return count
527def get_cgroup_cpu_quota(root: Path = Path('/sys/fs/cgroup')) -> float | None:
528 """Get the cpu quota of the cgroup of the process, `None` if unlimited.
530 Reads the root of the cgroup mount, which in a container is the container's
531 cgroup.
532 """
533 v2 = root / 'cpu.max'
534 v1 = root / 'cpu' / 'cpu.cfs_quota_us'
535 if v2.is_file():
536 quota, period = v2.read_text().split()
537 elif v1.is_file():
538 quota = v1.read_text().strip()
539 period = (root / 'cpu' / 'cpu.cfs_period_us').read_text()
540 else:
541 # no cpu controller, so no limit
542 quota, period = 'max', ''
543 # v2 writes 'max' and v1 writes -1 for no limit
544 if quota in ('max', '-1'):
545 return None
546 else:
547 return int(quota) / int(period)
550def is_key(x: object) -> TypeIs[Key[Array, ' *shape']]:
551 """Determine if `x` is a jax random key."""
552 return isinstance(x, Array) and jnp.issubdtype(x.dtype, prng_key)
555def jit_active() -> bool:
556 """Check if we are under jit."""
557 return not hasattr(jnp.empty(0), 'platform')
560def cpu_barrier(x: _T) -> _T:
561 """Apply `lax.optimization_barrier` on cpu only, to steer xla:cpu fusion."""
562 return lax.platform_dependent(x, cpu=lax.optimization_barrier, default=lambda x: x)
565@custom_vmap
566def vmap_max(x: Integer[Array, '']) -> Integer[Array, '']:
567 """Take the maximum over the axes of the enclosing vmaps, if any.
569 Parameters
570 ----------
571 x
572 A non-negative integer.
574 Returns
575 -------
576 The maximum of `x` over the batch, `x` itself if not vmapped, 0 if the batch is empty.
578 Notes
579 -----
580 This is a workaround for collectives over vmap named axes not working under
581 `jax.shard_map`, see jax issue #42649. Used by `variable_length_scan` and
582 `variable_length_update`.
583 """
584 return x
587@vmap_max.def_vmap
588def vmap_max_rule(
589 axis_size: int, # noqa: ARG001
590 in_batched: Sequence[bool],
591 x: Integer[Array, ' batch'],
592) -> tuple[Integer[Array, ''], bool]:
593 # jax calls the rule only if some argument is batched, here the only one
594 (batched,) = in_batched
595 assert batched
596 # the max is batched as usual by any outer vmap, so apply again to reduce it
597 return vmap_max(jnp.max(x, axis=0, initial=0)), False
600class InPlace(Module):
601 """An element of a batched array, that reads the whole array when indexed.
603 It supports only indexing, see `sequential_vmap`.
604 """
606 array: Shaped[Array, ' batch *shape']
607 """The whole batched array."""
609 index: Int32[Array, '']
610 """The index of the element along the leading axis of `array`."""
612 def __getitem__(self, key: object) -> Shaped[Array, '...']:
613 key = key if isinstance(key, tuple) else (key,)
614 return self.array[(self.index, *key)]
617# the arguments are not typed with a `ParamSpec`, because jax passes them to the
618# batching rule as an untyped tuple
619def sequential_vmap(
620 f: Callable[..., _R],
621 *,
622 in_place: Callable[..., tuple[Array, ...] | Array] | None = None,
623) -> Callable[..., _R]:
624 """
625 Like `jax.custom_batching.sequential_vmap`, but with some arguments read in place.
627 Parameters
628 ----------
629 f
630 The function to apply, with positional arguments only.
631 in_place
632 Takes the arguments of `f` and returns the arrays, or a tuple of
633 arrays, to read in place. "In place" means that instead of slicing the
634 array to pass it to `f`, the full unsliced array is wrapped as an
635 `InPlace` object that's passed to `f`.
637 Returns
638 -------
639 `f`, with a sequential batching rule.
641 Notes
642 -----
643 The purpose of this function is to avoid redundant copies of arrays in the
644 case where an argument to `f` is passed into a loop (e.g.,
645 `lax.while_loop`) inside `f`, which forces the materialization of the slice
646 of the array.
647 """
648 g = custom_vmap(f)
650 @g.def_vmap
651 def rule(
652 axis_size: int, in_batched: Sequence[PyTree[bool]], *args: Any
653 ) -> tuple[_R, PyTree[bool]]:
654 in_batched = tuple(in_batched)
655 if axis_size == 0: 655 ↛ 662line 655 didn't jump to line 662 because the condition on line 655 was always true
656 # shortcut because `InPlace` does not support empty batch axis, so
657 # `lax.map`'s own shortcut would not work on our wrapped function
658 in_axes = tree.map(lambda batched: 0 if batched else None, in_batched)
659 out = vmap(f, in_axes=in_axes)(*args)
660 return out, tree.map(lambda _: True, out)
662 def wrapped_in_place(args: tuple) -> PyTree:
663 # `tree_at` passes the arguments as one tuple, `in_place` takes
664 # them apart like `f`
665 assert in_place is not None
666 return in_place(*args)
668 if in_place is not None:
669 # the arrays read in place are not sliced
670 in_place_batched = wrapped_in_place(in_batched)
671 in_batched = tree_at(
672 wrapped_in_place, in_batched, replace_fn=lambda _: False
673 )
675 # flatten everything and extract vmapped arguments
676 args_leaves, args_treedef = tree.flatten(args)
677 flat_in_batched = tree.leaves(in_batched)
678 flat_vmapped_args = [
679 x
680 for x, batched in zip(args_leaves, flat_in_batched, strict=True)
681 if batched
682 ]
684 def apply(
685 index_and_vmapped_args: tuple[Int32[Array, ''], Sequence[Array]],
686 ) -> _R:
687 """Apply `InPlace` where needed, then call `f`."""
688 index, flat_vmapped_args_at = index_and_vmapped_args
690 # re-insert unvmapped arguments and unflatten
691 it = iter(flat_vmapped_args_at)
692 args_at = tree.unflatten(
693 args_treedef,
694 [
695 next(it) if batched else x
696 for x, batched in zip(args_leaves, flat_in_batched, strict=True)
697 ],
698 )
700 # apply `InPlace` where `in_place` indicates to do so
701 if in_place is not None:
702 views = tree.map(
703 lambda x, batched: InPlace(x, index) if batched else x,
704 wrapped_in_place(args),
705 in_place_batched,
706 )
707 args_at = tree_at(wrapped_in_place, args_at, views)
709 # call `f`
710 return f(*args_at)
712 out = lax.map(apply, (jnp.arange(axis_size), flat_vmapped_args))
713 return out, tree.map(lambda _: True, out)
715 return g
718def variable_length_scan(
719 f: Callable[[C, X, Bool[Array, ''] | None], tuple[C, Y]],
720 init: C,
721 xs: X,
722 length: Integer[Array, ''] | None = None,
723 *,
724 block_size: int = 1,
725 unroll: int | bool = 1,
726) -> tuple[C, Y]:
727 """
728 Like `jax.lax.scan`, but only over the first `length` elements of `xs`.
730 Parameters
731 ----------
732 f
733 Like the function scanned by `jax.lax.scan`, but with a third argument
734 that says whether the element is within the first `length`. If not,
735 `f` shall return the carry unchanged, and its other output is replaced
736 by zeros. `variable_length_scan` does not undo the carry update itself
737 with a select over the whole carry, because `f` may have a cheaper way,
738 like zeroing a delta before adding it. The argument is `None` if
739 `length` is.
740 init
741 The initial carry.
742 xs
743 The elements to scan over, along the leading axis.
744 length
745 How many elements to scan over (can be larger than the actual length of
746 `xs`, the excess will be skipped). If `None`, all of them, with a loop
747 of fixed length. Under `jax.vmap`, if `length` is batched, the loop
748 runs up to the maximum `length` in the batch, to keep the loop
749 condition unbatched.
750 block_size
751 If `length` is set, the loop condition is evaluated every `block_size`
752 iterations instead of at every iteration. The purpose of this setting
753 is avoiding overhead on gpu due to the condition requiring a host trip.
754 If `block_size` is not a divisor of `length`, the remainder iterations
755 in the last block are run anyway, to avoid double compilation of the
756 loop body.
757 unroll
758 How much to unroll the loop (within each block), passed to `jax.lax.scan`.
760 Returns
761 -------
762 carry : C
763 The final carry.
764 ys : Y
765 The stacked outputs of `f`, zero past `length`.
766 """
767 # extract length of `xs`
768 (len_x,) = {x.shape[0] for x in tree.leaves(xs)}
770 # shortcut through `lax.scan`
771 if length is None or len_x == 0:
772 return lax.scan(lambda carry, x: f(carry, x, None), init, xs, unroll=unroll)
774 # clamp the lengths to the number of elements
775 length = jnp.minimum(length, len_x)
776 block_size = max(1, min(block_size, len_x))
778 # compute number of blocks (in the output, not effectively looped over)
779 num_blocks_out = -(-len_x // block_size)
781 def scan_block(i: Integer[Array, ''] | int, carry: C) -> tuple[C, Y]:
782 """Do `block_size` iterations."""
784 def step(carry: C, j: Int32[Array, '']) -> tuple[C, Y]:
785 """Do a single iteration."""
786 # the elements are indexed out of the closed-over `xs`, instead of
787 # passing the block as scan xs, such that the block is not copied;
788 # the index is clamped in the last block, past `length` anyway
789 position = i * block_size + j
790 x = tree.map(lambda x: dynamic_slice_in_dim(x, position, 1).squeeze(0), xs)
791 valid = position < length
792 carry, y = f(carry, x, valid)
793 # zero the outputs of the elements past `length`, like those of the
794 # blocks never visited, such that they do not depend on
795 # `block_size`, or on the other lengths in a vmap batch
796 return carry, tree.map(lambda y: jnp.where(valid, y, jnp.zeros_like(y)), y)
798 return lax.scan(step, carry, jnp.arange(block_size), unroll=unroll)
800 # Allocate `ys`, the output is written in it block by block. Initialize to
801 # zero because we promise the unused part of the tail to be zero. Match the
802 # sharding of `y` to make the initial loop carry type match the running
803 # loop carry type.
804 _, dummy_y_block = eval_shape(scan_block, 0, init)
805 ys = tree.map(
806 lambda y: zeros_varying_like(y, (num_blocks_out, *y.shape)), dummy_y_block
807 )
809 # compute number of blocks to loop over
810 num_blocks_loop = (vmap_max(length) + block_size - 1) // block_size
812 def cond(state: BlocksLoopState) -> Bool[Array, '']:
813 """Return whether the loop over blocks shall continue."""
814 return state.i_block < num_blocks_loop
816 def body(state: BlocksLoopState) -> BlocksLoopState:
817 """Process one block."""
818 carry, y_block = scan_block(state.i_block, state.carry)
819 ys = tree.map(
820 lambda ys, y: dynamic_update_slice_in_dim(ys, y[None, ...], state.i_block),
821 state.ys,
822 y_block,
823 )
824 return BlocksLoopState(state.i_block + 1, carry, ys)
826 # loop over blocks, squash block axis from the output and return
827 state = lax.while_loop(cond, body, BlocksLoopState(jnp.int32(0), init, ys))
828 ys = tree.map(
829 lambda y: y.reshape(num_blocks_out * block_size, *y.shape[2:])[:len_x, ...],
830 state.ys,
831 )
832 return state.carry, ys
835def dynamic_slice_in_dim(
836 x: Shaped[Array, '...'], start: Integer[Array, ''] | int, size: int, axis: int = 0
837) -> Shaped[Array, '...']:
838 """
839 Like `jax.lax.dynamic_slice_in_dim`, but still a slice under `jax.vmap`.
841 If `start` is not batched, the batching rule slices the batched `x` along
842 the shifted `axis`, while the one of `jax.lax.dynamic_slice_in_dim` turns
843 the slice into a gather.
845 Parameters
846 ----------
847 x
848 The array to slice.
849 start
850 The index of the first element of the slice.
851 size
852 The length of the slice.
853 axis
854 The (non-negative) axis to slice along.
856 Returns
857 -------
858 The slice ``x[..., start : start + size, ...]``.
859 """
861 def lax_take(
862 x: Shaped[Array, '...'], start: Integer[Array, ''] | int
863 ) -> Shaped[Array, '...']:
864 return lax.dynamic_slice_in_dim(x, start, size, axis)
866 take = custom_vmap(lax_take)
868 @take.def_vmap
869 def rule(
870 axis_size: int,
871 in_batched: Sequence[bool],
872 x: Shaped[Array, '...'],
873 start: Integer[Array, '...'] | int, # jax passes a constant as a python scalar
874 ) -> tuple[Shaped[Array, '...'], bool]:
875 del axis_size
877 # jax moves the batch axis of the batched arguments to the front, and
878 # expects it there in the output
879 x_batched, start_batched = in_batched
880 if start_batched:
881 in_axes = (0 if x_batched else None, 0)
882 return vmap(lax_take, in_axes)(x, start), True
883 else:
884 return dynamic_slice_in_dim(x, start, size, axis + 1), True
886 return take(x, start)
889def dynamic_update_slice_in_dim(
890 x: Shaped[Array, '...'],
891 update: Shaped[Array, '...'],
892 start: Integer[Array, ''] | int,
893 axis: int = 0,
894) -> Shaped[Array, '...']:
895 """
896 Like `jax.lax.dynamic_update_slice_in_dim`, but still a slice update under `jax.vmap`.
898 If `start` is not batched, the batching rule updates the batched `x` along
899 the shifted `axis`, while the one of `jax.lax.dynamic_update_slice_in_dim`
900 turns the update into a scatter, that xla does not do in place.
902 Parameters
903 ----------
904 x
905 The array to update.
906 update
907 The values to write, with the shape of `x` but for the length along
908 `axis`.
909 start
910 The index of the first element to overwrite.
911 axis
912 The (non-negative) axis to update along.
914 Returns
915 -------
916 `x` with ``x[..., start : start + update.shape[axis], ...]`` set to `update`.
917 """
919 def lax_put(
920 x: Shaped[Array, '...'],
921 update: Shaped[Array, '...'],
922 start: Integer[Array, ''] | int,
923 ) -> Shaped[Array, '...']:
924 return lax.dynamic_update_slice_in_dim(x, update, start, axis)
926 put = custom_vmap(lax_put)
928 @put.def_vmap
929 def rule(
930 axis_size: int,
931 in_batched: Sequence[bool],
932 x: Shaped[Array, '...'],
933 update: Shaped[Array, '...'],
934 start: Integer[Array, '...'] | int,
935 ) -> tuple[Shaped[Array, '...'], bool]:
936 x_batched, update_batched, start_batched = in_batched
937 if start_batched:
938 in_axes = (0 if x_batched else None, 0 if update_batched else None, 0)
939 return vmap(lax_put, in_axes)(x, update, start), True
940 else:
941 if not x_batched:
942 x = jnp.broadcast_to(x, (axis_size, *x.shape))
943 if not update_batched:
944 update = jnp.broadcast_to(update, (axis_size, *update.shape))
945 return dynamic_update_slice_in_dim(x, update, start, axis + 1), True
947 return put(x, update, start)
950def variable_length_update(
951 update: Callable[[S, X], S],
952 post: Callable[[S, X], Y],
953 state: S,
954 xs: X,
955 length: Integer[Array, ''] | None = None,
956 *,
957 block_size: int | None = None,
958) -> tuple[S, Y]:
959 """
960 Update the first `length` elements of arrays, one block at a time.
962 The semantics are given by this Python implementation, with numpy arrays
963 in place of the pytrees of jax arrays::
965 def variable_length_update(update, post, state, xs, length, block_size):
966 ys = np.zeros_like(post(state, xs))
967 for start in range(0, length, block_size):
968 block = slice(start, start + block_size)
969 state[block] = update(state[block], xs[block])
970 ys[block] = post(state[block], xs[block])
971 ys[length:] = 0
972 return state, ys
974 The number of iterations is set at run time, so the cost scales with
975 `length` while the arrays keep a fixed size, and `state` is overwritten
976 block by block without copying it.
978 Parameters
979 ----------
980 update
981 Computes the new `state`. It shall be vectorized along the leading
982 axis, such that the result does not depend on the blocks.
983 post
984 Computes other outputs from the new `state`, vectorized like `update`.
985 state
986 The arrays to update.
987 xs
988 The other inputs of `update` and `post`.
989 length
990 How many elements to process. If `None`, all of them, at once. Under
991 `jax.vmap`, the loop runs up to the maximum `length` in the batch.
992 block_size
993 The number of elements in a block, a divisor of the number of
994 elements. If `None`, all of them: a single block is processed whole
995 without a loop, whatever the `length`.
997 Returns
998 -------
999 state : S
1000 The updated `state`, left as it was in the blocks not processed.
1001 ys : Y
1002 The outputs of `post`, zero past `length`.
1004 Raises
1005 ------
1006 ValueError
1007 If `block_size` is not a divisor of the number of elements.
1009 Notes
1010 -----
1011 `post` exists, instead of `update` returning the other outputs too, because
1012 xla writes a block back over the old one in place only if nothing else
1013 reads the new block before; `post` reads it after, out of the whole array.
1015 If `block_size` is equal to the number of elements (one block) then
1016 everything is processed even in the ``length == 0`` case.
1017 """
1018 (num_el,) = {x.shape[0] for x in tree.leaves((state, xs))}
1019 if block_size is None:
1020 block_size = num_el
1021 if block_size < 1 or num_el % block_size:
1022 msg = f'{block_size=} is not a divisor of the {num_el} elements'
1023 raise ValueError(msg)
1025 if length is None or block_size == num_el:
1026 # all the elements at once, a single block needs no loop
1027 state = update(state, xs)
1028 ys = post(state, xs)
1029 else:
1030 state, ys = update_blocks(
1031 update, post, state, xs, length, block_size=block_size
1032 )
1034 if length is not None:
1035 # zero the outputs past `length`: the last block processed computes
1036 # them and the blocks after it do not, so they would depend on
1037 # `block_size`, and on the other lengths in a vmap batch
1038 valid = jnp.arange(num_el) < length
1039 ys = tree.map(
1040 lambda y: jnp.where(
1041 valid.reshape(-1, *[1] * (y.ndim - 1)), y, jnp.zeros_like(y)
1042 ),
1043 ys,
1044 )
1046 return state, ys
1049def update_blocks(
1050 update: Callable[[S, X], S],
1051 post: Callable[[S, X], Y],
1052 state: S,
1053 xs: X,
1054 length: Integer[Array, ''],
1055 *,
1056 block_size: int,
1057) -> tuple[S, Y]:
1058 """Implement `variable_length_update` over more than one block."""
1059 (num_el,) = {x.shape[0] for x in tree.leaves((state, xs))}
1061 # Allocate `ys`, the loop writes the outputs in it block by block. Zeros,
1062 # to define the outputs of the blocks not processed. They vary over the
1063 # same mesh axes as the outputs of `post`, for the initial loop carry to
1064 # have the type of the running one.
1065 dummy_ys = eval_shape(lambda: post(update(state, xs), xs))
1066 ys = tree.map(lambda y: zeros_varying_like(y, y.shape), dummy_ys)
1068 # the blocks to process, up to the maximum `length` in a vmap batch to
1069 # keep the loop condition unbatched
1070 num_blocks = -(-jnp.clip(vmap_max(length), 0, num_el) // block_size)
1072 def cond(loop: BlocksLoopState) -> Bool[Array, '']:
1073 return loop.i_block < num_blocks
1075 def body(loop: BlocksLoopState) -> BlocksLoopState:
1076 start = loop.i_block * block_size
1078 def take(
1079 x: Shaped[Array, ' num_el *shape'],
1080 ) -> Shaped[Array, ' block_size *shape']:
1081 return dynamic_slice_in_dim(x, start, block_size)
1083 def put(
1084 x: Shaped[Array, ' num_el *shape'],
1085 block: Shaped[Array, ' block_size *shape'],
1086 ) -> Shaped[Array, ' num_el *shape']:
1087 return dynamic_update_slice_in_dim(x, block, start)
1089 xs_block = tree.map(take, xs)
1090 state = update(tree.map(take, loop.carry), xs_block)
1091 state = tree.map(put, loop.carry, state)
1092 # `post` gets the new block sliced back out of `state`, not the output
1093 # of `update`: read by something else first, xla would not write the
1094 # block in place
1095 ys = tree.map(put, loop.ys, post(tree.map(take, state), xs_block))
1096 return BlocksLoopState(loop.i_block + 1, state, ys)
1098 loop = lax.while_loop(cond, body, BlocksLoopState(jnp.int32(0), state, ys))
1099 return loop.carry, loop.ys
1102# WORKAROUND(beartype<=0.23.1): beartype rejects generic NamedTuple hints
1103# (beartype#748), so `carry` and `ys` are typed as any pytree. Once fixed, make
1104# this `NamedTuple, Generic[C, Y]` and annotate `cond` and `body` in
1105# `variable_length_scan` with `BlocksLoopState[C, Y]`.
1106class BlocksLoopState(NamedTuple):
1107 """The carry of the loop over blocks in `variable_length_scan` and `variable_length_update`."""
1109 i_block: Int32[Array, '']
1110 """The index of the next block."""
1112 carry: PyTree
1113 """The carry of the scan, or the arrays updated in place."""
1115 ys: PyTree
1116 """The stacked outputs, with an axis over blocks in `variable_length_scan`."""
1119def zeros_varying_like(
1120 x: Shaped[Array, '*any'] | ShapeDtypeStruct, shape: tuple[int, ...]
1121) -> Shaped[Array, '*shape']:
1122 """Make zeros with the dtype of `x`, varying over the same mesh axes as `x`."""
1123 zeros = jnp.zeros(shape, x.dtype)
1124 axes = tuple(varying_axes(x))
1125 return vary(zeros, axes) if axes else zeros
1128def _equal_shards(x: Shaped[Array, '...'], axis_name: str) -> Bool[Array, '']:
1129 """Check if all shards of `x` are equal, to be used in a `shard_map` context."""
1130 size = lax.axis_size(axis_name)
1131 perm = [(i, (i + 1) % size) for i in range(size)]
1132 perm_x = lax.ppermute(x, axis_name, perm)
1133 diff = jnp.any(x != perm_x)
1134 return jnp.logical_not(lax.psum(diff, axis_name))
1137@jit(static_argnames=('axis_name', 'in_specs', 'mesh', 'axis_names', 'check_vma'))
1138def equal_shards(
1139 x: PyTree[Array, ' S'], axis_name: str, **shard_map_kwargs: Any
1140) -> PyTree[Bool[Array, ''], ' S']:
1141 """Check that all shards of `x` are equal across axis `axis_name`.
1143 Parameters
1144 ----------
1145 x
1146 A pytree of arrays to check. Each array is checked separately.
1147 axis_name
1148 The mesh axis name across which equality is checked. It's not checked
1149 across other axes.
1150 **shard_map_kwargs
1151 Additional arguments passed to `jax.shard_map` to set up the function
1152 that checks equality. You may need to specify `in_specs` passing
1153 the (pytree of) `jax.sharding.PartitionSpec` that specifies how `x`
1154 is sharded, if the axes are not explicit, and `mesh` if there is not
1155 a default mesh set by `jax.set_mesh`.
1157 Returns
1158 -------
1159 A pytree of booleans indicating whether each leaf is equal across devices along the mesh axis.
1160 """
1161 equal_shards_leaf = partial(_equal_shards, axis_name=axis_name)
1163 def check_equal(x: PyTree[Array, ' S']) -> PyTree[Bool[Array, ''], ' S']:
1164 return tree.map(equal_shards_leaf, x)
1166 sharded_check_equal = shard_map(
1167 check_equal, out_specs=PartitionSpec(), **shard_map_kwargs
1168 )
1170 return sharded_check_equal(x)