Moves and the Metropolis-within-Gibbs scheduler¶
jaxrens decouples what configurations to propose from how they
combine in a single NS iteration. Individual MCMC kernels — random
walk, galilean, HMC, volume, shear, stretch, single-atom, single-atom
sweep, species swap, alchemical morph — are each described to the
sampler by a MoveKernel
descriptor (a dataclass carrying the kernel’s build_kernel factory,
its kernel_kwargs, weight, step_size, any extra_state_fields,
and which state aspects it mutates). They’re
composed at run time into a single step function by
build_mwg(), which implements
Metropolis-within-Gibbs (MWG): at each MCMC step, one kernel is
sampled and invoked.
The MWG step¶
Given a list of \(M\) kernels with weights \(\{w_k\}_{k=1}^{M}\), each MCMC step picks kernel \(k\) with probability
runs one step of that kernel, and records which one ran in
MoveInfo.move_idx. Over n_mcmc_steps calls per walker, each
kernel fires roughly \(p_k \cdot n_\mathrm{mcmc}\) times. YAML:
moves:
- type: gmc
step_size: 0.1
weight: 4.0 # 4/7 of steps
- type: volume
step_size: 0.3
weight: 1.0 # 1/7
- type: shear
step_size: 0.1
weight: 1.0
- type: stretch
step_size: 0.1
weight: 1.0
Note
The Galilean kernel’s YAML discriminator is gmc. type: galilean
is still accepted as a legacy alias and rewritten to gmc at parse
time, so older configs keep working — but gmc is the canonical
spelling and the one the Configuration documents. The
module is still sampling/moves/galilean.py; only the config key
changed.
flowchart LR
W["walker state x_t"] --> S["sample move idx<br/>p_k = w_k / Σ w_j"]
S --> R{"which kernel?"}
R -->|gmc| G["galilean.step"]
R -->|volume| V["volume.step"]
R -->|shear| SH["shear.step"]
R -->|stretch| ST["stretch.step"]
G --> O["x_{t+1},<br/>MoveInfo(move_idx, accepted, ...)"]
V --> O
SH --> O
ST --> O
One move schedule for every chain¶
The move index is drawn once per MCMC step and shared by every chain
walked in that step: the 1 + n_extra chains of an NS iteration, all
walkers during burn-in, and every run of a multi-run job (VmapRuns,
and PmapVmapRuns across all GPUs). Which move type runs at step \(t\)
is therefore common to all of them; each chain still draws its own
proposal, so the chains evolve independently otherwise.
Sampling stays correct: the move choice depends only on the RNG, never on
the walker state, so each chain is still a valid Metropolis-within-Gibbs
chain with selection probabilities \(p_k\). The only cost is that move
types are correlated across chains and runs within one step.
The MWG step_fn therefore takes the selection key as a separate,
required argument: step_fn(rng_key, state, emax, move_key).
rng_key drives the proposal and is per chain; move_key picks the move
and must be unbatched under any vmap, i.e. closed over or passed with
in_axes=None, never mapped
(see ns_step()’s move_key).
Acceptance at the NS constraint¶
NS enforces a hard likelihood threshold instead of a Metropolis-style temperature criterion. A proposed move from configuration \(r\) to \(r'\) is accepted iff
where \(E_\mathrm{max}\) is the current likelihood constraint. Equivalently,
Each kernel must satisfy detailed balance on the constrained prior — propose symmetrically with respect to \(\pi\), and the hard acceptance automatically gives a valid transition. Most kernels meet this by construction (random walk, reflection-based galilean, HMC with momentum resampling); the volume move uses Jacobian factors to compensate for its non-symmetric proposal.
Per-move acceptance and adaptation¶
ns_step accumulates per-move acceptance / proposal counts and
reject-reason counts across the scan:
n_accepted_per_move[k],n_proposed_per_move[k]reject_reason_counts_per_move[k, 0..3]—[accepted, energy, cell, prior]
The AdaptationManager reads these counters and runs a bisection
loop over each kernel’s step_size so its long-run acceptance
stays in [min_rate, max_rate] — typically [0.3, 0.5]. Step
sizes are clamped to [floor=1e-20, step_size_max].
The green band shows the acceptance window; rates outside it trigger a bisection round.
How AdaptationManager.apply dispatches the bisection¶
Same construction-time-cache pattern as the
InterREManager: the
manager is built once before the loop and stores one
jax.jit-compiled adjust_step_size callable per move type;
_run_loop only calls fires(i) and (on a fire) apply(...).
Inside apply, the work iterates over moves in Python and
dispatches each to a JIT’d adjust_step_size whose lax.while_loop
body runs the bisection.
flowchart TB
LOOP["NS outer loop<br/>iteration i"]
LOOP --> FIRES{"manager.fires(i)<br/>i > 0 ∧ i mod adjust_interval == 0"}
FIRES -- no --> CONT["continue NS step"]
FIRES -- yes --> APPLY["manager.apply(pop, emax, key, step_sizes)"]
APPLY --> LOOPK{"for each move k<br/>in move_descriptors"}
LOOPK --> DESC{"BatchDescriptor"}
DESC -- SingleRun --> SR["adjust_step_size(...)<br/>scalar ss"]
DESC -- VmapRuns --> VR["jax.vmap(adjust_step_size)<br/>(R, ...)"]
DESC -- PmapVmapRuns --> PR["jax.jit(shard_map(jax.vmap(adjust_step_size)))<br/>'gpu' mesh, (G, P, ...)"]
DESC -- ShardedSingleRun --> SH["jax.jit(shard_map(adjust_step_size_sharded))<br/>'shard' mesh, (G, K/G, ...)<br/>psum'd acceptance counts"]
subgraph jit_box["adjust_step_size — JIT + lax.while_loop"]
direction TB
SAMPLE["sample n_samples walkers<br/>jax.random.choice"]
TRIAL["run trial moves<br/>(vmap or chunked lax.map)"]
RATE["rate = mean(accepted)<br/>+ reject-reason counts"]
PROC{"_process_rate_jax<br/>rate ∈ [min_rate, max_rate]?"}
UP["new_ss = ss × adjust_factor<br/>(rate too low — too small steps)<br/>clamp to step_size_max"]
DN["new_ss = ss / adjust_factor<br/>(rate too high — too big steps)<br/>clamp to floor 1e-20"]
CONV(["converged ✓<br/>or bracket detected"])
NEXT{"round < max_rounds<br/>and not converged?"}
SAMPLE --> TRIAL --> RATE --> PROC
PROC -- yes --> CONV
PROC -- "no, too low" --> UP --> NEXT
PROC -- "no, too high" --> DN --> NEXT
NEXT -- yes --> SAMPLE
NEXT -- no --> CONV
end
SR --> SAMPLE
VR --> SAMPLE
PR --> SAMPLE
SH --> SAMPLE
CONV --> WRITE["update step_sizes[k] ← new_ss<br/>+ collect 9 diagnostics<br/>(rate, n_rounds, cap_hits, …)"]
WRITE --> NEXTK{"more moves?"}
NEXTK -- yes --> LOOPK
NEXTK -- no --> RET["return (new_step_sizes,<br/>per_move_outputs, key)"]
classDef decision fill:#fff7e0,stroke:#a07000,color:#222
classDef path fill:#eef5ff,stroke:#1565c0,color:#222
classDef jitBox fill:#fff7e0,stroke:#a07000,color:#5a3a00
classDef io fill:#f5f5f5,stroke:#444,color:#222
class FIRES,LOOPK,DESC,PROC,NEXT,NEXTK decision
class SR,VR,PR,SAMPLE,TRIAL,RATE,UP,DN path
class jit_box jitBox
class LOOP,APPLY,CONT,WRITE,RET,CONV io
A few invariants:
Cached compilation.
_build_jit_fnsruns once in__init__and stores onejax.jit-compiledadjust_step_sizeper move type. Each subsequentapplyhits the cache; no per-iteration retracing.Move-by-move Python loop, JIT’d inner.
applyiterates over moves in plain Python sostep_sizes[k]can be updated one entry at a time and per-move diagnostics can be logged atDEBUGlevel. The hot work — the bisection — happens inside the JIT’d callable.lax.while_loopbisection. Each round samplesadjust_n_sampleswalkers, runs trial moves through the same move kernel that NS uses (so acceptance is measured against the sameEmax), and updatesssbyadjust_factorbased on whether the rate is belowmin_rateor abovemax_rate. Convergence flags are set once the rate enters[min_rate, max_rate]or a proper bracket forms (one round too-low, one too-high) — the latter prevents oscillation when the optimum lies between the discretefactor-spaced rungs.Optional chunked-vmap.
trial_batch_sizetogglesjax.vmapvsjax.lax.mapfor the trial-move evaluation; the latter caps peak memory attrial_batch_size × per-trial tape, matters for HMC at largen_samples.
Adding a new kernel¶
A move kernel is anything that:
Declares what extra per-walker state it needs (
extra_state_fields).Provides a
build_kernel(backend, **kernel_kwargs)factory that returns a pure functionstep(rng_key, state, likelihood_constraint) → (new_state, MoveInfo).Optionally implements
init()for any move-specific state setup.
A minimal example:
from jaxrens.sampling.move_kernel import MoveKernel
def build_my_move(backend):
def step(rng_key, state, emax):
# propose state', compute new energy, accept iff H < emax
...
return new_state, MoveInfo(...)
return step
descriptor = MoveKernel(
name="my_move",
build_kernel=build_my_move,
step_size=0.1,
weight=1.0,
)
Then plug it into build_mwg(backend, [descriptor, ...]) like any
built-in kernel.
Where this lives in the code¶
Concern |
File |
|---|---|
Kernel descriptor |
|
MWG composer |
|
Individual kernels |
|
Info payload |
|
Adaptation |
|