ShardedSingleRun

class jaxrens.sampling.batch_descriptor.ShardedSingleRun(n_gpu, n_runs=1, shape_prefix=())[source]

Bases: object

Descriptor for a single NS run sharded across n_gpu GPUs.

Logically one NS run; physically the K-walker population is split into n_gpu chunks of K // n_gpu walkers, one per device. ns_step_sharded uses lax.all_gather / lax.argmax / lax.psum collectives across the "shard" axis to act on the global population coherently while letting each device hold only its share. Use case: memory scaling for heavy backends (MACE, NeuralIL, Nequix) on large populations that overflow a single GPU.

Distinct from PmapVmapRuns — that class runs G * P independent NS replicas. ShardedSingleRun runs one population spread across G devices.

Deliberately does not inherit from _UniformBatcher (see the module docstring): n_runs is always 1 here, so the n_runs == prod(shape_prefix) invariant the other three batchers share does not hold — the leading G axis is a sharding axis, not a replica axis. Four small, purely shape_prefix-driven methods (walker_axis, extract_step_sizes, broadcast_step_sizes, scalar_key) are still correct as written for this shape and are duplicated below rather than shared through inheritance, to avoid pretending this class belongs to that family.

Shape conventions:

  • Population leaves: (G, K // G, ...).

  • shape_prefix = (n_gpu,) — matches the physical layout. Consumers iterating shape_prefix (the cumulative counters in _run_loop, the per-move stack_axis in build_adapt_step) end up with a length-G axis where each row is identical post- lax.psum. Correct; G× redundant memory on small counters. Acceptable cost.

reduce_for_termination collapses the (G,) axis to a scalar — every shard sees the same global value after the in-step collectives, so taking [0] is exact.

split_keys returns a plain, unbroadcast (n_sub_keys,) array rather than a redundant (G,) copy — wrap_for_batch()’s replicated= argument tells shard_map to hand it to every device as-is (in_specs=P()), so no pre-broadcast/device_put is needed. reduce_emax keeps its (G,) broadcast (see its own docstring for why — its output sometimes substitutes for a value that’s genuinely (G,)-shaped elsewhere, unlike split_keys’s output). distinct_keys is different again — it returns genuinely independent per-shard keys, a real (G,)-sharded array, not a coherent broadcast, so it keeps its device_put-onto- the-mesh placement. See experiments/shard_map_rewrite.md (item 4) for the full account, including what was tried and reverted.

Variables:
  • n_gpu (int) – Number of GPU devices (G) the population is sharded across.

  • n_runs (int) – Always 1 — one logical NS run.

  • shape_prefix (tuple[int, ]) – (n_gpu,) — physical sharding axis.

Parameters:
property is_batched: bool

Always True — the population is distributed across G devices.

property mesh

The "shard"-axis jax.sharding.Mesh for this topology.

Built once per instance and shared by every consumer, same as PmapVmapRuns.mesh.

property walker_axis: int

Axis index of the per-walker (K) dimension — always 1 here.

extract_step_sizes(pop)[source]

Per-replica step sizes from pop.step_sizes (G, K, n_moves).

Returns shape (G, n_moves) — walker axis dropped.

Return type:

Array

broadcast_step_sizes(per_move_ss, n_walkers)[source]

Inverse of extract_step_sizes() — re-insert the walker axis.

Parameters:
  • per_move_ss (Array)

  • n_walkers (int)

Return type:

Array

scalar_key(rng_key)[source]

Reduce a per-shard key array to a single scalar key.

Every shard carries an identical broadcast key by construction, so taking entry 0 is exact — same as _UniformBatcher.scalar_key.

Parameters:

rng_key (Array)

Return type:

Array

wrap_step(ns_step_fn, step_fn, n_mcmc_steps, n_extra)[source]

Return a shard_map-compiled NS step callable (pmap-equivalent).

ns_step_fn here should be ns_step_sharded (not the plain ns_step) — it uses lax.all_gather / lax.psum collectives that only work inside a mapped context with matching axis_name="shard" (jax.shard_map via jaxrens.sampling.mesh.pmap_like(), same as jax.pmap provided).

The returned callable has signature:

step(ns_state)  ->  (ns_state, info)

with leading shape (G, ...) on every leaf. Unlike the jax.pmap this replaces, the result composes with jax.jit.

Parameters:
  • n_mcmc_steps (int)

  • n_extra (int)

split_keys(rng_key, n_sub_keys)[source]

Split a key into n_sub_keys coherent (shard-independent) sub-keys.

rng_key may be either:

  • A scalar key.

  • A (G,) array of identical broadcast keys (legacy callers) — collapsed via [0] before splitting.

The load-bearing invariant for ns_step_sharded and adjust_step_size_sharded is that every shard makes the same RNG decisions — this returns one plain, unbroadcast (n_sub_keys,) array rather than a redundant (G,)-broadcast copy of it, since wrap_for_batch’s replicated= argument marks it as a replicated (in_specs=P()) input instead: no pre-broadcast/device_put needed, shard_map hands the same value to every device directly. See experiments/shard_map_rewrite.md (“Per-argument in_specs instead of force-broadcasting scalars”).

Returns shape (n_sub_keys,) with typed-key dtype.

Parameters:
  • rng_key (Array)

  • n_sub_keys (int)

Return type:

Array

reduce_for_termination(log_evidence, hmax)[source]

Take [0] from the (G,) axis — every shard has the same value.

ns_step_sharded writes identical log_evidence / hmax on every shard (post-psum), so [0] is exact.

Parameters:
Return type:

tuple[float, float]

reduce_emax(energy)[source]

Global max over the entire (G, K_per_gpu) population, broadcast to (G,).

Returns shape (G,) (every entry identical) on the 'shard'-named mesh — same convention as VmapRuns.reduce_emax() returning (R,) and PmapVmapRuns.reduce_emax() returning (G, P).

Unlike split_keys(), this one keeps its (G,) broadcast rather than returning a plain scalar for wrap_for_batch’s replicated= — burn-in’s initial_walk feeds this value into the same adapt_step machinery that the regular NS loop feeds with ns_state.emax (a real, structurally (G,)-shaped field). Simplifying this to a scalar was tried and reverted: it broke burn-in’s adaptation call, since the shared _build_sharded_per_move closure can’t use a different replicated mask depending on which caller supplied emax. See experiments/shard_map_rewrite.md (item 4) for the finding.

Parameters:

energy (Float[jaxlib._jax.Array, 'G K'])

Return type:

Float[jaxlib._jax.Array, ’G’]

flatten(arr)[source]

Take [0:1] from the G axis — one logical run.

All shards hold identical per-run data after lax.psum in ns_step_sharded / adjust_step_size_sharded, so slicing one shard is exact. Returns a length-1 leading axis to match the flatten contract ((n_runs, ...)).

Parameters:

arr (Shaped[ndarray, 'G ...'] | Shaped[jaxlib._jax.Array, 'G ...'])

Return type:

Shaped[ndarray, ‘1 …’] | Shaped[jaxlib._jax.Array, ‘1 …’]

unflatten(arr_flat)[source]

Re-broadcast a length-1 leading axis to (G, …).

Parameters:

arr_flat (Shaped[ndarray, '1 ...'] | Shaped[jaxlib._jax.Array, '1 ...'])

Return type:

Shaped[ndarray, ‘G …’] | Shaped[jaxlib._jax.Array, ‘G …’]

wrap_for_batch(per_element_fn, *, check_vma=False, replicated=())[source]

Wrap a per-replica callable in shard_map over the shard axis.

Default signature contract (replicated=()): every input has a leading (G,) axis on the 'shard'-named mesh; outputs preserve that axis. This matches VmapRuns.wrap_for_batch() and PmapVmapRuns.wrap_for_batch()’s contracts (each “row” of the leading axis is fed to per_element_fn).

replicated: one bool per positional argument of per_element_fn, in order; True marks that argument as an already-replicated plain value (no (G,) axis at all — e.g. reduce_emax() / split_keys()’s outputs, post- simplification) rather than a genuinely (G, ...)-sharded one. Those arguments get in_specs=P() (handed to every device as-is, no squeeze/broadcast) instead of P("shard"). Leaving it empty preserves the old uniform-P("shard")-for-everything contract exactly. Outputs are always P("shard") — this only changes how inputs are described, not outputs (see experiments/shard_map_rewrite.md, item 4, for why the output-replication case needs a different, costlier approach).

Not built on jaxrens.sampling.mesh.pmap_like() when replicated is non-empty — that helper’s contract is one uniform spec for every argument, which can’t express this.

Parameters:
distinct_keys(rng_key)[source]

Split a scalar key into G INDEPENDENT keys on the shard mesh.

Overrides the _UniformBatcher default (split + reshape, duplicated here since this class doesn’t inherit from it) to also device_put the result onto the 'shard'-named mesh so the per-shard shard_map accepts it alongside the sharded NSState.

Returns shape (G,) typed-key array sharded along axis 0.

Parameters:

rng_key (Array)

Return type:

Array