Skip to content

tencirlab.vmc

Source · Used by: Figure 2(a,b) · 6×6 PEPS versus exact densities

Variational Monte Carlo for number-conserving lattice models: local energies of Pauli operators, particle-exchange Metropolis sampling, stochastic reconfiguration, time integrators, and importance-sampled overlaps against a reference state.

States are configurations s of 0/1 occupations. A wave function enters as amplitude(theta, s) -> complex, holomorphic in the complex parameters theta.

PauliLocal

Bases: NamedTuple

Arrays for <s|H|s'> of a Pauli operator H on configurations s.

flips[g] is the bit mask of the g-th off-diagonal group, s' = s ^ flips[g]. Term t contributes coefficients[t] * (-1)**(z[t] . s) to group groups[:, t] or, for diagonal terms, to diagonal[t].

Source code in tencirlab/vmc.py
25
26
27
28
29
30
31
32
33
34
35
36
37
38
class PauliLocal(NamedTuple):
    """
    Arrays for ``<s|H|s'>`` of a Pauli operator ``H`` on configurations ``s``.

    ``flips[g]`` is the bit mask of the ``g``-th off-diagonal group, ``s' = s ^
    flips[g]``. Term ``t`` contributes ``coefficients[t] * (-1)**(z[t] . s)`` to group
    ``groups[:, t]`` or, for diagonal terms, to ``diagonal[t]``.
    """

    flips: jax.Array
    z: jax.Array
    coefficients: jax.Array
    groups: jax.Array
    diagonal: jax.Array

pauli_local

pauli_local(operator: PauliOperator) -> PauliLocal

Prepare a TenCirPauli operator; qubit i is occupation s[i].

Source code in tencirlab/vmc.py
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
def pauli_local(operator: tcp.PauliOperator) -> PauliLocal:
    """Prepare a TenCirPauli operator; qubit ``i`` is occupation ``s[i]``."""
    codes = np.array([term.word.to_codes() for term in operator.terms])
    x = np.isin(codes, (1, 2)).astype(np.int32)
    z = np.isin(codes, (2, 3)).astype(np.int32)
    # <s|Y|1-s> = -i (-1)**s and <s|Z|s> = (-1)**s
    phases = np.array([1, -1j, -1, 1j])[(x * z).sum(axis=1) % 4]
    coefficients = np.array([t.coefficient for t in operator.terms]) * phases
    masks, index = np.unique(x, axis=0, return_inverse=True)
    groups = np.eye(len(masks))[:, index.ravel()]
    diagonal = (x.sum(axis=1) == 0).astype(float)
    keep = masks.sum(axis=1) > 0
    return PauliLocal(
        jnp.asarray(masks[keep]),
        jnp.asarray(z),
        jnp.asarray(coefficients),
        jnp.asarray(groups[keep]),
        jnp.asarray(diagonal),
    )

local_energy

local_energy(
    amplitude: Amplitude,
    theta: Array,
    s: Array,
    operator: PauliLocal,
    max_connected: int | None = None,
) -> jax.Array

<s|H|psi> / <s|psi>. With max_connected, only that many connected configurations with the largest matrix elements are contracted, which is exact when no configuration has more nonzero elements, e.g. 4 min(N, L - N) for nearest-neighbour hopping of N particles on L square-lattice sites.

Source code in tencirlab/vmc.py
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
def local_energy(
    amplitude: Amplitude,
    theta: jax.Array,
    s: jax.Array,
    operator: PauliLocal,
    max_connected: int | None = None,
) -> jax.Array:
    """
    ``<s|H|psi> / <s|psi>``. With ``max_connected``, only that many connected
    configurations with the largest matrix elements are contracted, which is exact
    when no configuration has more nonzero elements, e.g. ``4 min(N, L - N)`` for
    nearest-neighbour hopping of ``N`` particles on ``L`` square-lattice sites.
    """
    terms = operator.coefficients * (1 - 2 * ((operator.z @ s) % 2))
    elements = operator.groups @ terms
    flips = operator.flips
    if max_connected is not None:
        _, top = jax.lax.top_k(jnp.abs(elements), max_connected)
        elements, flips = elements[top], flips[top]
    connected = jax.vmap(amplitude, (None, 0))(theta, s ^ flips)
    return operator.diagonal @ terms + elements @ connected / amplitude(theta, s)

scores

scores(
    amplitude: Amplitude, theta: Array, s: Array
) -> jax.Array

Log-derivatives O_k(s) = d log psi(s) / d theta_k.

Source code in tencirlab/vmc.py
85
86
87
88
def scores(amplitude: Amplitude, theta: jax.Array, s: jax.Array) -> jax.Array:
    """Log-derivatives ``O_k(s) = d log psi(s) / d theta_k``."""
    value, gradient = jax.value_and_grad(amplitude, holomorphic=True)(theta, s)
    return gradient / value

exchange_metropolis

exchange_metropolis(
    amplitude: Amplitude,
    theta: Array,
    states: Array,
    key: Array,
    n_steps: int,
    batch_size: int | None = None,
) -> tuple[jax.Array, jax.Array, jax.Array]

Metropolis chains at fixed particle number, sampling |psi|^2.

Each step moves one uniformly chosen particle of every chain to a uniformly chosen empty site, so the proposal is symmetric. Returns the states, the acceptance rate, and the new key.

Source code in tencirlab/vmc.py
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
def exchange_metropolis(
    amplitude: Amplitude,
    theta: jax.Array,
    states: jax.Array,
    key: jax.Array,
    n_steps: int,
    batch_size: int | None = None,
) -> tuple[jax.Array, jax.Array, jax.Array]:
    """
    Metropolis chains at fixed particle number, sampling ``|psi|^2``.

    Each step moves one uniformly chosen particle of every chain to a uniformly
    chosen empty site, so the proposal is symmetric. Returns the states, the
    acceptance rate, and the new key.
    """

    def log_prob(s):
        values = jax.lax.map(lambda c: amplitude(theta, c), s, batch_size=batch_size)
        return 2 * jnp.log(jnp.abs(values))

    def step(carry, _):
        states, current, accepted, key = carry
        key, k1, k2 = jax.random.split(key, 3)
        u = jax.random.uniform(k1, states.shape)
        occupied = jnp.argmax(jnp.where(states == 1, u, -1.0), axis=1)
        empty = jnp.argmax(jnp.where(states == 0, u, -1.0), axis=1)
        rows = jnp.arange(states.shape[0])
        proposal = states.at[rows, occupied].set(0).at[rows, empty].set(1)
        proposed = log_prob(proposal)
        accept = jnp.log(jax.random.uniform(k2, current.shape)) < proposed - current
        states = jnp.where(accept[:, None], proposal, states)
        current = jnp.where(accept, proposed, current)
        return (states, current, accepted + accept.mean(), key), None

    (states, _, accepted, key), _ = jax.lax.scan(
        step, (states, log_prob(states), 0.0, key), None, length=n_steps
    )
    return states, accepted / n_steps, key

sr_solve

sr_solve(
    o: Array, eloc: Array, diag_shift: float
) -> jax.Array

Solve the centered stochastic-reconfiguration equations S x = F with S = Obar^dag Obar / N, F = Obar^dag Ebar / N, and a diagonal shift.

Uses the P x P form when there are more samples N than parameters P and the N x N (minSR) form otherwise, as in arXiv:2512.06768. Exact null directions of Obar, such as PEPS gauge directions, have no component in F, so the shift removes them from the solution without an explicit projector.

Source code in tencirlab/vmc.py
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
def sr_solve(o: jax.Array, eloc: jax.Array, diag_shift: float) -> jax.Array:
    """
    Solve the centered stochastic-reconfiguration equations ``S x = F`` with
    ``S = Obar^dag Obar / N``, ``F = Obar^dag Ebar / N``, and a diagonal shift.

    Uses the ``P x P`` form when there are more samples ``N`` than parameters
    ``P`` and the ``N x N`` (minSR) form otherwise, as in arXiv:2512.06768. Exact
    null directions of ``Obar``, such as PEPS gauge directions, have no component in
    ``F``, so the shift removes them from the solution without an explicit projector.
    """
    n, p = o.shape
    o = (o - o.mean(axis=0)) / jnp.sqrt(n)
    e = (eloc - eloc.mean()) / jnp.sqrt(n)
    if n > p:
        s = o.conj().T @ o
        return jnp.linalg.solve(
            s + diag_shift * jnp.eye(p, dtype=s.dtype), o.conj().T @ e
        )
    t = o @ o.conj().T
    return o.conj().T @ jnp.linalg.solve(t + diag_shift * jnp.eye(n, dtype=t.dtype), e)

rk4_step

rk4_step(
    velocity: Velocity[Carry],
    theta: Array,
    carry: Carry,
    dt: float,
) -> tuple[jax.Array, Carry, jax.Array]

Fourth-order Runge-Kutta step of d theta / dt = v, where velocity(theta, carry) -> (v, carry, info) threads sampler state through the four stages. Returns the new parameters, carry, and the first stage's info.

Source code in tencirlab/vmc.py
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
def rk4_step(
    velocity: Velocity[Carry], theta: jax.Array, carry: Carry, dt: float
) -> tuple[jax.Array, Carry, jax.Array]:
    """
    Fourth-order Runge-Kutta step of ``d theta / dt = v``, where
    ``velocity(theta, carry) -> (v, carry, info)`` threads sampler state through the
    four stages. Returns the new parameters, carry, and the first stage's info.
    """

    def stage(state, tableau):
        previous, total, carry = state
        offset, weight = tableau
        direction, carry, info = velocity(theta + dt * offset * previous, carry)
        return (direction, total + weight * direction, carry), info

    zero = jnp.zeros_like(theta)
    dtype = theta.real.dtype
    tableau = (
        jnp.array([0.0, 0.5, 0.5, 1.0], dtype=dtype),
        jnp.array([1.0, 2.0, 2.0, 1.0], dtype=dtype),
    )
    (_, total, carry), info = jax.lax.scan(stage, (zero, zero, carry), tableau)
    return theta + dt / 6 * total, carry, info[0]

euler_step

euler_step(
    velocity: Velocity[Carry],
    theta: Array,
    carry: Carry,
    dt: float,
) -> tuple[jax.Array, Carry, jax.Array]

Euler step that threads the velocity evaluation's state and diagnostics.

Source code in tencirlab/vmc.py
178
179
180
181
182
183
def euler_step(
    velocity: Velocity[Carry], theta: jax.Array, carry: Carry, dt: float
) -> tuple[jax.Array, Carry, jax.Array]:
    """Euler step that threads the velocity evaluation's state and diagnostics."""
    v, carry, info = velocity(theta, carry)
    return theta + dt * v, carry, info

tvmc_velocity

tvmc_velocity(
    amplitude: Amplitude,
    operator: PauliLocal,
    n_sweeps: int,
    diag_shift: float,
    imaginary: bool = False,
    max_connected: int | None = None,
    batch_size: int | None = None,
    sample_batch_size: int | None = None,
) -> Velocity[tuple[jax.Array, jax.Array]]

Parameter velocity of the time-dependent variational principle, theta' = -i S^{-1} F in real time and -S^{-1} F in imaginary time, with S and F estimated from Metropolis chains. velocity(theta, (states, key)) advances the chains by n_sweeps exchange moves per site and returns (v, (states, key), (energy, energy_variance, acceptance)). Energy and score batches use batch_size; Metropolis proposals can use sample_batch_size because each proposal contracts only one amplitude.

Source code in tencirlab/vmc.py
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
def tvmc_velocity(
    amplitude: Amplitude,
    operator: PauliLocal,
    n_sweeps: int,
    diag_shift: float,
    imaginary: bool = False,
    max_connected: int | None = None,
    batch_size: int | None = None,
    sample_batch_size: int | None = None,
) -> Velocity[tuple[jax.Array, jax.Array]]:
    """
    Parameter velocity of the time-dependent variational principle,
    ``theta' = -i S^{-1} F`` in real time and ``-S^{-1} F`` in imaginary time, with
    ``S`` and ``F`` estimated from Metropolis chains. ``velocity(theta, (states,
    key))`` advances the chains by ``n_sweeps`` exchange moves per site and returns
    ``(v, (states, key), (energy, energy_variance, acceptance))``.
    Energy and score batches use ``batch_size``; Metropolis proposals can use
    ``sample_batch_size`` because each proposal contracts only one amplitude.
    """

    def per_sample(theta, s):
        return scores(amplitude, theta, s), local_energy(
            amplitude, theta, s, operator, max_connected
        )

    def velocity(theta, carry):
        states, key = carry
        states, acceptance, key = exchange_metropolis(
            amplitude, theta, states, key, n_sweeps * states.shape[1], sample_batch_size
        )
        o, eloc = jax.lax.map(
            lambda s: per_sample(theta, s), states, batch_size=batch_size
        )
        x = sr_solve(o, eloc, diag_shift)
        v = -x if imaginary else -1j * x
        info = jnp.stack([eloc.mean().real, eloc.var(), acceptance])
        return v, (states, key), info

    return velocity

overlap_block

overlap_block(
    ratios: Array, observables: Array
) -> jax.Array

Sums over a block of samples s ~ |phi(s)|^2 with ratios = psi(s) / phi(s) and diagonal observables of shape (samples, k): [count, sum r, sum w, sum w^2, sum w obs_1..k] with w = |r|^2. Sums of sub-batches add up.

Source code in tencirlab/vmc.py
227
228
229
230
231
232
233
234
235
def overlap_block(ratios: jax.Array, observables: jax.Array) -> jax.Array:
    """
    Sums over a block of samples ``s ~ |phi(s)|^2`` with ``ratios = psi(s) / phi(s)``
    and diagonal ``observables`` of shape ``(samples, k)``: ``[count, sum r, sum w,
    sum w^2, sum w obs_1..k]`` with ``w = |r|^2``. Sums of sub-batches add up.
    """
    w = jnp.abs(ratios) ** 2
    head = jnp.stack([ratios.shape[0], ratios.sum(), w.sum(), w @ w])
    return jnp.concatenate([head, w @ observables])

overlap_estimate

overlap_estimate(
    blocks: ndarray,
) -> dict[str, np.ndarray | np.floating]

Self-normalized importance estimates from overlap_block sums of independent blocks, with delete-one-block jackknife errors: the infidelity 1 - |<phi|psi>|^2 / (<phi|phi> <psi|psi>), <psi|obs|psi> / <psi|psi>, and the effective sample size of the weights.

Source code in tencirlab/vmc.py
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
def overlap_estimate(blocks: np.ndarray) -> dict[str, np.ndarray | np.floating]:
    """
    Self-normalized importance estimates from ``overlap_block`` sums of independent
    blocks, with delete-one-block jackknife errors: the infidelity ``1 -
    |<phi|psi>|^2 / (<phi|phi> <psi|psi>)``, ``<psi|obs|psi> / <psi|psi>``, and the
    effective sample size of the weights.
    """
    blocks = np.asarray(blocks)

    def estimate(sums):
        n, r, w = sums[0].real, sums[1], sums[2].real
        return np.concatenate([[1 - abs(r) ** 2 / (n * w)], sums[4:].real / w])

    total = blocks.sum(axis=0)
    deleted = np.stack([estimate(total - b) for b in blocks])
    m = len(blocks)
    error = np.sqrt((m - 1) / m * ((deleted - deleted.mean(axis=0)) ** 2).sum(axis=0))
    value = estimate(total)
    return {
        "infidelity": value[0],
        "infidelity_error": error[0],
        "observables": value[1:],
        "observables_error": error[1:],
        "effective_samples": total[2].real ** 2 / total[3].real,
    }

integrate

integrate(
    step: Stepper[Carry],
    velocity: Velocity[Carry],
    theta: Array,
    carry: Carry,
    dt: float,
    n_steps: int,
    normalize: Callable[
        [Array], Array
    ] = lambda theta: theta,
) -> tuple[jax.Array, Carry, jax.Array]

n_steps steps of step (rk4_step or euler_step) in one scan, applying normalize after each. Returns the parameters, the carry, and the per-step info of shape (n_steps, ...).

Source code in tencirlab/vmc.py
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
def integrate(
    step: Stepper[Carry],
    velocity: Velocity[Carry],
    theta: jax.Array,
    carry: Carry,
    dt: float,
    n_steps: int,
    normalize: Callable[[jax.Array], jax.Array] = lambda theta: theta,
) -> tuple[jax.Array, Carry, jax.Array]:
    """
    ``n_steps`` steps of ``step`` (``rk4_step`` or ``euler_step``) in one scan,
    applying ``normalize`` after each. Returns the parameters, the carry, and the
    per-step info of shape ``(n_steps, ...)``.
    """

    def body(state, _):
        theta, carry = state
        theta, carry, info = step(velocity, theta, carry, dt)
        return (normalize(theta), carry), info

    (theta, carry), info = jax.lax.scan(body, (theta, carry), None, length=n_steps)
    return theta, carry, info

History

Date Pull request Kind Change
2026-12-01 #10 migration Fermionic PEPS–tVMC corner quench