"""BUG-CCSD: adaptive low-rank RCCSD on density-fitted integrals.
The doubles amplitude is kept as ``T = U diag(S) U^T`` in occupied-virtual
pair space. Each iteration applies the CCSD doubles numerator ``N(t1, T)`` to
the basis, augments the basis with residual directions, solves the Galerkin
(Sylvester) problem in the augmented space and truncates by eigenvalue
magnitude (basis update & Galerkin, BUG). ``N`` is exact at the retained
rank: no dense T2 or residual is stored. The occupied ladder W*tau and the
crossed ring Z*T, with their t1-dressed integrals, form one pair-space
operator X built once per state on the device (sixth order); everything else
is a DF contraction of fifth order.
The action runs on JAX (GPU, or CPU for the tests); the DF factors live on
the host and are uploaded once per solve, or streamed in auxiliary chunks
when they exceed ``bug_helper.RESIDENT_LIMIT_BYTES``. The reference for ``N`` is PySCF's
DF-RCCSD numerator: ``N(t1, T) V`` is PySCF's doubles numerator in pair form
applied to ``V``.
"""
from __future__ import annotations
import time
from functools import partial
from typing import NamedTuple
import jax
import jax.numpy as jnp
import numpy as np
from pytc.solver.bug_core import (
LowRankResult,
amplitude_step,
check_stop,
plateau_tol,
extract_df_factors,
require_float64,
sylvester,
truncate_sym,
)
from pytc.solver.bug_core import orth_directions, project_directions, requested_aug_width
from pytc.solver import bug_helper
from pytc.solver.bug_helper import aux_streamed, clock, on_device, release_device_copies, timed
from pytc.solver.bug_mp2 import bug_mp2_amplitudes, df_kernel
# Per aux panel the kernels hold about three (ov, rank) arrays per auxiliary
# index; the panel is capped so they stay within this budget.
PANEL_BUDGET_BYTES = 12e9
[docs]
def _aux_panels(B, block):
"""(p, q, naux) -> (npanel, block, p, q), zero-padding the last panel."""
naux = B.shape[2]
pad = (-naux) % block
B = jnp.moveaxis(B, 2, 0)
if pad:
B = jnp.concatenate((B, jnp.zeros((pad,) + B.shape[1:], B.dtype)))
return B.reshape(-1, block, *B.shape[1:])
[docs]
def _probe_blocks(call, V, width_block):
"""Apply ``call`` to zero-padded probe blocks of ``V``; host output."""
o, v, width = V.shape
V = np.asarray(V)
out = bug_helper.host_empty((o, v, width))
for s in range(0, width, width_block):
block = V[:, :, s:s + width_block]
n = block.shape[2]
if n < width_block:
block = np.concatenate(
(block, np.zeros((o, v, width_block - n), block.dtype)), axis=2)
out[:, :, s:s + n] = np.asarray(call(jnp.asarray(block)))[:, :, :n]
return out
# --------------------------------------------------------------------------
# JAX kernels. Each reduces over the auxiliary index with ``lax.scan`` over
# fixed-size panels, so the live workspace is (aux panel) x o x max(o, v) x
# (probe block) regardless of system size.
# --------------------------------------------------------------------------
@partial(jax.jit, static_argnames=("aux_block",))
def _exchange_block(B_ov, V, aux_block):
def body(acc, panel):
middle = jnp.einsum("Qkd,ldz->Qklz", panel, V)
return acc + jnp.einsum("Qklz,Qlc->kcz", middle, panel), None
return jax.lax.scan(body, jnp.zeros(V.shape, V.dtype), _aux_panels(B_ov, aux_block))[0]
[docs]
def exchange_action(B_ov, V, *, aux_block=32, probe_block=512):
"""``result[k,c,z] = sum_{Q,l,d} B[k,d,Q] V[l,d,z] B[l,c,Q]``."""
B = on_device(B_ov)
V = np.asarray(V) if not isinstance(V, jax.Array) else V
outs = [_exchange_block(B, jnp.asarray(V[:, :, s:s + probe_block]), aux_block)
for s in range(0, V.shape[2], probe_block)]
return np.asarray(jnp.concatenate(outs, axis=2)) if outs else np.zeros(V.shape)
@partial(jax.jit, static_argnames=("aux_block",))
def _exchange_energy_block(B_ov, V, aux_block):
def body(acc, panel):
middle = jnp.einsum("Qkd,ldz->Qklz", panel, V)
return acc + jnp.einsum("Qklz,Qlkz->z", middle, middle), None
return jax.lax.scan(body, jnp.zeros(V.shape[2], V.dtype), _aux_panels(B_ov, aux_block))[0]
[docs]
def exchange_energy(B_ov, V, *, aux_block=32, probe_block=512):
"""``result[z] = sum_{k,c,l,d} (kd|lc) V[k,c,z] V[l,d,z]``."""
B = on_device(B_ov)
outs = [_exchange_energy_block(B, jnp.asarray(V[:, :, s:s + probe_block]), aux_block)
for s in range(0, V.shape[2], probe_block)]
return np.asarray(jnp.concatenate(outs)) if outs else np.zeros(0)
@jax.jit
def _singles_only_block(t1, V, B_oo, B_ov, B_vv):
"""The eight singles-only doubles terms as binary contractions."""
o, v, naux = B_ov.shape
width = V.shape[2]
nov = o * v
probe = V.reshape(nov, width)
ov = B_ov.reshape(nov, naux)
# Shared Q/probe reductions for the bare ov and t1-dressed vv factors.
z_ov = ov.T @ probe
t1_bvv = jnp.matmul(t1[None], B_vv.transpose(2, 1, 0))
t1_bvv_flat = t1_bvv.reshape(naux, nov)
z_vv = t1_bvv_flat @ probe
result = ov @ z_vv
result += t1_bvv_flat.T @ z_ov
# Shared occupied pair/probe reduction sum_b t1[k,b] V[j,b,z].
jkz = jnp.tensordot(V, t1, axes=(1, 1)).transpose(0, 2, 1)
z_oo_kj = jnp.tensordot(B_oo, jkz, axes=([0, 1], [1, 0]))
z_oo_jk = jnp.tensordot(B_oo, jkz, axes=([0, 1], [0, 1]))
boo_z_vv = jnp.tensordot(B_oo, z_vv, axes=(2, 0))
term = jnp.tensordot(t1.T, boo_z_vv, axes=(1, 0))
result -= term.transpose(1, 0, 2).reshape(nov, width)
result -= t1_bvv_flat.T @ z_oo_kj
result -= ov @ z_oo_jk
t1_bov = jnp.tensordot(t1, B_ov, axes=(1, 1))
z_bov = jnp.tensordot(t1_bov, jkz, axes=([0, 1], [0, 1]))
result -= ov @ z_bov
boo_z_ov = jnp.tensordot(B_oo, z_ov, axes=(2, 0))
term = jnp.tensordot(boo_z_ov, t1, axes=(1, 0))
result -= term.transpose(0, 2, 1).reshape(nov, width)
t1_bov_z = jnp.tensordot(t1_bov, z_ov, axes=(2, 0))
term = jnp.tensordot(t1_bov_z, t1, axes=(1, 0))
result -= term.transpose(0, 2, 1).reshape(nov, width)
return result.reshape(o, v, width)
[docs]
def singles_only_action(t1, V, B_oo, B_ov, B_vv, *, probe_block=512):
t1_d = jnp.asarray(t1)
return aux_streamed(
lambda oo, ov, vv: _probe_blocks(
lambda block: _singles_only_block(t1_d, block, oo, ov, vv), V, probe_block),
B_oo, B_ov, B_vv)
@jax.jit
def _w1_panel(ov, oo, vv, crossed, t1, U2, weighted):
q, o, v = ov.shape
t1_crossed = jnp.einsum("ia,qja,jb->qib", t1, ov, t1)
value = (ov + jnp.einsum("kd,qcd->qkc", t1, vv)
- jnp.einsum("qjk,jc->qkc", oo, t1)
- t1_crossed - 0.5 * crossed)
overlap = ov.reshape(q, o * v) @ U2
value = value + (overlap @ weighted.T).reshape(q, o, v)
return value.reshape(q, o * v).T, jnp.moveaxis(crossed + t1_crossed, 0, 2)
[docs]
def w1_outer_factors(t1, U, S, B_oo, B_ov, B_vv, crossed_df, *, aux_block=32):
"""``Wvoov`` left DF factors (o*v, naux) and the crossed tau DF block.
``crossed_df`` is the crossed amplitude applied to ``B_ov``, (o, v, naux).
"""
o, v, naux = B_ov.shape
t1_d = jnp.asarray(t1)
U2 = jnp.asarray(U).reshape(o * v, -1)
weighted = U2 * jnp.asarray(S)[None]
result = bug_helper.host_empty((o * v, naux))
crossed_tau = bug_helper.host_empty((o, v, naux))
for q0 in range(0, naux, aux_block):
Q = slice(q0, min(q0 + aux_block, naux))
panel = [jnp.asarray(np.ascontiguousarray(np.moveaxis(B[:, :, Q], 2, 0)))
for B in (B_ov, B_oo, B_vv, crossed_df)]
value, tau = _w1_panel(*panel, t1_d, U2, weighted)
result[:, Q] = np.asarray(value)
crossed_tau[:, :, Q] = np.asarray(tau)
return result, crossed_tau
@partial(jax.jit, static_argnames=("block_q",))
def _vvvv_block(B_ov, B_vv, t1, U, S, V, block_q):
"""Complete dressed ``Wvvvv.tau`` group with DF and tau kept factorized."""
o, v, r = U.shape
rp = V.shape[2]
rt = r + 1
F = jnp.concatenate((U, t1[:, :, None]), axis=2)
weights = jnp.concatenate((S, jnp.ones(1, dtype=S.dtype)))
Fc = jnp.reshape(jnp.transpose(F, (1, 0, 2)), (v, o * rt))
Vm = jnp.reshape(jnp.transpose(V, (1, 0, 2)), (v * o, rp))
t1V = jnp.reshape(jnp.transpose(t1 @ V, (1, 0, 2)), (o * o, rp))
def body(acc, blocks):
B, O = blocks
RB = jnp.reshape(B @ Fc, (block_q, v * o, rt))
Z = jnp.reshape(O @ Fc, (block_q, o * o, rt))
HB = jnp.swapaxes(RB, 1, 2) @ Vm
HA = jnp.swapaxes(Z, 1, 2) @ t1V
left = RB @ (weights[None, :, None] * (HB - HA))
Y = Z @ (weights[None, :, None] * HB)
right = jnp.reshape(t1.T @ jnp.reshape(Y, (block_q, o, o * rp)),
(block_q, v * o, rp))
return acc + jnp.sum(left - right, axis=0), None
acc0 = jnp.zeros((v * o, rp), dtype=jnp.result_type(B_vv, U, V))
acc, _ = jax.lax.scan(body, acc0, (_aux_panels(B_vv, block_q), _aux_panels(B_ov, block_q)))
return jnp.transpose(jnp.reshape(acc, (v, o, rp)), (1, 0, 2))
@partial(jax.jit, static_argnames=("block_q",))
def _vvvv_projected_block(B_ov, B_vv, t1, U, S, Q, block_q):
"""``Q^T Wvvvv.tau Q`` with one projection per side."""
o, v, r = U.shape
rank_q = Q.shape[2]
rt = r + 1
factors = jnp.concatenate((U, t1[:, :, None]), axis=2)
weights = jnp.concatenate((S, jnp.ones(1, dtype=S.dtype)))
factor_matrix = jnp.reshape(jnp.transpose(factors, (1, 0, 2)), (v, o * rt))
q_matrix = jnp.reshape(jnp.transpose(Q, (1, 0, 2)), (v * o, rank_q))
t1_q = jnp.reshape(jnp.transpose(t1 @ Q, (1, 0, 2)), (o * o, rank_q))
def body(core, blocks):
vv_block, ov_block = blocks
virtual_factor = jnp.reshape(vv_block @ factor_matrix, (block_q, v * o, rt))
occupied_factor = jnp.reshape(ov_block @ factor_matrix, (block_q, o * o, rt))
virtual_core = jnp.swapaxes(virtual_factor, 1, 2) @ q_matrix
occupied_core = jnp.swapaxes(occupied_factor, 1, 2) @ t1_q
contribution = (
jnp.swapaxes(virtual_core, 1, 2)
@ (weights[None, :, None] * (virtual_core - occupied_core))
- jnp.swapaxes(occupied_core, 1, 2)
@ (weights[None, :, None] * virtual_core))
return core + jnp.sum(contribution, axis=0), None
zeros = jnp.zeros((rank_q, rank_q), dtype=jnp.result_type(B_ov, U, Q))
return jax.lax.scan(body, zeros, (_aux_panels(B_vv, block_q), _aux_panels(B_ov, block_q)))[0]
@partial(jax.jit, static_argnames=("block_q",))
def _w2_direct_block(t1, normal_probe, transpose_probe, B_oo, B_ov, B_vv, block_q):
"""Dressed direct half of the Wvovo ring and of its transpose."""
def body(carry, blocks):
normal, transpose = carry
oo_block, ov_block, vv_block = blocks
occupied = oo_block + ov_block @ t1.T
virtual = vv_block - t1.T @ ov_block
middle = jnp.einsum("kbz,Qab->Qkaz", normal_probe, virtual)
normal = normal + jnp.einsum("Qki,Qkaz->iaz", occupied, middle)
middle = jnp.einsum("iaz,Qac->Qicz", transpose_probe, virtual)
transpose = transpose + jnp.einsum("Qki,Qicz->kcz", occupied, middle)
return (normal, transpose), None
zeros = jnp.zeros_like(normal_probe)
panels = tuple(_aux_panels(B, block_q) for B in (B_oo, B_ov, B_vv))
return jax.lax.scan(body, (zeros, zeros), panels)[0]
@partial(jax.jit, static_argnames=("rank_block",))
def _crossed_amplitude_block(U, S, V, rank_block):
o, v, rank = U.shape
npad = (-rank) % rank_block
factors = jnp.reshape(jnp.pad(jnp.transpose(U, (2, 0, 1)),
((0, npad), (0, 0), (0, 0))), (-1, rank_block, o, v))
weights = jnp.reshape(jnp.pad(S, ((0, npad),)), (-1, rank_block))
V_transpose = jnp.transpose(V, (2, 1, 0))
def body(result, block):
panel, weight = block
values = (panel[:, None] @ V_transpose[None]) @ panel[:, None]
return result + jnp.einsum("x,xzia->iaz", weight, values), None
zeros = jnp.zeros((o, v, V.shape[2]), dtype=jnp.result_type(U, S, V))
return jax.lax.scan(body, zeros, (factors, weights))[0]
[docs]
def crossed_amplitude_action(U, S, V, *, rank_block=32, probe_block=256):
"""Apply ``T[(i,a),(k,c)] = T[i,k,c,a]`` without forming crossed T; host array.
Probe blocks bound the (rank_block, probes, o, max(o, v)) panel
independently of the width (the W1 factors call this with V = B_ov).
"""
U, S = jnp.asarray(U), jnp.asarray(S)
outs = [_crossed_amplitude_block(U, S, jnp.asarray(V[:, :, s:s + probe_block]), rank_block)
for s in range(0, V.shape[2], probe_block)]
return np.asarray(jnp.concatenate(outs, axis=2))
# --------------------------------------------------------------------------
# The pair operator X: the occupied ladder and the crossed ring
#
# X_occ[(ia),(jb)] = sum_kl W[i,j,k,l] tau[k,a,l,b]
# W[i,j,k,l] = sum_cd (kc|ld) t[i,c,j,d] + (ki|lj)^
# X_vir = (F + F^T) / 2, F[(ia),(jb)] = sum_kc Z[k,c,i,b] t[k,a,j,c]
# Z[k,c,i,b] = sum_ld (kd|lc) t[i,d,l,b] - 2 (ki|bc)^
#
# with the t1-dressed integrals (ki|lj)^ = sum_Q o[Q,k,i] o[Q,l,j] and
# (ki|bc)^ = sum_Q o[Q,k,i] w[Q,b,c], o = B_oo + B_ov t1^T, w = B_vv - t1^T B_ov.
# As in RR-CCSD's A and C terms (Hohenstein & Martinez 2021, Eqs. 17, 25),
# the dressed-integral parts ride along with the quadratic ones: they cost
# N_aux o^4 and N_aux o^2 v^2 per state, against N_aux o v^2 r per probe
# pass for the factorized kernel they replace.
# --------------------------------------------------------------------------
[docs]
class DFDirectBlocks:
"""(kc|ld) occupied row blocks rebuilt on the device from B_ov on demand.
``blocks[K]`` returns ``sum_P B[K,c,P] B[l,d,P]``; storing (kc|ld) cost
nov^2 doubles of host RAM.
"""
def __init__(self, B_ov):
self._B = on_device(B_ov)
def __getitem__(self, K):
return _direct_rows(self._B[K], self._B)
@jax.jit
def _direct_rows(B_rows, B):
return jnp.einsum("kcP,ldP->kcld", B_rows, B)
[docs]
def _blocks(n, size):
return [slice(start, min(start + size, n)) for start in range(0, n, size)]
@jax.jit
def _amplitude(U_rows, S, U):
return jnp.einsum("icx,x,jdx->icjd", U_rows, S, U)
@jax.jit
def _occupied_core(direct_rows, t_rows):
# O[k,l,i,j] for k in the direct block and i in the amplitude block.
return jnp.einsum("kcld,icjd->klij", direct_rows, t_rows)
@jax.jit
def _occupied_panel(W_rows, tau_rows):
# tau_rows is in amplitude layout [k,a,l,b]
return jnp.einsum("ijkl,kalb->ijab", W_rows, tau_rows)
@jax.jit
def _crossed_panel(direct_rows, t_block):
# Zcol[k,c,i,b] = sum_ld (kd|lc) t[i,d,l,b]
return jnp.einsum("kdlc,idlb->kcib", direct_rows, t_block)
@jax.jit
def _forward_panel(Z_rows, t_rows):
return jnp.einsum("kcib,kajc->iajb", Z_rows, t_rows)
@jax.jit
def _dressed_crossed(t1, B_ov, B_vv, occupied):
"""(ki|bc)^ as [k,c,i,b] for the occupied columns i of ``occupied``."""
virtual = B_vv - jnp.einsum("kb,kcQ->bcQ", t1, B_ov)
return jnp.einsum("kiQ,bcQ->kcib", occupied, virtual)
[docs]
class QuadraticOperator:
"""Exact quadratic operator X built once per state, applied as ``X @ M``.
The row blocks of Y = (X_occ + F)/2 are formed once on the device (X_occ
is pair-symmetric, so X = Y + Y^T). ``resident=True`` keeps the Y row
panels on the device (nov^2 doubles). ``resident=False`` parks only the
upper triangle of the symmetric X in host RAM (nov^2/2 doubles) and streams
it back per application. Row panel J stores X[J, J.start:]; the part of
Y left of the diagonal is transposed on the device and added into the
earlier panels.
"""
def __init__(self, t1, U, S, direct, B=None, *, block=8, resident=True, apply_rows=8192):
"""``B = (B_oo, B_ov, B_vv)`` adds the dressed-integral parts; without
it X holds the terms quadratic in T only."""
o, v, _ = U.shape
self._apply_rows = int(apply_rows)
self._resident = bool(resident)
self.timings = {"device_build": 0.0, "device_to_host": 0.0, "apply": 0.0}
t1_host = np.asarray(t1)
t1, U, S = jnp.asarray(t1), jnp.asarray(U), jnp.asarray(S)
blocks = _blocks(o, int(block))
O = jnp.zeros((o, o, o, o), dtype=U.dtype)
for K in blocks:
direct_rows = jnp.asarray(direct[K])
for I in blocks:
O = O.at[K, :, I, :].set(_occupied_core(direct_rows, _amplitude(U[I], S, U)))
W = jnp.transpose(O, (2, 3, 0, 1))
if B is not None:
B_oo, B_ov, B_vv = B
# o[k,i,Q], (o, o, naux): small, per state.
occupied = jnp.asarray(B_oo + np.einsum("kaQ,ia->kiQ", B_ov, t1_host, optimize=True))
W = W + jnp.einsum("kiQ,ljQ->ijkl", occupied, occupied)
U_tau = jnp.concatenate((U, t1[:, :, None]), axis=2)
S_tau = jnp.concatenate((S, jnp.ones((1,), dtype=S.dtype)))
self._panels = []
for I in blocks:
start = time.perf_counter()
R = sum(_occupied_panel(W[I][:, :, K, :], _amplitude(U_tau[K], S_tau, U_tau))
for K in blocks)
t_block = _amplitude(U[I], S, U)
Z = jnp.concatenate(
[_crossed_panel(jnp.asarray(direct[K]), t_block) for K in blocks], axis=0)
if B is not None:
occupied_I = occupied[:, I]
Z = Z - 2 * aux_streamed(
lambda ov, vv, occ: _dressed_crossed(t1, ov, vv, occ),
B_ov, B_vv, occupied_I, static=(True, True, False))
F = sum(_forward_panel(Z[K], _amplitude(U[K], S, U)) for K in blocks)
rows = (0.5 * (jnp.transpose(R, (0, 2, 1, 3)) + F)).reshape(-1, o * v)
r0, r1 = I.start * v, I.stop * v
if self._resident:
rows.block_until_ready()
else:
right = rows[:, r0:].at[:, :r1 - r0].add(rows[:, r0:r1].T)
left = rows[:, :r0].T
right.block_until_ready()
middle = time.perf_counter()
if self._resident:
self._panels.append((r0, r1, rows))
else:
self._panels.append((r0, r1, np.array(right, dtype=np.float64)))
left = np.asarray(left)
for j0, j1, panel in self._panels[:-1]:
panel[:, r0 - j0:r1 - j0] += left[j0:j1]
self.timings["device_build"] += middle - start
self.timings["device_to_host"] += time.perf_counter() - middle
def __matmul__(self, M):
start = time.perf_counter()
M_dev = jnp.asarray(M)
out = jnp.zeros(M_dev.shape, dtype=M_dev.dtype)
if self._resident:
for r0, r1, panel in self._panels:
out = out.at[r0:r1].add(panel @ M_dev)
out = out + panel.T @ M_dev[r0:r1]
else:
for j0, j1, stored in self._panels:
for s in range(0, stored.shape[0], self._apply_rows):
panel = jnp.asarray(stored[s:s + self._apply_rows])
g0, g1 = j0 + s, j0 + s + panel.shape[0]
out = out.at[g0:g1].add(panel @ M_dev[j0:])
out = out.at[j1:].add(panel[:, j1 - j0:].T @ M_dev[g0:g1])
out = np.asarray(out)
self.timings["apply"] += time.perf_counter() - start
return out
# --------------------------------------------------------------------------
# The CCSD numerator at one state (t1, U, S)
# --------------------------------------------------------------------------
[docs]
def _df_direct(B_ov, V):
"""Apply the direct DF pair kernel ``(ia|jb)`` without forming it."""
o, v, naux = B_ov.shape
B = B_ov.reshape(o * v, naux)
return (B @ (B.T @ V.reshape(o * v, -1))).reshape(o, v, -1)
[docs]
def _pair_amplitude_action(U, S, V):
"""Apply ``U diag(S) U^T`` to a probe block."""
o, v, rank = U.shape
U_flat = U.reshape(o * v, rank)
V_flat = V.reshape(o * v, V.shape[2])
return (U_flat @ (S[:, None] * (U_flat.T @ V_flat))).reshape(V.shape)
[docs]
def _one_body_actions(U, S, V, Lvv, Loo):
"""Apply the virtual and occupied one-body groups with GEMMs."""
o, v, rank = U.shape
width = V.shape[2]
U_flat = U.reshape(o * v, rank)
V_flat = V.reshape(o * v, width)
overlap = U_flat.T @ V_flat
virtual_u = jnp.matmul(Lvv, U).reshape(o * v, rank)
n5 = virtual_u @ (S[:, None] * overlap)
n5 += U_flat @ (S[:, None] * (virtual_u.T @ V_flat))
occupied_u = jnp.tensordot(Loo.T, U, axes=(1, 0)).reshape(o * v, rank)
n6 = -(occupied_u @ (S[:, None] * overlap))
n6 -= U_flat @ (S[:, None] * (occupied_u.T @ V_flat))
return n5.reshape(o, v, width), n6.reshape(o, v, width)
[docs]
def build_state(t1, U, S, B_oo, B_ov, B_vv, *, direct, quadratic_mode="device",
quadratic_block=8, compiled_aux_block=8, compiled_vvvv_block=16,
timings=None, prefix=""):
"""State-dependent intermediates and the exact quadratic operator.
``direct`` supplies (kc|ld) occupied row blocks (a :class:`DFDirectBlocks`
or an (o, v, o, v) array).
"""
o, v = t1.shape
naux = B_ov.shape[2]
with timed(timings, prefix + "cache_tau_traces"):
factors = np.concatenate((U, t1[:, :, None]), axis=2)
weights = np.concatenate((S, np.ones(1)))
overlap = B_ov.reshape(o * v, naux).T @ factors.reshape(o * v, -1)
direct_vv = np.zeros((v, v))
direct_oo = np.zeros((o, o))
for q0 in range(0, naux, 16):
q1 = min(q0 + 16, naux)
ov = B_ov[:, :, q0:q1].transpose(2, 0, 1)
dressed = ((overlap[q0:q1] * weights[None]) @ factors.reshape(o * v, -1).T
).reshape(q1 - q0, o, v)
direct_vv += np.einsum("Qkc,Qka->ac", ov, dressed, optimize=True)
direct_oo += np.einsum("Qkc,Qic->ki", ov, dressed, optimize=True)
# Both exchange traces contract the same DF exchange action, Q r o^2 v.
exchange_factors = exchange_action(B_ov, factors)
weighted_factors = factors * weights[None, None]
exchange_vv = (weighted_factors.transpose(1, 0, 2).reshape(v, -1)
[docs]
@ exchange_factors.transpose(1, 0, 2).reshape(v, -1).T)
exchange_oo = (exchange_factors.reshape(o, -1)
@ weighted_factors.reshape(o, -1).T)
t1_overlap = overlap[:, -1]
with timed(timings, prefix + "cache_lvv_loo"):
Lvv = -2 * direct_vv + exchange_vv
Lvv += 2 * np.einsum("Q,acQ->ac", t1_overlap, B_vv, optimize=True)
Loo = 2 * direct_oo - exchange_oo
Loo += 2 * np.einsum("Q,kiQ->ki", t1_overlap, B_oo, optimize=True)
for q in range(naux):
Lvv -= B_vv[:, :, q] @ t1.T @ B_ov[:, :, q]
Loo -= (B_ov[:, :, q] @ t1.T) @ B_oo[:, :, q]
with timed(timings, prefix + "cache_w1_left"):
w1_left, crossed_tau_df = w1_outer_factors(
t1, U, S, B_oo, B_ov, B_vv, crossed_amplitude_action(U, S, B_ov))
with timed(timings, prefix + "cache_exact_quadratic"):
quadratic = QuadraticOperator(t1, U, S, direct, (B_oo, B_ov, B_vv), block=quadratic_block,
resident=quadratic_mode == "device")
if timings is not None:
for name, value in quadratic.timings.items():
timings[prefix + "quadratic_" + name] = (
timings.get(prefix + "quadratic_" + name, 0.0) + value)
per_aux = 3 * 8 * o * v * max(S.size + 1, 1)
fit = max(1, int(PANEL_BUDGET_BYTES // per_aux))
return dict(Lvv=Lvv, Loo=Loo, exchange_u=exchange_factors[:, :, :S.size],
w1_left=w1_left, crossed_tau_df=crossed_tau_df, quadratic=quadratic,
aux_block=min(compiled_aux_block, fit), vvvv_block=min(compiled_vvvv_block, fit))
def _w1_actions(U, S, B_ov, normal_probe, transpose_probe, cache):
"""Apply Wvoov and its transpose to two probe blocks in one DF pass."""
o, v, naux = B_ov.shape
rank = S.size
U, S, B_ov = jnp.asarray(U), jnp.asarray(S), on_device(B_ov)
left = jnp.asarray(cache["w1_left"])
B_flat = B_ov.reshape(o * v, naux)
normal_flat = normal_probe.reshape(o * v, -1)
transpose_flat = transpose_probe.reshape(o * v, -1)
normal = left @ (B_flat.T @ normal_flat)
transpose = B_flat @ (left.T @ transpose_flat)
U_flat = U.reshape(o * v, rank)
transpose_core = S[:, None] * (U_flat.T @ transpose_flat)
right = jnp.asarray(cache["exchange_u"]).reshape(o * v, rank)
transpose -= 0.5 * right @ transpose_core
normal -= 0.5 * U_flat @ (S[:, None] * (right.T @ normal_flat))
return normal.reshape(o, v, -1), transpose.reshape(o, v, -1)
[docs]
def _w2_actions(t1, U, S, B_oo, B_ov, B_vv, normal_probe, transpose_probe,
crossed_transpose_probe, aux_block, timings, prefix):
"""Apply Wvovo and its transpose without retaining Wvovo."""
with timed(timings, prefix + "ring_w2_direct"):
normal, transpose = (np.array(x) for x in aux_streamed(
lambda oo, ov, vv: _w2_direct_block(
t1, normal_probe, transpose_probe, oo, ov, vv, block_q=aux_block),
B_oo, B_ov, B_vv))
with timed(timings, prefix + "ring_w2_exchange"):
width = normal_probe.shape[2]
exchange_both = exchange_action(
B_ov, np.concatenate((normal_probe, crossed_transpose_probe), axis=2))
with timed(timings, prefix + "ring_w2_crossed"):
normal -= 0.5 * crossed_amplitude_action(U, S, exchange_both[:, :, :width])
transpose -= 0.5 * exchange_both[:, :, width:]
return normal, transpose
[docs]
def doubles_action(t1, U, S, V, B_oo, B_ov, B_vv, cache, *, timings=None, prefix=""):
"""``N(t1, T) V`` for a probe block ``V`` (o, v, w); returns (o*v, w)."""
o, v, _ = U.shape
width = V.shape[2]
aux_block = cache["aux_block"]
with timed(timings, prefix + "one_singles_only"):
n1 = singles_only_action(t1, V, B_oo, B_ov, B_vv)
with timed(timings, prefix + "two_direct"):
n2 = _df_direct(B_ov, V)
with timed(timings, prefix + "four_vvvv"):
n4 = np.asarray(aux_streamed(
lambda ov, vv: _vvvv_block(ov, vv, t1, U, S, V, block_q=cache["vvvv_block"]),
B_ov, B_vv))
with timed(timings, prefix + "five_six_one_body"):
n5, n6 = (np.asarray(x) for x in _one_body_actions(
*(jnp.asarray(x) for x in (U, S, V, cache["Lvv"], cache["Loo"]))))
with timed(timings, prefix + "seven_ring"):
U_x, S_x, V_x = (jnp.asarray(x) for x in (U, S, V))
t_action = _pair_amplitude_action(U_x, S_x, V_x)
crossed_action = crossed_amplitude_action(U, S, V)
combined = jnp.concatenate((t_action, jnp.asarray(crossed_action)), axis=2)
w1_normal, w1_transpose = _w1_actions(U, S, B_ov, combined, V_x, cache)
w2_t, w2_transpose = _w2_actions(
t1, U, S, B_oo, B_ov, B_vv, np.asarray(t_action), V, crossed_action,
aux_block, timings, prefix)
n7a = np.asarray(
2 * w1_normal[:, :, :width] - jnp.asarray(w2_t)
+ _pair_amplitude_action(U_x, S_x, 2 * w1_transpose - jnp.asarray(w2_transpose)))
n7b = -np.asarray(w1_normal[:, :, width:]) - crossed_amplitude_action(
U, S, np.asarray(w1_transpose))
with timed(timings, prefix + "exact_quadratic_action"):
quadratic = cache["quadratic"] @ V.reshape(o * v, -1)
return (n1 + n2 + n4 + n5 + n6 + n7a + n7b).reshape(o * v, width) + quadratic
[docs]
def projected_doubles(t1, U, S, Q, B_oo, B_ov, B_vv, cache, *, timings=None, prefix=""):
"""``Q^T N(t1, T) Q`` for new directions ``Q`` with ``U^T Q = 0``.
The particle ladder is contracted into the small core before any
pair-space output is formed; every ring term containing ``T Q`` vanishes.
"""
o, v, _ = U.shape
k = Q.shape[2]
Q_flat = Q.reshape(o * v, k)
with timed(timings, prefix + "one_singles_only"):
core = Q_flat.T @ singles_only_action(t1, Q, B_oo, B_ov, B_vv).reshape(o * v, k)
with timed(timings, prefix + "two_direct"):
Q_df = B_ov.reshape(o * v, -1).T @ Q_flat
core += Q_df.T @ Q_df
with timed(timings, prefix + "exact_quadratic_action"):
core += Q_flat.T @ (cache["quadratic"] @ Q_flat)
with timed(timings, prefix + "four_vvvv"):
core += np.asarray(aux_streamed(
lambda ov, vv: _vvvv_projected_block(ov, vv, t1, U, S, Q, block_q=cache["vvvv_block"]),
B_ov, B_vv))
with timed(timings, prefix + "five_six_one_body"):
n5, n6 = _one_body_actions(U, S, Q, cache["Lvv"], cache["Loo"])
core += Q_flat.T @ (n5 + n6).reshape(o * v, k)
with timed(timings, prefix + "seven_ring"):
# Only the crossed-amplitude W1 topology survives U^T Q = 0.
crossed_Q = crossed_amplitude_action(U, S, Q).reshape(o * v, k)
w1 = (Q_flat.T @ cache["w1_left"]) @ (B_ov.reshape(o * v, -1).T @ crossed_Q)
core -= w1 + w1.T
return core
[docs]
def singles_numerator(t1, U, S, B_oo, B_ov, B_vv, cache, *, timings=None, prefix=""):
"""The singles numerator (``t1_new = numerator / eia``)."""
o, v = t1.shape
naux = B_ov.shape[2]
with timed(timings, prefix + "singles_f_intermediates"):
t1_overlap = B_ov.reshape(o * v, naux).T @ t1.reshape(o * v)
Fov = 2 * np.einsum("iaQ,Q->ia", B_ov, t1_overlap, optimize=True)
Foo = cache["Loo"].copy()
Foo -= 2 * np.einsum("Q,kiQ->ki", t1_overlap, B_oo, optimize=True)
Fvv = cache["Lvv"].copy()
Fvv -= 2 * np.einsum("Q,acQ->ac", t1_overlap, B_vv, optimize=True)
for q in range(naux):
ov = B_ov[:, :, q]
Fov -= (ov @ t1.T) @ ov
Foo += (ov @ t1.T) @ B_oo[:, :, q]
Fvv += B_vv[:, :, q] @ t1.T @ ov
with timed(timings, prefix + "singles_amplitude_fock"):
singles = t1 @ Fvv.T - Foo.T @ t1
U_flat = U.reshape(o * v, S.size)
singles += 2 * (U_flat @ (S * (Fov.reshape(o * v) @ U_flat))).reshape(o, v)
for index in range(S.size):
factor = U[:, :, index]
singles -= S[index] * (factor @ Fov.T) @ factor
singles += (t1 @ Fov.T) @ t1
with timed(timings, prefix + "singles_bare_df"):
singles += 2 * np.einsum("iaQ,Q->ia", B_ov, t1_overlap, optimize=True)
for q in range(naux):
singles -= B_oo[:, :, q].T @ t1 @ B_vv[:, :, q].T
with timed(timings, prefix + "singles_tau_df"):
t1_d, U_d, S_d = (jnp.asarray(x) for x in (t1, U, S))
singles += np.asarray(aux_streamed(
lambda oo, ov, vv, cdf: _singles_tau_df(t1_d, U_d, S_d, oo, ov, vv, cdf),
B_oo, B_ov, B_vv, cache["crossed_tau_df"], static=(True, True, True, False)))
return singles
[docs]
def _singles_tau_df(t1, U, S, B_oo, B_ov, B_vv, crossed_df):
"""The four tau-dependent DF singles groups in explicit N5 order."""
o, v, naux = B_ov.shape
factors = jnp.concatenate((U, t1[:, :, None]), axis=2)
weights = jnp.concatenate((S, jnp.ones(1, dtype=S.dtype)))
overlap = B_ov.reshape(o * v, naux).T @ factors.reshape(o * v, -1)
virtual_direct = jnp.zeros((o, v), dtype=np.result_type(U.dtype, B_ov.dtype))
occupied_direct = jnp.zeros_like(virtual_direct)
for q0 in range(0, naux, 32):
q1 = min(q0 + 32, naux)
oo = B_oo[:, :, q0:q1].transpose(2, 0, 1)
vv = B_vv[:, :, q0:q1].transpose(2, 0, 1)
dressed = ((overlap[q0:q1] * weights[None]) @ factors.reshape(o * v, -1).T
).reshape(q1 - q0, o, v)
virtual_direct += jnp.einsum("Qac,Qic->ia", vv, dressed)
occupied_direct += jnp.einsum("Qki,Qka->ia", oo, dressed)
virtual_exchange = jnp.einsum("icQ,acQ->ia", crossed_df, B_vv)
occupied_exchange = jnp.einsum("kaQ,kiQ->ia", crossed_df, B_oo)
return (2 * virtual_direct - virtual_exchange
- 2 * occupied_direct + occupied_exchange)
[docs]
def energy(t1, U, S, B_ov):
"""Matrix-free CCSD correlation energy from (t1, U, S) (canonical HF)."""
o, v, r = U.shape
B = B_ov.reshape(o * v, -1)
direct_U = B.T @ U.reshape(o * v, r)
direct_t1 = B.T @ t1.reshape(o * v)
exchange_U = exchange_energy(B_ov, U)
exchange_t1 = 0.0
Oq = np.ascontiguousarray(B_ov.transpose(2, 0, 1))
for q0 in range(0, Oq.shape[0], 16):
M = t1 @ Oq[q0:q0 + 16].swapaxes(1, 2)
exchange_t1 += np.sum(M * M.swapaxes(1, 2))
return (S @ (2 * (direct_U * direct_U).sum(axis=0) - exchange_U)
+ 2 * np.vdot(direct_t1, direct_t1).real - exchange_t1)
# --------------------------------------------------------------------------
# MP2 start, residual and the BUG outer loop
# --------------------------------------------------------------------------
[docs]
def mp2_start(B_ov, eia, tau=1e-4, maxiter=5, truncation="relative"):
"""Low-rank warm start: a few BUG-MP2 iterations on the direct-only amplitude."""
res = bug_mp2_amplitudes(df_kernel(B_ov, direct_only=True), eia, tau=tau,
maxiter=maxiter, truncation=truncation)
return res.U, res.S
[docs]
class ResidualInfo(NamedTuple):
"""Norm decomposition for the doubles residual action."""
norm: float
parallel_norm: float
external_norm: float
relative_norm: float
scale: float
[docs]
def ccsd_residual_action(Ur, S, nU, eia_pair):
"""``R2(T) U = N2 U - D U S - U S (U^T D U)`` and its norms (device arrays).
With ``T = U diag(S) U^T`` the fixed-point equation is ``D T + T D =
N2(t1, T)``. Only the external part adds basis directions, but the
parallel part is needed for an honest convergence test.
"""
S = jnp.asarray(S)
dU = eia_pair[:, None] * Ur
dUS = dU * S[None, :]
core = S[:, None] * (Ur.T @ dU)
residual = nU - dUS - Ur @ core
parallel = Ur.T @ residual
norm2 = float(jnp.vdot(residual, residual).real)
parallel2 = float(jnp.vdot(parallel, parallel).real)
norm = float(np.sqrt(norm2))
scale = max(float(jnp.linalg.norm(nU)) + float(jnp.linalg.norm(dUS))
+ float(jnp.linalg.norm(core)), np.finfo(float).tiny)
return residual, ResidualInfo(norm, float(np.sqrt(parallel2)),
float(np.sqrt(max(norm2 - parallel2, 0.0))),
norm / scale, scale)
[docs]
def low_rank_ccsd(
mf,
tau=1e-4,
maxiter=100,
conv=1e-10,
rmin=1,
damp=0.7,
init="mf",
aug_k=None,
aug_sel="residual",
aug_precond=None,
aug_warmup=False,
amplitude_tol=None,
energy_plateau_tolerance=None,
quadratic_mode="device",
quadratic_block=8,
frozen=0,
truncation="relative",
callback=None,
dense_core="device",
):
"""Solve RCCSD with an adaptive symmetric low-rank doubles amplitude.
``tau`` truncates the Galerkin core by eigenvalue magnitude, relative to
the largest (``truncation="relative"``) or absolute (``"absolute"``); it
is not a CCSD residual tolerance. ``init="mf"`` is the matrix-free MP2
warm start; an explicit ``(U, S)`` pair, or ``(U, S, t1)`` to restart a run,
is also accepted. ``callback`` receives a dict per iteration whose
``"state"`` is the current ``(U, S, t1)``, so a caller can checkpoint and
later restart through ``init``. ``frozen`` drops the lowest canonical
orbitals.
Each iteration applies N(T) to the basis U, adds residual directions Q
and remeasures the new block by the projected kernels: N is a symmetric
pair-space matrix, so U^T N Q is the transpose of Q^T N U from the basis
pass and only Q^T N Q is new.
``aug_k`` caps the new directions per iteration (a count, or a fraction
of the rank if < 1); ``aug_sel`` picks them by projected residual norm
(``"residual"``) or as the leading singular vectors of the external
residual (``"svd"``). ``aug_precond="jacobi"`` divides residual column x
by (D + e_x), e_x = u_x^T D u_x, so directions are ranked by approximate
amplitude update. ``aug_warmup=True`` adds every direction (k = r) until
the rank grows by at most 2% in one iteration.
The run stops when the amplitude step is below ``conv`` or the energy
has changed by less than ``energy_plateau_tolerance`` (default
``tau^2 |E|``) over three iterations; ``amplitude_tol`` additionally requires
||dT|| + ||dt1|| below ``amplitude_tol`` (||T|| + ||t1||).
``quadratic_mode`` keeps the exact quadratic operator on the device
(``"device"``, nov^2 doubles) or its upper triangle in host RAM
(``"host"``). ``dense_core`` runs the truncation eigh on the device
(``"device"``; out of memory stops the run) or on the host CPU
(``"host"``). JAX must run in float64 (``JAX_ENABLE_X64=1``).
Returns a :class:`~pytc.solver.bug_core.LowRankResult` with ``t1`` set;
``diagnostics`` holds the per-iteration histories, stage and kernel times.
"""
require_float64()
if truncation not in ("relative", "absolute"):
raise ValueError("truncation must be 'relative' or 'absolute'")
if maxiter < 1:
raise ValueError("maxiter must be positive")
if aug_sel not in ("residual", "amplitude", "svd"):
raise ValueError("aug_sel must be 'residual', 'amplitude' or 'svd'")
if aug_precond not in (None, "jacobi"):
raise ValueError("aug_precond must be None or 'jacobi'")
if quadratic_mode not in ("device", "host"):
raise ValueError("quadratic_mode must be 'device' or 'host'")
if dense_core not in ("device", "host"):
raise ValueError("dense_core must be 'device' or 'host'")
if not 0 < damp <= 1:
raise ValueError("damp must be in (0, 1]")
ncore = int(frozen)
nocc = mf.mol.nelectron // 2 - ncore
if not 0 <= ncore < mf.mol.nelectron // 2:
raise ValueError("frozen must count fewer than the occupied orbitals")
mo_coeff = np.asarray(mf.mo_coeff)[:, ncore:]
mo_e = np.asarray(mf.mo_energy)[ncore:]
nvir = mo_coeff.shape[1] - nocc
eia = mo_e[:nocc, None] - mo_e[None, nocc:]
setup_start = clock()
B_oo, B_ov, B_vv = extract_df_factors(mf, nocc, mo_coeff=mo_coeff)
if B_ov.nbytes > bug_helper.RESIDENT_LIMIT_BYTES:
# B_oo and B_vv stream by aux chunks; the B_ov consumers (direct blocks,
# exchange, W1) need it device-resident. Fail here rather than let JAX
# move it whole at the first dispatch.
raise MemoryError(
f"B_ov is {B_ov.nbytes / 1e9:.1f} GB, above RESIDENT_LIMIT_BYTES="
f"{bug_helper.RESIDENT_LIMIT_BYTES / 1e9:.0f} GB; BUG-CCSD keeps B_ov on the device")
df_extract_seconds = clock() - setup_start
try:
direct = DFDirectBlocks(B_ov)
initial_guess_start = clock()
t1 = np.zeros((nocc, nvir))
if isinstance(init, str) and init == "mf":
U, S = mp2_start(B_ov, eia, tau=tau, truncation=truncation)
elif isinstance(init, tuple) and len(init) in (2, 3):
U, S = map(np.asarray, init[:2])
if len(init) == 3:
t1 = np.asarray(init[2], dtype=float).reshape(nocc, nvir)
else:
raise ValueError("init must be 'mf', an (U, S) pair or an (U, S, t1) triple")
initial_guess_seconds = clock() - initial_guess_start
setup_seconds = clock() - setup_start
eia_x = jnp.asarray(eia.reshape(-1))
hist = {key: [] for key in (
"rank_hist", "e_hist", "residual_norm_hist", "residual_external_hist",
"residual_relative_hist", "singles_residual_hist", "combined_residual_hist",
"augmentation_rank_hist", "iteration_time_hist", "relative_amplitude_change_hist",
"stage_time_hist")}
rank_hist, energy_hist = hist["rank_hist"], hist["e_hist"]
kernel_times = {}
stop_reason = "maxiter"
converged = False
e_corr = 0.0
it = -1
for it in range(maxiter):
iteration_start = clock()
# Drop the previous state's cache and nov x rank device arrays first:
# the parked quadratic operator is nov^2/2 doubles and the outer-loop
# arrays add to the peak device memory.
cache = nU = residual = rdir = U_aug = Qnew = Ur = None
stages = {}
warming = aug_warmup and not (
len(rank_hist) >= 2 and rank_hist[-1] - rank_hist[-2] <= 0.02 * rank_hist[-1])
aug_warmup = warming
requested = None
if aug_k is not None and not warming:
requested = requested_aug_width(S.size, nocc, nvir, aug_k=aug_k)
start = clock()
cache = build_state(t1, U, S, B_oo, B_ov, B_vv, direct=direct,
quadratic_mode=quadratic_mode, quadratic_block=quadratic_block,
timings=kernel_times, prefix="state_")
stages["cache"] = clock() - start
start = clock()
nU = jnp.asarray(doubles_action(t1, U, S, U, B_oo, B_ov, B_vv, cache,
timings=kernel_times, prefix="state_"))
stages["doubles"] = clock() - start
start = clock()
t1_num = singles_numerator(t1, U, S, B_oo, B_ov, B_vv, cache,
timings=kernel_times, prefix="state_")
stages["singles"] = clock() - start
start = clock()
Ur = jnp.asarray(U.reshape(nocc * nvir, S.size))
residual, residual_info = ccsd_residual_action(Ur, S, nU, eia_x)
singles_norm = float(np.linalg.norm(t1_num - eia * t1))
singles_scale = max(float(np.linalg.norm(t1_num)) + float(np.linalg.norm(eia * t1)),
np.finfo(float).tiny)
rdir = residual
if aug_precond == "jacobi":
# column x approximately solves (D + e_x) du_x = r_x
shift = jnp.einsum("px,p,px->x", Ur, eia_x, Ur)
rdir = residual / (eia_x[:, None] + shift[None, :])
Qa = orth_directions(project_directions(
Ur, rdir, kabs=requested, how="top" if aug_sel == "amplitude" else aug_sel))
U_aug = jnp.concatenate([Ur, Qa], axis=1)
r0 = Ur.shape[1]
Qnew = U_aug[:, r0:]
stages["residual_augment"] = clock() - start
start = clock()
top_left = Ur.T @ nU
if Qnew.shape[1] == 0:
G = top_left
else:
bottom_left = Qnew.T @ nU
bottom_right = jnp.asarray(projected_doubles(
t1, U, S, np.asarray(Qnew).reshape(nocc, nvir, -1), B_oo, B_ov, B_vv,
cache, timings=kernel_times, prefix="new_projected_"))
G = jnp.block([[top_left, bottom_left.T], [bottom_left, bottom_right]])
stages["projected_remeasurement"] = clock() - start
combined_relative = float(np.sqrt(residual_info.relative_norm**2
+ (singles_norm / singles_scale) ** 2))
start = clock()
Y = sylvester(U_aug.T @ (eia_x[:, None] * U_aug), G)
P = U_aug.T @ Ur
M = (1 - damp) * ((P * jnp.asarray(S)[None, :]) @ P.T) + damp * Y
Q_r, S_new, trunc = truncate_sym(0.5 * (M + M.T), tau, rmin=rmin, rule=truncation,
dense_core=dense_core)
S_new = np.asarray(S_new)
rank = trunc.kept
U_new = np.asarray(U_aug @ Q_r).reshape(nocc, nvir, rank)
t1_new = t1_num / eia
stages["projected_update"] = clock() - start
U_flat = jnp.asarray(U_new.reshape(-1, rank))
amplitude_scale = float(np.sqrt(S_new @ S_new)) + float(np.linalg.norm(t1_new))
step, valid = amplitude_step(S_new, S, U_flat.T @ Ur, U_flat, Ur, conv=conv,
amplitude_tol=amplitude_tol, scale=amplitude_scale)
amplitude_change = step + float(np.linalg.norm(t1_new - t1))
relative_amplitude_change = amplitude_change / max(amplitude_scale, np.finfo(float).tiny)
t1, U, S = t1_new, U_new, S_new
start = clock()
e_corr = energy(t1, U, S, B_ov)
stages["energy"] = clock() - start
for key, value in (
("rank_hist", rank), ("e_hist", float(e_corr)),
("residual_norm_hist", residual_info.norm),
("residual_external_hist", residual_info.external_norm),
("residual_relative_hist", residual_info.relative_norm),
("singles_residual_hist", singles_norm),
("combined_residual_hist", combined_relative),
("augmentation_rank_hist", int(Qnew.shape[1])),
("iteration_time_hist", clock() - iteration_start),
("relative_amplitude_change_hist", float(relative_amplitude_change)),
("stage_time_hist", stages)):
hist[key].append(value)
if callback is not None:
callback({
"iteration": it,
"rank": rank,
"energy": float(e_corr),
"amplitude_change": float(amplitude_change),
"relative_amplitude_change": float(relative_amplitude_change),
"relative_residual": residual_info.relative_norm,
"combined_relative_residual": combined_relative,
"augmentation_rank": int(Qnew.shape[1]),
"iteration_time": hist["iteration_time_hist"][-1],
"stage_times": dict(stages),
"kernel_times": dict(kernel_times),
"state": (U, S, t1),
})
reason = check_stop(
amplitude_change, amplitude_scale, valid, energy_hist,
(plateau_tol(truncation, tau, e_corr)
if energy_plateau_tolerance is None else energy_plateau_tolerance),
conv=conv, amplitude_tol=amplitude_tol)
if reason:
converged, stop_reason = True, reason
break
finally:
# the device/host caches can hold tens of GB: free them on any exit
release_device_copies()
diagnostics = dict(hist, kernel_times=dict(kernel_times),
df_extract_seconds=float(df_extract_seconds),
initial_guess_seconds=float(initial_guess_seconds),
setup_seconds=float(setup_seconds), full_pair_dimension=int(nocc * nvir),
dense_core=dense_core)
return LowRankResult(energy=float(e_corr), U=U, S=S, iterations=it + 1, converged=converged,
stop_reason=stop_reason, rank_hist=rank_hist, e_hist=energy_hist, t1=t1,
diagnostics=diagnostics)