Coverage for src/bartz/mcmcstep/_reduction.py: 99%
232 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/mcmcstep/_reduction.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"""Indexed-reduce (scatter-add) configs, one per algorithm, and the core ops."""
27import math
28from abc import abstractmethod
29from functools import partial
30from typing import Literal
32import jax
33from equinox import Module, field
34from jax import lax, vmap
35from jax import numpy as jnp
36from jax.extend.backend import backends
37from jax.typing import DTypeLike
38from jaxtyping import Array, Float, Integer, Shaped, UInt, UInt32
40from bartz.npz import serializable
42# target number of datapoint batches on cpu, and minimum datapoints per batch,
43# when batching is resolved automatically; unlike the gpu heuristic these are
44# flat (the cpu has no SM-count analog to scale with)
45_AUTO_CPU_TARGET = 16
46_AUTO_CPU_MIN_BATCH = 32
48# SM count used to trace `AutoBatchedReduction`'s gpu branch when no cuda backend
49# is visible. `lax.platform_dependent` traces that branch even with no gpu, only
50# to discard it at lowering, so this value never sizes a real gpu's batch grid;
51# it just keeps the dead trace valid (a present cuda backend reports its own).
52_MOOT_GPU_SM = 1
54# words per chunk in the two-stage sum of `popcount_equal`: chunk sums longer
55# than this are split by xla:cpu into reduce-windows that do not fuse the bit
56# arithmetic, which then gets materialized
57_POPCOUNT_CHUNK = 32
59# datapoints per chunk in the 'chunked' method of `OneHotReduction`: with more
60# additions per chunk, xla:cpu stops fusing them with the comparison
61ONEHOT_CHUNK = 8
64class ReductionConfig(Module):
65 """Select and configure an indexed-reduce (scatter-add) implementation.
67 Each concrete subclass identifies a reduction algorithm and carries its
68 options. Pass instances to `init` to control how the residuals, counts and
69 likelihood precisions are summed over the datapoints in each leaf.
70 """
72 @abstractmethod
73 def _reduce(
74 self,
75 values: Float[Array, '*batch_shape n'] | int,
76 indices: UInt[Array, ' n'],
77 /,
78 *,
79 size: int,
80 subset: Integer[Array, ' subset_size'] | None = None,
81 dtype: DTypeLike,
82 data_sharded: bool,
83 # the output's trailing axis is the number of reduced bins: the length
84 # of the subset, or `size` without one. jaxtyping evals the `{...}` dim
85 # against the arguments but forbids spaces, hence the `getattr`.
86 ) -> Shaped[Array, '*batch_shape {getattr(subset,"size",size)}']:
87 """Indexed reduce along the last axis of `values`.
89 Parameters
90 ----------
91 values
92 The values to sum into bins, or a scalar `int` weighting every
93 datapoint equally (used to count the datapoints in each bin).
94 indices
95 The bin index each datapoint falls into.
96 size
97 The static excluded upper bound on the values of `indices`, and
98 the number of output bins when no subset is given.
99 subset
100 If given, reduce only into these bins, in this order, ignoring
101 datapoints whose index is not amongst them. The bins shall be
102 distinct, but for those past `size`, which reduce to zero.
103 dtype
104 The dtype of the output and of the accumulation; the values are
105 kept in their own, possibly narrower, dtype until accumulated.
106 data_sharded
107 Whether the data axis is sharded; if true, the result is
108 psum-reduced across the ``'data'`` axis of the enclosing
109 `shard_map`.
111 Returns
112 -------
113 The per-bin sums, with the same leading dimensions as `values` and the bins on the trailing axis.
114 """
115 ...
118def resolve_subset(
119 indices: UInt[Array, ' n'], size: int, subset: Integer[Array, ' subset_size'] | None
120) -> tuple[int, UInt[Array, ' n']]:
121 """Reduce the bin-subset case to the full one for scatter algorithms.
123 Parameters
124 ----------
125 indices
126 The bin index each datapoint falls into, in ``[0, size)``.
127 size
128 The number of bins.
129 subset
130 The bins to reduce into, or `None` for all bins.
132 Returns
133 -------
134 out_size : int
135 The number of output bins: the length of `subset`, or `size` without it.
136 indices : UInt[Array, ' n']
137 The scatter indices into the output bins: unchanged without a subset,
138 else the position in `subset` of the bin of each datapoint, out of
139 bounds if absent, where the scatter drops it.
140 """
141 if subset is None:
142 return size, indices
143 else:
144 (subset_size,) = subset.shape
145 positions = jnp.full_like(indices, subset_size)
146 for i in reversed(range(subset_size)):
147 # the comparison is in the wider dtype of the two, so bins past
148 # `size` do not wrap and alias a real bin
149 positions = jnp.where(indices == subset[i], i, positions)
150 return subset_size, positions
153@serializable
154class BatchedReduction(ReductionConfig):
155 """Segment-sum with optional batching along the datapoints.
157 Fastest at the usual tree sizes. See `AutoBatchedReduction` to resolve
158 `num_batches` automatically per platform.
159 """
161 num_batches: int | None = field(static=True, default=None)
162 """The number of datapoint batches, or `None` (the default) for an unbatched
163 reduce."""
165 batches_inner: bool = field(static=True, default=True)
166 """Whether the batch axis sits on the scatter buffer's inner, contiguous axis
167 (``size``-by-``num_batches``) or its outer axis (``num_batches``-by-``size``);
168 the two layouts give the backend different memory access patterns. `True` (the
169 default) matches the historical layout. No effect when `num_batches` is `None`."""
171 contiguous: bool = field(static=True, default=False)
172 """How datapoints are assigned to batches. `False` (the default) strides them,
173 sending datapoint ``i`` to batch ``i % num_batches``; `True` splits them into
174 contiguous chunks, sending ``i`` to batch ``i // batch_size``. No effect when
175 `num_batches` is `None`."""
177 def _reduce(
178 self,
179 values: Float[Array, '*batch_shape n'] | int,
180 indices: UInt[Array, ' n'],
181 /,
182 *,
183 size: int,
184 subset: Integer[Array, ' subset_size'] | None = None,
185 dtype: DTypeLike,
186 data_sharded: bool,
187 ) -> Shaped[Array, '*batch_shape {getattr(subset,"size",size)}']:
188 values = jnp.asarray(values)
189 assert values.ndim == 0 or values.shape[-1:] == indices.shape
190 size, indices = resolve_subset(indices, size, subset)
191 batch_shape = values.shape[:-1]
193 # Cast `values` explicitly. The scatter buffer is in `dtype`, which
194 # might be narrower than `values.dtype`. Conversely, when
195 # `values.dtype` is narrower than `dtype`, this formally creates a
196 # larger intermediate array, but under jit either it was already
197 # materialized anyway or the cast is fused into the reduction.
198 values = values.astype(dtype)
200 if self.num_batches is None:
201 out = jnp.zeros((*batch_shape, size), dtype).at[..., indices].add(values)
202 else:
203 # in the sharded case, n is the size of the local shard, not the full size
204 (n,) = indices.shape
205 # unsigned avoids a negative-index normalization select in the scatter
206 iota = jnp.arange(n, dtype=jnp.uint32)
207 if self.contiguous:
208 batch_size = -(-n // self.num_batches) # ceil: last batch is partial
209 batch_indices = iota // batch_size
210 else:
211 batch_indices = iota % self.num_batches
212 if self.batches_inner:
213 out = (
214 jnp.zeros((*batch_shape, size, self.num_batches), dtype)
215 .at[..., indices, batch_indices]
216 .add(values)
217 .sum(axis=-1)
218 )
219 else:
220 out = (
221 jnp.zeros((*batch_shape, self.num_batches, size), dtype)
222 .at[..., batch_indices, indices]
223 .add(values)
224 .sum(axis=-2)
225 )
227 if data_sharded:
228 out = lax.psum(out, 'data')
229 return out
232@serializable
233class AutoBatchedReduction(ReductionConfig):
234 """`BatchedReduction` that picks `num_batches` automatically per platform.
236 A flat target on cpu, and on gpu a count scaling with the SM count and the
237 multivariate outcome size. Only cpu and cuda are supported; any other
238 platform raises at lowering.
239 """
241 min_batch_size: float = field(static=True, default=128.0)
242 """Minimum datapoints per batch on gpu; caps the batch count at
243 ``n / min_batch_size``."""
245 beta_sm: float = field(static=True, default=48.0)
246 """Batches per streaming multiprocessor on gpu; the batch count saturates at
247 ``beta_sm * n_sms * m ** -gamma``, with `n_sms` the gpu's SM count and ``m``
248 the multivariate work per datapoint."""
250 gamma: float = field(static=True, default=0.4)
251 """Exponent by which multivariate outcomes (``m`` values per datapoint) shrink
252 the saturation batch count on gpu."""
254 batches_inner: bool = field(static=True, default=True)
255 """Same as `BatchedReduction`."""
257 contiguous: bool = field(static=True, default=False)
258 """Same as `BatchedReduction`."""
260 def _reduce(
261 self,
262 values: Float[Array, '*batch_shape n'] | int,
263 indices: UInt[Array, ' n'],
264 /,
265 *,
266 size: int,
267 subset: Integer[Array, ' subset_size'] | None = None,
268 dtype: DTypeLike,
269 data_sharded: bool,
270 ) -> Shaped[Array, '*batch_shape {getattr(subset,"size",size)}']:
271 # defer the cpu/gpu choice to XLA: both branches are traced, but only the
272 # one for the run platform is lowered. With no `default`, an untested
273 # platform (rocm, tpu) errors at lowering instead of silently falling back.
274 kwargs = dict(size=size, subset=subset, dtype=dtype, data_sharded=data_sharded)
275 return lax.platform_dependent(
276 cpu=partial(self._reduce_cpu, values, indices, **kwargs),
277 cuda=partial(self._reduce_gpu, values, indices, **kwargs),
278 )
280 def _reduce_cpu(
281 self,
282 values: Float[Array, '*batch_shape n'] | int,
283 indices: UInt[Array, ' n'],
284 /,
285 *,
286 size: int,
287 subset: Integer[Array, ' subset_size'] | None = None,
288 dtype: DTypeLike,
289 data_sharded: bool,
290 ) -> Shaped[Array, '*batch_shape {getattr(subset,"size",size)}']:
291 # flat target: the cpu has no SM-count analog to scale the batch count with
292 (n,) = indices.shape
293 num_batches = _final_round(n, _AUTO_CPU_TARGET, _AUTO_CPU_MIN_BATCH)
294 return self._delegate(num_batches)._reduce( # noqa: SLF001
295 values,
296 indices,
297 size=size,
298 subset=subset,
299 dtype=dtype,
300 data_sharded=data_sharded,
301 )
303 def _reduce_gpu(
304 self,
305 values: Float[Array, '*batch_shape n'] | int,
306 indices: UInt[Array, ' n'],
307 /,
308 *,
309 size: int,
310 subset: Integer[Array, ' subset_size'] | None = None,
311 dtype: DTypeLike,
312 data_sharded: bool,
313 ) -> Shaped[Array, '*batch_shape {getattr(subset,"size",size)}']:
314 # `n` is the local shard size when data-sharded, which is exactly what the
315 # heuristic wants. `m` is the multivariate batch size: the product of the
316 # values' leading (non-datapoint) axes (1 for the scalar count case), i.e.
317 # how much vector work rides on each scatter slot; clamped to >=1 so a
318 # zero-size leading axis (e.g. k=0 outcome components) leaves a moot, empty
319 # reduce with the m=1 baseline cap.
320 (n,) = indices.shape
321 m = max(1, math.prod(jnp.shape(values)[:-1]))
322 # the gpu cap scales up with the SM count and down, sublinearly, with the
323 # multivariate work per slot
324 sm_cap = self.beta_sm * _gpu_sm_count() * m ** (-self.gamma)
325 num_batches = _final_round(n, sm_cap, self.min_batch_size)
326 return self._delegate(num_batches)._reduce( # noqa: SLF001
327 values,
328 indices,
329 size=size,
330 subset=subset,
331 dtype=dtype,
332 data_sharded=data_sharded,
333 )
335 def _delegate(self, num_batches: int | None) -> BatchedReduction:
336 """Build a `BatchedReduction` with the resolved count and this config's layout."""
337 return BatchedReduction(
338 num_batches=num_batches,
339 batches_inner=self.batches_inner,
340 contiguous=self.contiguous,
341 )
344def _final_round(
345 n: int, target: float | int, min_batch_size: float | int
346) -> int | None:
347 """Cap batches to keep them above `min_batch_size`, round to a power of 2, and disable batching if there's only 1 batch."""
348 # at least `min_batch_size` elements per batch
349 num = min(n / min_batch_size, target)
351 # round to the nearest power of 2 because I guess XLA and the hardware
352 # will like that (not sure about this, maybe just multiple of 32?)
353 num = 2 ** round(math.log2(num)) if num > 0 else 0
355 # disable batching if the batch is as large as the whole dataset
356 return num if num > 1 else None
359def _gpu_sm_count() -> int:
360 """Streaming-multiprocessor count shared by the visible cuda gpus.
362 Read by `AutoBatchedReduction` to size the gpu batch grid. Since
363 `lax.platform_dependent` only runs the gpu branch on cuda, this trusts
364 `jax.devices('cuda')` and each device's `core_count` rather than guessing,
365 and raises if the gpus report differing counts (a mixed gpu set is
366 unsupported).
367 """
368 if 'cuda' not in backends():
369 # no cuda backend: lax.platform_dependent still traces the gpu branch
370 # here, only to discard it at lowering, so the count is never used
371 return _MOOT_GPU_SM
372 counts = {device.core_count for device in jax.devices('cuda')}
373 if len(counts) > 1:
374 msg = (
375 f'visible cuda gpus report differing SM counts {sorted(counts)}; '
376 'AutoBatchedReduction assumes a single gpu model'
377 )
378 raise ValueError(msg)
379 (count,) = counts
380 return count
383@serializable
384class OneHotReduction(ReductionConfig):
385 """Dense one-hot reduction.
387 Materializes the membership of each datapoint in its leaf as a one-hot
388 matrix over the output bins and contracts it against the values. Beats
389 `BatchedReduction` only when the number of bins is very small (e.g. a
390 single leaf pair), or on gpu for multivariate residuals.
391 """
393 method: Literal['matmul', 'multiply', 'chunked', 'scatter_set'] = field(
394 static=True, default='matmul'
395 )
396 """How to contract the values against the one-hot leaf-membership matrix:
398 'matmul'
399 Contract the values with the one-hot matrix via a dot. Faster on gpu,
400 especially for multivariate residuals.
401 'multiply'
402 Elementwise-multiply by the one-hot matrix and reduce over the
403 datapoints; whether the ``n``-by-``size`` product is fused into the
404 reduction or materialized is left to the backend.
405 'chunked'
406 Like 'multiply', but sum the product over short chunks of datapoints
407 first, which xla:cpu fuses with the comparison, while it materializes
408 the whole product before a long reduction. Faster on cpu.
409 'scatter_set'
410 Scatter the values into a dense buffer with unique (non-atomic) writes,
411 then sum over the datapoints.
412 """
414 n_inner: bool = field(static=True, default=True)
415 """Whether the datapoints sit on the one-hot's inner, contiguous axis
416 (``size``-by-``n``) or its outer axis (``n``-by-``size``); the two layouts
417 give the backend different memory access patterns. `True` (the default)
418 fuses better on gpu. 'chunked' supports only `True`."""
420 def _reduce( # noqa: C901, the match over the methods
421 self,
422 values: Float[Array, '*batch_shape n'] | int,
423 indices: UInt[Array, ' n'],
424 /,
425 *,
426 size: int,
427 subset: Integer[Array, ' subset_size'] | None = None,
428 dtype: DTypeLike,
429 data_sharded: bool,
430 ) -> Shaped[Array, '*batch_shape {getattr(subset,"size",size)}']:
431 values = jnp.asarray(values)
432 assert values.ndim == 0 or values.shape[-1:] == indices.shape
434 # a scalar value is the count case, weighting each datapoint by `values`;
435 # it broadcasts in the scatter/multiply paths, only matmul needs a vector
436 scalar = values.ndim == 0
437 (n,) = indices.shape
438 batch_shape = values.shape[:-1]
439 size, bins, indices = resolve_subset_bins(
440 indices, size, subset, remap=self.method == 'scatter_set'
441 )
442 # unsigned avoids a negative-index normalization select in the scatter
443 iota = jnp.arange(n, dtype=jnp.uint32)
445 # one-hots and scatter buffers hold the values, so they are built in
446 # the values' dtype; only the reduction accumulates in `dtype`. The
447 # scalar count case has no input precision to preserve and uses `dtype`.
448 values_dtype = dtype if scalar else values.dtype
450 match self.method, self.n_inner:
451 case 'scatter_set', True:
452 out = (
453 jnp.zeros((*batch_shape, size, n), values_dtype)
454 .at[..., indices, iota]
455 .set(values, unique_indices=True)
456 .sum(axis=-1, dtype=dtype)
457 )
458 case 'scatter_set', False:
459 out = (
460 jnp.zeros((*batch_shape, n, size), values_dtype)
461 .at[..., iota, indices]
462 .set(values, unique_indices=True)
463 .sum(axis=-2, dtype=dtype)
464 )
465 case 'matmul', True:
466 onehot = (bins[:, None] == indices).astype(values_dtype) # (size, n)
467 vec = jnp.broadcast_to(values.astype(dtype), (n,)) if scalar else values
468 out = jnp.einsum(
469 '...n,sn->...s', vec, onehot, preferred_element_type=dtype
470 )
471 case 'matmul', False:
472 onehot = (indices[:, None] == bins).astype(values_dtype) # (n, size)
473 vec = jnp.broadcast_to(values.astype(dtype), (n,)) if scalar else values
474 out = jnp.einsum(
475 '...n,ns->...s', vec, onehot, preferred_element_type=dtype
476 )
477 case 'multiply', True:
478 onehot = bins[:, None] == indices # (size, n)
479 if scalar:
480 out = values * onehot.sum(axis=-1, dtype=dtype)
481 else:
482 out = (values[..., None, :] * onehot).sum(axis=-1, dtype=dtype)
483 case 'multiply', False:
484 onehot = indices[:, None] == bins # (n, size)
485 if scalar:
486 out = values * onehot.sum(axis=-2, dtype=dtype)
487 else:
488 out = (values[..., :, None] * onehot).sum(axis=-2, dtype=dtype)
489 case 'chunked', True:
490 out = chunked_onehot_sum(values, indices, bins, dtype)
491 case 'chunked', False: 491 ↛ 495line 491 didn't jump to line 495 because the pattern on line 491 always matched
492 msg = "OneHotReduction(method='chunked') supports only n_inner=True"
493 raise NotImplementedError(msg)
495 if data_sharded:
496 out = lax.psum(out, 'data')
497 return out
500def chunked_onehot_sum(
501 values: Float[Array, '*batch_shape n'] | Integer[Array, ''],
502 indices: UInt[Array, ' n'],
503 bins: UInt[Array, ' size'],
504 dtype: DTypeLike,
505) -> Shaped[Array, '*batch_shape size']:
506 """Implement the 'chunked' method of `OneHotReduction`."""
507 (n,) = indices.shape
508 even_n = n - n % ONEHOT_CHUNK
509 num_chunks = even_n // ONEHOT_CHUNK
511 # whole chunks: the one-hot product is (*batch_shape, size, chunks, chunk)
512 onehot = bins[:, None, None] == indices[:even_n].reshape(num_chunks, ONEHOT_CHUNK)
513 if values.ndim == 0:
514 product = onehot
515 else:
516 *batch_shape, _ = values.shape
517 head = values[..., :even_n].reshape(*batch_shape, num_chunks, ONEHOT_CHUNK)
518 product = head[..., None, :, :] * onehot
520 # sum within each chunk with explicit additions rather than a reduction,
521 # which xla:cpu would hand to a library call that needs the product
522 # materialized; the barrier stops xla from turning the additions into one.
523 # The accumulators are at least as wide as `dtype`.
524 partial_sums = product[..., 0].astype(dtype)
525 for i in range(1, ONEHOT_CHUNK):
526 partial_sums += product[..., i]
527 out = lax.optimization_barrier(partial_sums).sum(axis=-1, dtype=dtype)
529 # the datapoints left over
530 rem_onehot = bins[:, None] == indices[even_n:] # (size, n % chunk)
531 if values.ndim == 0:
532 out += rem_onehot.sum(axis=-1, dtype=dtype)
533 return values * out
534 else:
535 out += (values[..., None, even_n:] * rem_onehot).sum(axis=-1, dtype=dtype)
536 return out
539def resolve_subset_bins(
540 indices: UInt[Array, ' n'],
541 size: int,
542 subset: Integer[Array, ' subset_size'] | None,
543 *,
544 remap: bool,
545) -> tuple[int, UInt[Array, ' out_size'], UInt[Array, ' n']]:
546 """Resolve the bin subset into output size, comparison bins, and scatter indices.
548 The comparison methods of `OneHotReduction` reduce against the bins of the
549 subset directly, while its scatter method (`remap`) indexes bins by
550 position, so the indices are converted like in `resolve_subset`.
551 """
552 if subset is None:
553 return size, jnp.arange(size, dtype=indices.dtype), indices
554 else:
555 # uint32, not the possibly narrow `indices.dtype`, so bins past `size`
556 # do not wrap and alias a real bin in the comparison
557 bins = subset.astype(jnp.uint32)
558 if remap:
559 _, indices = resolve_subset(indices, size, subset)
560 return bins.size, bins, indices
563@serializable
564class AutoOneHotReduction(ReductionConfig):
565 """`OneHotReduction` that picks `method` and `n_inner` automatically.
567 Resolves both knobs from trace-time information per site and platform, then
568 delegates to a plain `OneHotReduction`. Uses `matmul` only for wide-bin
569 multivariate reductions and `multiply` otherwise, or `chunked` in its place
570 on cpu; lays the datapoints on the inner axis with `chunked` and for the
571 cuda count, on the outer axis otherwise. The count and precision sites
572 support only cpu and cuda, raising at lowering elsewhere.
574 The site is recovered from the value: scalar is the count, a wide output the
575 residual, a narrow non-scalar output the precision.
577 Known limitation: the wide-bin univariate residual on cpu past ~10^6
578 datapoints prefers a layout this picks against (up to ~2x slower).
579 """
581 min_matmul_bins: int = field(static=True, default=8)
582 """Minimum output bins for `matmul`; below it `multiply` is always used."""
584 def _reduce(
585 self,
586 values: Float[Array, '*batch_shape n'] | int,
587 indices: UInt[Array, ' n'],
588 /,
589 *,
590 size: int,
591 subset: Integer[Array, ' subset_size'] | None = None,
592 dtype: DTypeLike,
593 data_sharded: bool,
594 ) -> Shaped[Array, '*batch_shape {getattr(subset,"size",size)}']:
595 out_size = size if subset is None else subset.size
596 m = max(1, math.prod(jnp.shape(values)[:-1]))
597 gpu_method = (
598 'matmul' if m >= 2 and out_size >= self.min_matmul_bins else 'multiply'
599 )
600 cpu_method = 'chunked' if gpu_method == 'multiply' else gpu_method
602 if jnp.ndim(values) == 0: # count
603 cpu_inner, cuda_inner = False, True
604 elif out_size <= 2: # precision
605 cpu_inner, cuda_inner = True, False
606 else: # residual
607 cpu_inner, cuda_inner = False, False
609 args = (values, indices)
610 kwargs: dict = dict(
611 size=size, subset=subset, dtype=dtype, data_sharded=data_sharded
612 )
613 # 'chunked' has its own layout, the datapoints on the inner axis
614 cpu = OneHotReduction(
615 method=cpu_method, n_inner=cpu_inner or cpu_method == 'chunked'
616 )
617 cuda = OneHotReduction(method=gpu_method, n_inner=cuda_inner)
619 if cpu == cuda:
620 # the choice matches on every platform, so no platform split is
621 # needed and the reduction also runs on untested platforms (tpu/rocm)
622 return cuda._reduce(*args, **kwargs) # noqa: SLF001
623 else:
624 # defer the cpu/gpu choice to XLA: both branches are traced, but only
625 # the run platform's is lowered. If the layouts differ, there is no
626 # `default`, so an untested platform errors at lowering instead of
627 # silently falling back; otherwise it takes the cuda branch.
628 other = 'default' if cpu_inner == cuda_inner else 'cuda'
629 branches = {
630 'cpu': partial(cpu._reduce, *args, **kwargs), # noqa: SLF001
631 other: partial(cuda._reduce, *args, **kwargs), # noqa: SLF001
632 }
633 return lax.platform_dependent(**branches)
636@serializable
637class PopcountReduction(ReductionConfig):
638 """Count reduction by SWAR popcount on the packed bin indices.
640 Reinterprets the unsigned indices as 32-bit words holding one or more
641 indices each, flags the lanes equal to a bin with bit arithmetic, and
642 counts the flags with a popcount. Supports only counting (unit values)
643 into a subset of bins, so it can be used only as ``count_reduction_config``.
644 """
646 def _reduce(
647 self,
648 values: Float[Array, '*batch_shape n'] | int,
649 indices: UInt[Array, ' n'],
650 /,
651 *,
652 size: int,
653 subset: Integer[Array, ' subset_size'] | None = None,
654 dtype: DTypeLike,
655 data_sharded: bool,
656 ) -> Shaped[Array, '*batch_shape {getattr(subset,"size",size)}']:
657 del size # the subset alone sets the output
658 assert isinstance(values, int)
659 assert values == 1
660 assert subset is not None
661 bins = subset.astype(jnp.uint32)
662 out = vmap(partial(popcount_equal, indices))(bins).astype(dtype)
663 if data_sharded:
664 out = lax.psum(out, 'data')
665 return out
668@serializable
669class AutoOneHotOrPopcountReduction(ReductionConfig):
670 """`PopcountReduction` on cpu, `AutoOneHotReduction` on other platforms.
672 On gpu the one-hot count fuses with the computation of the indices, which
673 the popcount does not. Like `PopcountReduction`, it supports only counting
674 into a subset of bins, so it can be used only as ``count_reduction_config``.
675 """
677 def _reduce(
678 self,
679 values: Float[Array, '*batch_shape n'] | int,
680 indices: UInt[Array, ' n'],
681 /,
682 *,
683 size: int,
684 subset: Integer[Array, ' subset_size'] | None = None,
685 dtype: DTypeLike,
686 data_sharded: bool,
687 ) -> Shaped[Array, '*batch_shape {getattr(subset,"size",size)}']:
688 # the arguments are bound rather than passed through, so `values` stays
689 # a python int for the popcount checks
690 kwargs: dict = dict(
691 size=size, subset=subset, dtype=dtype, data_sharded=data_sharded
692 )
693 return lax.platform_dependent(
694 cpu=partial(PopcountReduction()._reduce, values, indices, **kwargs), # noqa: SLF001
695 default=partial(AutoOneHotReduction()._reduce, values, indices, **kwargs), # noqa: SLF001
696 )
699def popcount_equal(
700 indices: UInt[Array, ' n'], bin_index: UInt32[Array, '']
701) -> UInt32[Array, '']:
702 """Count the `indices` equal to `bin_index`, processing several at a time."""
703 (n,) = indices.shape
704 bits = jnp.iinfo(indices.dtype).bits
705 lanes = 32 // bits
706 head = n - n % lanes
708 # values that do not fit in a lane never match
709 fits = bin_index >> bits == 0
710 bin_index = bin_index.astype(indices.dtype)
712 # pack `lanes` indices per 32-bit word (the reshape drops the lane axis
713 # that the bitcast keeps when an index is already 32-bit)
714 num_words = head // lanes
715 words = lax.bitcast_convert_type(
716 indices[:head].reshape(num_words, lanes), jnp.uint32
717 ).reshape(num_words)
718 full = num_words - num_words % _POPCOUNT_CHUNK
720 # sum the matches per chunk of words, then sum the chunks. The barrier
721 # stops xla from merging the two sums into a single long reduction, which
722 # xla:cpu splits into reduce-windows that do not fuse the bit arithmetic
723 chunks = count_equal_lanes(
724 words[:full].reshape(full // _POPCOUNT_CHUNK, _POPCOUNT_CHUNK), bin_index
725 ).sum(axis=-1, dtype=jnp.uint32)
726 count = lax.optimization_barrier(chunks).sum(dtype=jnp.uint32)
727 count += count_equal_lanes(words[full:], bin_index).sum(dtype=jnp.uint32)
729 # count the indices left over from the packing one by one
730 count += (indices[head:] == bin_index).sum(dtype=jnp.uint32)
732 return jnp.where(fits, count, 0)
735def count_equal_lanes(
736 words: UInt32[Array, '*shape'], bin_index: UInt[Array, '']
737) -> UInt32[Array, '*shape']:
738 """Count the lanes equal to `bin_index` in each word of packed `bin_index`-typed lanes."""
739 bits = jnp.iinfo(bin_index.dtype).bits
740 lanes = 32 // bits
741 one = sum(1 << (bits * i) for i in range(lanes)) # 0x01..01 per lane
742 low = one * ((1 << (bits - 1)) - 1) # 0x7f..7f per lane
743 diff = words ^ (bin_index.astype(jnp.uint32) * one)
744 # exact per-lane zero test: the lane's top bit is set iff the lane is zero
745 flags = ~(((diff & low) + low) | diff | low)
746 return lax.population_count(flags)