nvalchemi.enhanced_sampling.ReplicaExchange#

class nvalchemi.enhanced_sampling.ReplicaExchange(states, initial_state_ids, *, mode='synchronous', attempt_interval=100, random_seed=1234)[source]#

Synchronous replica exchange with an even/odd pair schedule.

Parameters:
  • states (Sequence[ThermodynamicState]) – The ladder. state_id values must be exactly 0..S-1.

  • initial_state_ids (torch.Tensor) – Assignment of states to walkers, shape [B]. Must be a permutation of 0..S-1: replica exchange presumes a bijection between walkers and states, and a duplicate would let two walkers claim the same rung.

  • mode (Literal['synchronous']) – "synchronous" only. Asynchronous exchange is not implemented.

  • attempt_interval (int) – Dynamics steps per exchange segment.

  • random_seed (int) – Base seed for acceptance draws. Randomness is derived per attempt as random_seed + exchange_id rather than from a long-lived generator, so a checkpoint needs two integers instead of an opaque RNG blob — the same counter-based scheme NVTLangevin uses for its noise.

Raises:

ValueError – If the mode is unsupported, attempt_interval is below 1, the ladder is not dense, or the assignment is not a permutation.

Notes

Acceptance

Which rule applies is inferred from the ladder and validated, rather than being a free parameter that can silently disagree with it.

Temperature exchange — temperatures differ:

\[\log a = \min\bigl(0,\ (\beta_i - \beta_j)(U_i - U_j)\bigr)\]

A cold replica holding anomalously high energy therefore moves up the ladder with probability one, which is the point of the method.

Umbrella exchange — temperatures are equal and the states differ by bias window:

\[\log a = \min\bigl(0,\ u_i(x_i) + u_j(x_j) - u_i(x_j) - u_j(x_i)\bigr)\]

with \(u_k\) the reduced bias potential of state k. The two cross terms need the bias re-evaluated under swapped labels, which costs one extra bias evaluation per attempt.

Not supported

A ladder that varies temperature and bias window at once needs a combined acceptance rule that is not implemented. The temperature rule alone omits the cross-state bias terms, so running it anyway would break detailed balance with no symptom — it is therefore rejected, twice over: a bias that declares state_dependent_for_exchange is refused at construction, and the runner additionally probes empirically at prime time by evaluating every bias under a permuted assignment. Vary one or the other.

property acceptance: str#

Return the inferred acceptance rule name.

property acceptance_rate: float#

Return the fraction of attempted pair swaps that were accepted.

config_fingerprint()[source]#

Return the configuration a restored run must match.

Exchange semantics live in the ladder, not in the counters: the temperatures set the acceptance exponent, the rule follows from them, and the interval sets the segment cadence. Restoring a run into a different ladder would keep the counters and the walker assignment while silently changing what a swap means — the walkers would carry on labelled 0..S-1 against temperatures they were never sampled at.

initial_state_ids is deliberately excluded. It seeds the assignment only when the batch does not already carry one, and a restored batch always does, so it has no effect after step zero and would be a false mismatch.

Returns:

JSON-representable configuration.

Return type:

dict[str, Any]

decide(segment, state_ids, energies, bias_current=None, bias_swapped=None)[source]#

Decide this segment’s swaps and return the new assignment.

Pure with respect to the batch: it takes energies and returns a permutation, so the caller owns every side effect (rebinding the integrator, rescaling velocities, re-priming forces). That keeps the acceptance rule testable against hand-computed numbers.

Parameters:
  • segment (int) – Exchange segment index, which selects the even/odd pairing.

  • state_ids (Tensor) – Current assignment, shape [B].

  • energies (Tensor) – Per-walker potential energy U in eV, shape [B]. Used by temperature acceptance.

  • bias_current (Tensor | None) – Reduced bias potential per walker under its current state, shape [B]. Required for umbrella acceptance.

  • bias_swapped (Tensor | None) – Reduced bias potential per walker under its proposed state, shape [B]. Required for umbrella acceptance.

Returns:

The new state assignment [B], the pairs attempted, and the boolean accept mask over those pairs.

Return type:

tuple[torch.Tensor, list[tuple[int, int]], torch.Tensor]

Raises:

ValueError – If state_ids is not a permutation of the ladder, or if umbrella acceptance is in force but the bias energies were not supplied.

static describe_config_mismatch(saved, actual)[source]#

Return human-readable differences between two fingerprints.

Parameters:
  • saved (Mapping[str, Any] | None) – The checkpoint’s fingerprint, or None when it had no exchange.

  • actual (Mapping[str, Any] | None) – The live runner’s fingerprint, or None when it has none.

Returns:

One line per difference; empty when they agree.

Return type:

list[str]

load_state_dict(state)[source]#

Restore exchange state produced by state_dict().

Parameters:

state (Mapping[str, Any]) – The mapping previously returned by state_dict().

Raises:

ValueError – If the saved configuration disagrees with this instance’s.

Return type:

None

pair_acceptance_rates()[source]#

Return the per-neighbouring-pair acceptance rates.

A REMD ladder is tuned on these: a pair far below the others is a gap the walkers cannot cross, and the ladder needs another rung there.

Returns:

One rate per neighbouring pair, 0.0 where never attempted.

Return type:

list[float]

pair_schedule(segment)[source]#

Return the neighbouring state pairs attempted in segment.

Alternating even/odd offsets means every rung of the ladder is exchangeable with both neighbours over two segments, while no state appears in two pairs of the same segment — which is what lets all pairs be decided simultaneously.

Parameters:

segment (int) – Exchange segment index.

Returns:

Neighbouring (state_id, state_id + 1) pairs.

Return type:

list[tuple[int, int]]

per_system_params(state_ids)[source]#

Return the integrator parameters implied by an assignment.

The params_fn half of the swap: a state id is an index into the ladder, and what the integrator needs is the temperature it points at.

Parameters:

state_ids (Tensor) – Assignment, shape [B].

Returns:

{"temperature": T} in Kelvin per graph, shape [B].

Return type:

dict[str, torch.Tensor]

proposed_assignment(segment, state_ids)[source]#

Return the assignment that would result if every pair swapped.

Umbrella acceptance needs the bias evaluated under the proposed labels before the decision is made, so the caller needs the proposal separately from the outcome.

Parameters:
  • segment (int) – Exchange segment index.

  • state_ids (Tensor) – Current assignment, shape [B].

Returns:

The all-swaps-accepted assignment, shape [B].

Return type:

torch.Tensor

Raises:

ValueError – If state_ids is not a permutation of the ladder.

state_dict()[source]#

Return exchange state for checkpointing.

Returns:

Counters and the acceptance-RNG position. The position is two integers rather than a generator blob; see _uniforms().

Return type:

dict[str, Any]

swap_hook(*, bias_energy_fn=None, on_swap=None, slot_field='thermodynamic_state_id')[source]#

Return the generic swap hook that runs this ladder.

Everything mechanical — the pair schedule, the permutation, the cadence, the parameter rebinding — belongs to PairSwapHook. This supplies the two pieces that are enhanced-sampling physics: the Sugita-Okamoto acceptance rule and the temperature table it rebinds from. The tallies and the draw counter advance through the hook’s record_fn, so only a segment that actually commits counts.

Parameters:
  • bias_energy_fn (Callable[[Batch, torch.Tensor], torch.Tensor] | None) – (batch, state_ids) -> Tensor[B] giving the reduced bias potential under an assignment. Required for umbrella acceptance, which evaluates the bias under both the current and the proposed labels; unused by temperature acceptance.

  • on_swap (Callable[[Batch], None] | None) – Called with the batch after an accepted swap. Forces computed under the previous labels are what this is for.

  • slot_field (str) – Per-graph batch field holding the assignment.

Returns:

Configured for this ladder’s interval and rung count.

Return type:

PairSwapHook

property temperatures: Tensor#

Return the ladder temperatures in Kelvin, shape [S].

validate_assignment(state_ids, num_graphs=None, *, source='assignment')[source]#

Return state_ids as a validated [B] long tensor.

The bijection between walkers and states is the assumption every other piece rests on: pairing looks up “which walker holds state k”, and a duplicate or a wrong-length assignment makes that lookup meaningless. Without this the failures surface far from their cause — a length mismatch as ValueError: Length mismatch: 4 vs 2 from inside the batch storage, a duplicate as KeyError: 3 from the pair lookup — neither of which names the ladder or the batch.

Used for both the constructor argument and whatever assignment the batch actually carries, so the rule lives in one place.

Parameters:
  • state_ids (torch.Tensor) – Candidate assignment, any shape reshapeable to [B].

  • num_graphs (int | None) – Walker count to check the ladder against, when known.

  • source (str) – Name of the thing being validated, used in the error.

Returns:

The assignment as a 1-D long tensor.

Return type:

torch.Tensor

Raises:

ValueError – If the walker count disagrees with the ladder, or the assignment is not a permutation of 0..S-1.

validate_for(biases)[source]#

Reject bias/ladder combinations whose acceptance is undefined.

Parameters:

biases (Mapping[str, Any]) – The runner’s bias mapping.

Raises:

ValueError – If umbrella exchange is configured with no bias to exchange over, if any bias cannot supply the energy the acceptance rule needs, or if a state-dependent bias is combined with a temperature ladder.

Return type:

None