Algorithm Search⌘K

Algorithmadvanced

Parallel replica dynamics

Runs copies of a system in one basin on many processors and adds their times up to the first escape. Exact when escapes are exponential after dephasing.

Time
O((m c + s) G) expected
Space
O(m d) extra
Where
G = the cost of one step; c = the dephasing and decorrelation length in steps; d = the number of coordinates; m = the number of replicas; s = the mean escape time in steps
Properties
randomizednot exactiterativeparallelrandomized
Origin
Arthur F. Voter, 1998

Parallel replica dynamics accelerates a simulation of a system that moves by rare escapes from basins, by using many processors on one trajectory. It runs mm independent copies, the replicas, of the system in the current basin. When the first replica escapes, the physical clock advances by the sum of the times of all replicas, and the trajectory continues from the escaped replica. If the escape law is exponential once the replicas have forgotten their starting point, which takes a short dephasing run, the output has the same law as one long serial run. The method needs no knowledge of the exits and no transition state theory. The parallel speedup, at most mm, is a measured property of each run.

In plain words

You wait for a rare event, such as a lamp that fails at random with no memory of its age. One lamp may take a year. Light a hundred lamps at once and the first one fails after a few days on average. A hundred lamps for a few days is the same amount of lamp time as one lamp for a year, so the sum of the times of all lamps is the real waiting time, and the lamp that failed shows how it failed.

The trick only works for events with no memory. A system that just entered a basin does have a memory of where it came from. So each copy first runs a short time in the basin to forget it, and only then the race starts.

The problem

The input is a dynamics given as one time step of length hh, a map from a point to the label of its basin, the number mm of replicas, and a correlation length cc in steps. The output is the sequence of basins visited and the time of each change, with the law of a serial run. The method assumes that the dynamics is Markov, that escapes are rare compared with the time chc h that a trajectory needs to lose the memory of its entry into a basin, and that the replicas are statistically independent.

The algorithm

  1. PARALLEL-REPLICA-DYNAMICS(x, step, state_of, m, c, h)
  2. 1t ← 0; s ← state_of(x)
  3. 2repeat
  4. 3run x serially, t ← t + h per step, until x has stayed c steps in one basin
  5. 4every change of basin s → s' in L3 is a transition at time t (a correlated event)
  6. 5dephase: start m replicas at x; run each until it stays c steps in s, restarting it at x when it leaves (t does not change)
  7. 6run all replicas one step at a time, in parallel
  8. 7at the first step w at which some replica leaves s, take the smallest such index j
  9. 8t ← t + (m (w - 1) + j) h
  10. 9x ← replica j; record the transition s → state_of(x) at time t; s ← state_of(x)
  11. 10until enough transitions; return the transitions and t

Lines L3 and L4 are the decorrelation stage. After an escape the system can recross into the old basin or move on to a third one at once; these correlated events are not exponential, so they are followed by one serial trajectory with the true clock. Line L5 is the dephasing stage: each replica runs in the basin until it has forgotten its starting point, and a replica that leaves is restarted. These steps cost work but do not advance the clock. Lines L6 to L9 are the parallel stage. The clock in line L8 counts the trials of all replicas in the order (step, replica) up to the first escape. In continuous time the same rule is t←t+m tfirstt \leftarrow t + m\, t_{\mathrm{first}}.

Example

The clock by hand. Take a chain with one basin AA and two exits: from AA it goes to BB with probability 0.15 and to CC with probability 0.05 per step. Let m=3m = 3 and c=1c = 1. The decorrelation step stays in AA and adds 1 to the clock. Each replica dephases for 1 step and stays. In the first parallel step no replica leaves. In the second, replica 2 goes to BB and replica 3 goes to CC. Replica 2 is the first, so the clock advances by m(w−1)+j=3⋅1+2=5m (w - 1) + j = 3 \cdot 1 + 2 = 5, to t=6t = 6, and the next state is BB. The work is 10 steps and the elapsed time on 3 processors is 4 steps.

Exactness. For this chain the serial escape time is geometric with mean 1/0.2=51 / 0.2 = 5 steps and the exit is BB with probability 0.75. With c=5c = 5 and 2000 transitions from random.Random(2) for each mm:

mm mean time standard error fraction to BB
1 5.047 0.100 0.760
4 4.997 0.101 0.761
16 4.971 0.098 0.760

All agree with the serial law. Here the escape is so fast that the dephasing costs more than the race saves.

A measurement of the speedup. Take Brownian dynamics dx=−V′(x) dt+2kBT dWdx = -V'(x)\, dt + \sqrt{2 k_B T}\, dW in the double well V=(x2−1)2V = (x^2 - 1)^2 with kBT=1/3k_B T = 1/3, Euler-Maruyama steps h=0.01h = 0.01, the basins x<0x < 0 and x≥0x \ge 0, and c=50c = 50 steps. From x=−1x = -1, 300 first transitions for each mm, random.Random(1):

mm mean escape time standard error elapsed steps measured speedup efficiency
1 14.18 0.84 440321 0.97 0.97
4 14.41 0.94 135304 3.19 0.80
16 13.17 0.69 57237 6.90 0.43
64 12.90 0.71 44321 8.73 0.14

The mean times agree within the errors. The mean first passage time of the continuous dynamics is 12.70 by quadrature; the Euler steps see the crossing late, which makes the serial value of this discrete chain larger. The speedup is the physical time over the elapsed time: it is a measurement, and it saturates because the 50 dephasing steps and the 50 decorrelation steps per transition are not divided by mm, while the mean escape takes only about 1300 steps.

Correctness

The proof is in the correctness proof of this page. Its core is a property of the quasi-stationary distribution (QSD) ν\nu of the basin, the law of a long trajectory that has not left: from ν\nu, the exit step is geometric (exponential in continuous time) and the exit point is independent of the exit step. For mm independent replicas from ν\nu, the count m(w−1)+jm (w - 1) + j of line L8 then has the same geometric law, and the exit of replica jj has the same law as a serial exit. So the parallel stage is exact if the replicas start from ν\nu. The approximation is that the dephasing and decorrelation stages reach ν\nu only in the limit, with an error that decays exponentially in cc at the rate of the spectral gap of the dynamics killed outside the basin. For a chain with the same escape probability from every point of the basin, as in the first example, every distribution is a QSD and the method is exact.

Proof: Why the parallel stage gives the law of a serial escapefull

We prove the claim for a discrete-time Markov chain, as in the implementation. The proof has an exact part, for replicas that start from the quasi-stationary distribution of the basin, and an approximate part, which is the error of the dephasing and decorrelation stages.

Setting. (Xn)(X_n) is a Markov chain with time step hh. WW is the current basin, and τ=min⁡{n≥1:Xn∉W}\tau = \min\{n \ge 1 : X_n \notin W\} is the exit step. A probability measure ν\nu on WW is a quasi-stationary distribution (QSD) if, for X0∼νX_0 \sim \nu, the law of X1X_1 given τ>1\tau > 1 is again ν\nu. Write p=Pν(τ=1)p = P_\nu(\tau = 1).

Lemma 1 (exit from the QSD). If X0∼νX_0 \sim \nu, then for every n≥1n \ge 1 and every set BB outside WW,

Pν(τ=n, Xτ∈B)=(1−p)n−1 Pν(τ=1, X1∈B).P_\nu(\tau = n,\ X_\tau \in B) = (1 - p)^{n-1}\, P_\nu(\tau = 1,\ X_1 \in B).

So τ\tau is geometric with parameter pp, and the exit point XτX_\tau is independent of τ\tau.

Proof. By induction on nn. The case n=1n = 1 is trivial. For n≥2n \ge 2, by the Markov property at time 1, Pν(τ=n,Xτ∈B)=Pν(τ>1) Pμ(τ=n−1,Xτ∈B)P_\nu(\tau = n, X_\tau \in B) = P_\nu(\tau > 1)\, P_{\mu}(\tau = n - 1, X_\tau \in B), where μ\mu is the law of X1X_1 given τ>1\tau > 1. By the definition of the QSD, μ=ν\mu = \nu, and Pν(τ>1)=1−pP_\nu(\tau > 1) = 1 - p. The induction hypothesis gives the claim. The right side is a product of a function of nn and a function of BB, which is the independence. □\square

Lemma 2 (the parallel stage). Let Y1,…,YmY^1, \ldots, Y^m be independent copies of the chain, each started from ν\nu, with exit steps τ1,…,τm\tau_1, \ldots, \tau_m. Let w=min⁡jτjw = \min_j \tau_j, let JJ be the smallest jj with τj=w\tau_j = w, and let N=m(w−1)+JN = m (w - 1) + J. Then NN is geometric with parameter pp, and YwJY^J_w has the law of XτX_\tau under PνP_\nu, independent of NN. This is the content of lines L6 to L9.

Proof. Fix n=m(w−1)+jn = m (w - 1) + j with 1≤j≤m1 \le j \le m. The event {N=n,YwJ∈B}\{N = n, Y^J_w \in B\} says: replicas 1,…,j−11, \ldots, j - 1 have τi>w\tau_i > w, replica jj has τj=w\tau_j = w and exits into BB, and replicas j+1,…,mj + 1, \ldots, m have τi>w−1\tau_i > w - 1. By independence and Lemma 1, the probability is

(1−p)w(j−1)⋅(1−p)w−1Pν(τ=1,X1∈B)⋅(1−p)(w−1)(m−j).(1-p)^{w (j-1)} \cdot (1-p)^{w-1} P_\nu(\tau = 1, X_1 \in B) \cdot (1-p)^{(w-1)(m-j)}.

The exponent of 1−p1 - p is w(j−1)+(w−1)+(w−1)(m−j)=m(w−1)+j−1=n−1w (j - 1) + (w - 1) + (w - 1)(m - j) = m (w - 1) + j - 1 = n - 1. So the probability is (1−p)n−1Pν(τ=1,X1∈B)(1-p)^{n-1} P_\nu(\tau = 1, X_1 \in B), the same as Lemma 1 with nn in place of the serial exit step. □\square

The proof shows why the accounting m(w−1)+jm (w - 1) + j is exact: it orders the trials of the replicas as (step, replica) and counts the trials up to the first success, and independent geometric trials in any fixed order give a geometric count. The accounting mwm w is not exact for discrete steps: it makes the time a multiple of mm.

Theorem. Suppose that each dephased replica of line L5 has the law ν\nu, and that the trajectory at the end of the decorrelation stage of lines L3 and L4 has the law ν\nu. Then the clock increment and the next state of the parallel stage have the same joint law as the exit step and the exit point of one serial trajectory from the same point. Because the decorrelation stage is a serial run, the whole output (the times and the sequence of states) has the law of a serial run of the chain.

Proof. The decorrelation stage is the serial chain itself. At its end, by hypothesis the state has the law ν\nu, and by Lemma 1 the remaining serial exit is geometric with parameter pp and independent of the exit point. Lemma 2 gives the same joint law for the parallel stage. ■\blacksquare

The exact case. If the escape probability from each point of WW is the same number pp and the law of the exit point does not depend on the point, every probability measure on WW is a QSD with the same pp, and the theorem holds with no approximation. This is the chain of the first two tests.

What is approximate. For a real dynamics the hypotheses hold only in the limit. Line L5 restarts a replica that leaves, so each dephased replica has the law of XncorrX_{n_{\mathrm{corr}}} given τ>ncorr\tau > n_{\mathrm{corr}} for the chain started at the current point. If the chain killed outside WW is reversible with a spectral gap, this law converges to the QSD at the rate (λ2/λ1)ncorr(\lambda_2 / \lambda_1)^{n_{\mathrm{corr}}}, where λ1>∣λ2∣\lambda_1 > |\lambda_2| are the two largest eigenvalues of the killed chain (Le Bris, Lelievre, Luskin and Perez 2012, in continuous time). The same holds for the end of the decorrelation stage. So the error in law of each transition is of order (λ2/λ1)ncorr(\lambda_2 / \lambda_1)^{n_{\mathrm{corr}}}. For a deep basin the convergence is fast compared with the escape, and the error is small.

What is not proved. The theorem says nothing about the speedup. The elapsed time with mm processors is the decorrelation time, plus the longest dephasing, plus ww parallel steps, and only the last part is divided by mm. The speedup of a run is a measurement.

Complexity

Per transition, the decorrelation costs about cc steps, the dephasing mcm c steps or more with restarts, and the parallel stage about ss steps of work for a mean escape time of ss steps, so the work is O((mc+s)G)O((m c + s) G) and the elapsed time on mm processors is O((c+s/m)G)O((c + s / m) G) in the real RAM model, with O(md)O(m d) memory. The speedup approaches mm only when s≫mcs \gg m c, that is, when the escapes are much rarer than the dephasing time times the number of replicas. The speedup of a run is a measurement.

Properties

  • Exact for exponential escapes. If the replicas are in the QSD, the output has the law of the serial dynamics. No transition state theory and no harmonic approximation is used.
  • No knowledge of the exits. The escapes are found by the dynamics itself, so unexpected mechanisms are found as well.
  • Parallel in time. Unlike domain decomposition, it parallelizes the time axis of a small system.
  • Randomized. The output is one sample path of the state-to-state dynamics.

Variants and improvements

  • Continuous time. With exponential escapes the clock advances by m tfirstm\, t_{\mathrm{first}}; Voter's paper of 1998 states it in this form.
  • Discrete-time accounting. The count m(w−1)+jm (w - 1) + j of line L8 is exact for geometric escapes; the version for Markov chains of Aristoff, Lelievre and Simpson in 2014 uses it.
  • Fleming-Viot dephasing. Instead of restarting a replica that leaves at the starting point, restart it at the position of another replica. This samples the QSD with an interacting particle system, and the spread of the replicas gives a test of convergence.
  • Combination with hyperdynamics. Each replica can run biased dynamics, and the clock of each replica is then its hyper time.
  • Asynchronous replicas. Replicas on different processors need not be in step; in continuous time the times of all replicas are added up to the first escape.

When to use it

Use parallel replica dynamics when many processors are available, escapes are rare compared with the correlation time in a basin, and transition state theory or a bias for hyperdynamics is not reliable, for example for complex rearrangements at moderate temperature. Use kinetic Monte Carlo when the catalog of events is known, and temperature accelerated dynamics when harmonic TST holds and the boost of parallel replicas is not enough.

Pitfalls

  • Too short dephasing. If the replicas still remember the entry into the basin, the first escape is biased towards the early, correlated exits. The error decays only like e−λche^{-\lambda c h} with the gap λ\lambda of the killed dynamics.
  • Basins with internal barriers. If a basin has slow internal motion, the QSD is reached slowly and the escape is not exponential. Define the states so that each is one well.
  • Correlated replicas. The replicas need independent random streams. Copies of the same seed give the same trajectory.
  • Discrete clocks. Advancing the clock by mwm w steps for discrete time makes every time a multiple of mm; use the count of line L8.
  • Expecting a speedup of mm. The dephasing and decorrelation stages are serial in time, so the speedup saturates, as in the example.

Implementations

Each implementation follows the pseudocode above. A comment @line links a line of code to a line of the pseudocode. Point at a line of the pseudocode to see the matching code. The build runs the native tests of each language.

parallel_replica_dynamics.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/parallel-replica-dynamics/. The authors are listed in prov/6Z28SF.jsonl.
"""Parallel replica dynamics (Voter 1998) for a dynamics given as a time step.

step(x, rng) returns the state after one time step of length h, and
state_of(x) returns the label of the basin that contains x. One cycle has
three stages:

1. Decorrelation. One trajectory runs serially, and the clock advances
   with it, until it has stayed n_corr steps in one basin. Every change of
   basin in this stage is a transition of the output.
2. Dephasing. m replicas start from the current point and each runs until
   it has stayed n_corr steps in the basin. A replica that leaves the
   basin restarts. These steps do not advance the clock.
3. Parallel stage. All replicas advance one step at a time. At the first
   step w at which some replica leaves, take the smallest such index j
   (1-based). The clock advances by (m (w - 1) + j) h, and the trajectory
   continues from that replica.

If the escape from the basin is exponential (geometric, for discrete
steps) once the replicas are dephased, the time and the exit of each
transition have the same law as for one serial trajectory. This holds
exactly for a chain whose escape probability per step is constant in the
basin, and approximately for a real dynamics after dephasing. The speedup
is a measurement.

The time accounting m (w - 1) + j counts the trials of the replicas as if
they were done one after the other in the order (step, replica). This is
the accounting of Aristoff, Lelievre and Simpson (2014) for Markov chains.
"""

from typing import Callable, Hashable


def parallel_replica_dynamics(x0, step: Callable, state_of: Callable[[object], Hashable], m: int,
                              n_corr: int, rng, n_transitions: int, h: float = 1.0,
                              max_work: int = 10**7):
    """Run parallel replica dynamics until n_transitions changes of basin.

    Returns (x, t, transitions, work, wall): the final point, the clock, the
    list of (time, from_state, to_state), the total number of steps of all
    replicas (the cost), and the number of steps on the longest replica
    (the elapsed time on m processors, in steps). The measured speedup of a
    run is t / (h wall). Raises RuntimeError if work exceeds max_work.
    """
    x = x0
    s = state_of(x)
    t = 0.0                                                             # @line L1
    transitions = []
    work = 0
    wall = 0

    def charge(n=1):
        nonlocal work
        work += n
        if work > max_work:
            raise RuntimeError("parallel_replica_dynamics: max_work exceeded")

    while len(transitions) < n_transitions:                             # @line L2
        k = 0
        while k < n_corr and len(transitions) < n_transitions:
            x = step(x, rng)                                            # @line L3
            t += h
            charge()
            wall += 1
            k += 1
            s_new = state_of(x)
            if s_new != s:
                transitions.append((t, s, s_new))                       # @line L4
                s = s_new
                k = 0
        if len(transitions) >= n_transitions:
            break
        replicas = []
        longest = 0
        for _ in range(m):                                              # @line L5
            y, k, n = x, 0, 0
            while k < n_corr:
                y = step(y, rng)
                charge()
                n += 1
                k += 1
                if state_of(y) != s:
                    y, k = x, 0
            replicas.append(y)
            longest = max(longest, n)
        wall += longest
        w = 0
        while True:
            w += 1
            for j in range(m):                                          # @line L6
                replicas[j] = step(replicas[j], rng)
            charge(m)
            wall += 1
            first = next((j for j in range(m) if state_of(replicas[j]) != s), None)  # @line L7
            if first is not None:
                t += (m * (w - 1) + first + 1) * h                      # @line L8
                x = replicas[first]
                s_new = state_of(x)
                transitions.append((t, s, s_new))                       # @line L9
                s = s_new
                break
    return x, t, transitions, work, wall                                # @line L10
test_parallel_replica_dynamics.py 121 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/parallel-replica-dynamics/. The authors are listed in prov/6Z28SF.jsonl.
import math
import random

import pytest

from parallel_replica_dynamics import parallel_replica_dynamics

P_B, P_C = 0.15, 0.05


def bernoulli_step(x, rng):
    """From A, go to B with probability P_B and to C with probability P_C per step."""
    if x != "A":
        return x
    u = rng.random()
    if u < P_B:
        return "B"
    if u < P_B + P_C:
        return "C"
    return "A"


def label(x):
    return x


class Script:
    def __init__(self, values):
        self.values = list(values)

    def random(self):
        return self.values.pop(0)


def test_time_accounting_by_hand():
    # n_corr = 1, m = 3. Decorrelation: 1 step, no escape. Dephasing: 1 step
    # per replica, no escape. Parallel stage: step 1 has no escape; at step 2
    # replicas 2 and 3 escape, and replica 2 is the first. t = 1 + 3*1 + 2 = 6.
    rng = Script([0.9, 0.9, 0.9, 0.9, 0.9, 0.9, 0.9, 0.9, 0.0, 0.17])
    x, t, transitions, work, wall = parallel_replica_dynamics("A", bernoulli_step, label, 3, 1, rng, 1)
    assert x == "B"
    assert t == 6.0
    assert transitions == [(6.0, "A", "B")]
    assert work == 1 + 3 + 6
    assert wall == 1 + 1 + 2
    assert rng.values == []


def test_geometric_escape_law_is_kept():
    # With a constant escape probability, the time of the first transition is
    # geometric with mean 1 / (P_B + P_C) = 5 for any m, and the exit is B
    # with probability 0.75.
    rng = random.Random(2)
    times, to_b, work = [], 0, 0
    for _ in range(300):
        _, t, transitions, w, _ = parallel_replica_dynamics("A", bernoulli_step, label, 4, 5, rng, 1)
        assert t == int(t) and t >= 1
        times.append(t)
        to_b += transitions[0][2] == "B"
        work += w
    assert work <= 10000
    n = len(times)
    mean = sum(times) / n
    se = math.sqrt(sum((v - mean) ** 2 for v in times) / (n - 1) / n)
    assert abs(mean - 5.0) < 3.0 * se
    assert abs(to_b / n - 0.75) < 3.0 * math.sqrt(0.75 * 0.25 / n)


KT = 0.5
H = 0.01
SIGMA = math.sqrt(2.0 * KT * H)


def double_well_step(x, rng):
    return x - H * 4.0 * x * (x * x - 1.0) + SIGMA * rng.gauss(0.0, 1.0)


def side(x):
    return x >= 0.0


def test_bookkeeping_on_a_double_well():
    rng = random.Random(5)
    x, t, transitions, work, wall = parallel_replica_dynamics(-1.0, double_well_step, side, 4, 20, rng, 4,
                                                              h=H, max_work=10000)
    assert len(transitions) == 4
    times = [tr[0] for tr in transitions]
    assert times == sorted(times) and times[-1] == pytest.approx(t)
    for (_, a, b), (_, c, _) in zip(transitions, transitions[1:]):
        assert a != b and b == c
    assert transitions[0][1] is False and transitions[-1][2] == side(x)
    assert wall <= work


def test_mean_escape_time_of_a_double_well():
    # Mean first passage time from -1 to 0 for the continuous dynamics: 4.607
    # (quadrature). The Euler steps with h = 0.01 detect the crossing late,
    # which adds about 0.4 (a long serial run gives 5.05). Loose check.
    rng = random.Random(1)
    times, work = [], 0
    while True:
        try:
            _, t, _, w, _ = parallel_replica_dynamics(-1.0, double_well_step, side, 4, 20, rng, 1,
                                                      h=H, max_work=10000 - work)
        except RuntimeError:
            break
        times.append(t)
        work += w
    n = len(times)
    assert n >= 10
    mean = sum(times) / n
    se = math.sqrt(sum((v - mean) ** 2 for v in times) / (n - 1) / n)
    assert abs(mean - 4.607) < 3.0 * se + 0.5


def test_max_work():
    with pytest.raises(RuntimeError):
        parallel_replica_dynamics(-1.0, double_well_step, side, 4, 20, random.Random(1), 100,
                                  h=H, max_work=500)

History

Voter gave parallel replica dynamics in 1998 as the second of his accelerated molecular dynamics methods, after hyperdynamics in 1997. The justification was the exponential escape law of transition state theory, with a dephasing and a decorrelation time chosen from the physics. In 2012 Le Bris, Lelievre, Luskin and Perez gave the mathematical analysis: the dephased replicas approach the quasi-stationary distribution of the basin, and from it the escape is exactly exponential and independent of the exit point. Aristoff, Lelievre and Simpson gave the version for Markov chains in 2014.

References

  1. Arthur F. Voter, Parallel replica method for dynamics of infrequent events, Physical Review B 57(22), 1998, R13985, the dephasing stage, the parallel stage with the summed clock, and the decorrelation stage for correlated events
  2. Claude Le Bris, Tony Lelievre, Mitchell Luskin and Danny Perez, A mathematical formalization of the parallel replica dynamics, Monte Carlo Methods and Applications 18(2), 2012, the quasi-stationary distribution, the exponential exit law and the error of the dephasing
  3. David Aristoff, Tony Lelievre and Gideon Simpson, The parallel replica method for simulating long trajectories of Markov chains, Applied Mathematics Research eXpress 2014(2), 2014, 332-352, the version for discrete-time Markov chains and its time accounting

About this page

The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.

LadderLevelWhat the next level needs
Human proofH1 sketch
  • a full proof of time.expected
  • a full proof of space.extra
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
Code (python)I0 not checked yet
  • the tests did not run in this build
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW2 basic
  • a scene preset for the example