ShardedSingleRun¶
- class jaxrens.sampling.batch_descriptor.ShardedSingleRun(n_gpu, n_runs=1, shape_prefix=())[source]¶
Bases:
objectDescriptor for a single NS run sharded across
n_gpuGPUs.Logically one NS run; physically the
K-walker population is split inton_gpuchunks ofK // n_gpuwalkers, one per device.ns_step_shardeduseslax.all_gather/lax.argmax/lax.psumcollectives 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 runsG * Pindependent NS replicas.ShardedSingleRunruns one population spread across G devices.Deliberately does not inherit from
_UniformBatcher(see the module docstring):n_runsis always 1 here, so then_runs == prod(shape_prefix)invariant the other three batchers share does not hold — the leadingGaxis 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 iteratingshape_prefix(the cumulative counters in_run_loop, the per-movestack_axisinbuild_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_terminationcollapses the (G,) axis to a scalar — every shard sees the same global value after the in-step collectives, so taking[0]is exact.split_keysreturns a plain, unbroadcast(n_sub_keys,)array rather than a redundant(G,)copy —wrap_for_batch()’sreplicated=argument tellsshard_mapto hand it to every device as-is (in_specs=P()), so no pre-broadcast/device_putis needed.reduce_emaxkeeps its(G,)broadcast (see its own docstring for why — its output sometimes substitutes for a value that’s genuinely(G,)-shaped elsewhere, unlikesplit_keys’s output).distinct_keysis different again — it returns genuinely independent per-shard keys, a real(G,)-sharded array, not a coherent broadcast, so it keeps itsdevice_put-onto- the-mesh placement. Seeexperiments/shard_map_rewrite.md(item 4) for the full account, including what was tried and reverted.- Variables:
- Parameters:
- property mesh¶
The
"shard"-axisjax.sharding.Meshfor this topology.Built once per instance and shared by every consumer, same as
PmapVmapRuns.mesh.
- 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_fnhere should bens_step_sharded(not the plainns_step) — it useslax.all_gather/lax.psumcollectives that only work inside a mapped context with matchingaxis_name="shard"(jax.shard_mapviajaxrens.sampling.mesh.pmap_like(), same asjax.pmapprovided).The returned callable has signature:
step(ns_state) -> (ns_state, info)
with leading shape
(G, ...)on every leaf. Unlike thejax.pmapthis replaces, the result composes withjax.jit.
- split_keys(rng_key, n_sub_keys)[source]¶
Split a key into
n_sub_keyscoherent (shard-independent) sub-keys.rng_keymay 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_shardedandadjust_step_size_shardedis 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, sincewrap_for_batch’sreplicated=argument marks it as a replicated (in_specs=P()) input instead: no pre-broadcast/device_putneeded,shard_maphands the same value to every device directly. Seeexperiments/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_shardedwrites identicallog_evidence/hmaxon every shard (post-psum), so[0]is exact.
- reduce_emax(energy)[source]¶
Global
maxover the entire (G, K_per_gpu) population, broadcast to (G,).Returns shape
(G,)(every entry identical) on the'shard'-named mesh — same convention asVmapRuns.reduce_emax()returning(R,)andPmapVmapRuns.reduce_emax()returning(G, P).Unlike
split_keys(), this one keeps its(G,)broadcast rather than returning a plain scalar forwrap_for_batch’sreplicated=— burn-in’sinitial_walkfeeds this value into the sameadapt_stepmachinery that the regular NS loop feeds withns_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_moveclosure can’t use a differentreplicatedmask depending on which caller suppliedemax. Seeexperiments/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.psuminns_step_sharded/adjust_step_size_sharded, so slicing one shard is exact. Returns a length-1 leading axis to match theflattencontract ((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 matchesVmapRuns.wrap_for_batch()andPmapVmapRuns.wrap_for_batch()’s contracts (each “row” of the leading axis is fed toper_element_fn).replicated: one bool per positional argument of per_element_fn, in order;Truemarks 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 getin_specs=P()(handed to every device as-is, no squeeze/broadcast) instead ofP("shard"). Leaving it empty preserves the old uniform-P("shard")-for-everything contract exactly. Outputs are alwaysP("shard")— this only changes how inputs are described, not outputs (seeexperiments/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()whenreplicatedis non-empty — that helper’s contract is one uniform spec for every argument, which can’t express this.
- distinct_keys(rng_key)[source]¶
Split a scalar key into G INDEPENDENT keys on the shard mesh.
Overrides the
_UniformBatcherdefault (split + reshape, duplicated here since this class doesn’t inherit from it) to alsodevice_putthe result onto the'shard'-named mesh so the per-shardshard_mapaccepts it alongside the sharded NSState.Returns shape
(G,)typed-key array sharded along axis 0.- Parameters:
rng_key (Array)
- Return type:
Array