"""BUG-MP2: iterative low-rank DF-MP2.
The amplitude is carried as ``T = U diag(S) U^T`` in the pair space, so ``t2``
is never formed, and the energy denominator is closed exactly by one ``r x r``
Sylvester solve per iteration (no Laplace grid). The iteration applies only
the direct kernel ``(ia|jb)`` (canonical MP2 has ``t = (ia|jb)/Delta``); the
exchange enters once, in the energy ``sum t (2(ia|jb) - (ib|ja))``.
"""
from __future__ import annotations
import time
from functools import partial as _partial
import jax
import jax.numpy as jnp
import numpy as np
from pytc.solver.bug_core import (LowRankResult, amplitude_step, check_stop, extract_df_factors,
plateau_tol, rank_cut, require_float64, sylvester, truncate_sym)
from pytc.solver import bug_core, bug_helper
@jax.jit
def _df_direct(B_ov, V):
"""Apply ``(ia|jb)`` to a block using the two defining DF GEMMs.
``2 nov naux k`` -> ``N^4``.
"""
o, v, naux = B_ov.shape
B = B_ov.reshape(o * v, naux)
X = V.reshape(o * v, -1)
return (B @ (B.T @ X)).reshape(o, v, -1)
@jax.jit
def _df_exchange(B_ov, V):
"""Apply ``(ib|ja)``, one auxiliary slice at a time.
``naux o^2 v k`` -- the only ``N^5`` step in the MP2 iteration. See
Written as a ``lax.scan``
so the whole sweep is a single compiled kernel rather than a host loop.
"""
o, v, _ = B_ov.shape
k = V.shape[2]
Vt = jnp.transpose(V, (1, 2, 0)).reshape(v * k, o) # (v k, o)
def one(acc, Bq): # Bq: (o, v)
Y = (Vt @ Bq).reshape(v, k * v) # (v, k v)
return acc + (Bq @ Y).reshape(o, k, v).transpose(0, 2, 1), None
out, _ = jax.lax.scan(one, jnp.zeros(V.shape, dtype=V.dtype),
jnp.moveaxis(B_ov, 2, 0))
return out
[docs]
def df_kernel(B_ov, direct_only=False):
"""Pair-kernel callable on the DF factor: ``(ia|jb)`` if ``direct_only``,
else ``2(ia|jb) - (ib|ja)``. The factor goes to the device once."""
require_float64()
B = jnp.asarray(B_ov)
if direct_only:
return lambda V: _df_direct(B, jnp.asarray(V))
return lambda V: 2.0 * _df_direct(B, jnp.asarray(V)) - _df_exchange(B, jnp.asarray(V))
[docs]
def bug_mp2_amplitudes(matvec, eia, tau=1e-4, maxiter=100, conv=1e-10, r0=8, seed=0,
max_rank=None, aug_k=None, aug_sel='residual', truncation='relative',
energy_plateau_tolerance=None, amplitude_tol=None):
"""Matrix-free low-rank MP2 amplitudes as a :class:`LowRankResult`
(``energy=None``; ``U`` is ``(o, v, r)``, on the device).
``matvec`` applies the DIRECT kernel to an ``(o, v, k)`` block. No ``t2`` is
ever built; the denominator is closed exactly by the ``r x r`` Sylvester
solve, so no Laplace grid is needed. ``tau`` and ``truncation`` cut the
Galerkin core as in :func:`pytc.solver.bug_core.truncate_sym`.
Stops by :func:`~pytc.solver.bug_core.check_stop`, as every BUG solver does,
with the Galerkin energy ``tr(Y G)`` as the plateau energy.
"""
require_float64()
o, v = eia.shape
N = o * v
d = jnp.asarray(eia).reshape(-1)
r0 = min(int(r0), N)
U = jnp.asarray(np.linalg.qr(np.random.default_rng(seed).standard_normal((N, r0)))[0])
S = jnp.zeros(r0)
sel = ({} if aug_k is None else
dict(frac=aug_k, kmin=2 * (o + v)) if aug_k < 1 else dict(kabs=aug_k))
how = 'residual' if aug_sel == 'residual' else 'top'
e_hist, ranks, aug_ranks, t_iters = [], [], [], []
tm = dict(t_matvec=0.0, t_orth=0.0, t_core=0.0, t_update=0.0)
stop, it = 'maxiter', -1
t_loop0 = time.perf_counter()
for it in range(maxiter):
t_it0 = _t = time.perf_counter()
XU = matvec(U.reshape(o, v, -1)).reshape(N, -1)
tm['t_matvec'] += time.perf_counter() - _t
_t = time.perf_counter()
R = XU - d[:, None] * U * S[None, :] - U @ (S[:, None] * (U.T @ (d[:, None] * U)))
Qa = bug_core.orth_directions(bug_core.project_directions(U, R, how=how, **sel))
U_aug = jnp.concatenate([U, Qa], axis=1)
tm['t_orth'] += time.perf_counter() - _t
aug_ranks.append(int(U_aug.shape[1]))
_t = time.perf_counter()
JUa = matvec(U_aug.reshape(o, v, -1)).reshape(N, -1)
tm['t_matvec'] += time.perf_counter() - _t
_t = time.perf_counter()
G = U_aug.T @ JUa
Y = sylvester(U_aug.T @ (d[:, None] * U_aug), G)
e_hist.append(float(jnp.sum(Y * G))) # tr(Y G): r_aug^2, no basis-height work
W, S_new, _ = truncate_sym(Y, tau, max_rank=max_rank, rule=truncation,
energy_metric=G)
tm['t_core'] += time.perf_counter() - _t
_t = time.perf_counter()
U_new = U_aug @ W
step, valid = amplitude_step(S_new, S, U_new.T @ U, U_new, U, conv=conv,
amplitude_tol=amplitude_tol,
scale=float(np.sqrt(S_new @ S_new)))
tm['t_update'] += time.perf_counter() - _t
U, S = U_new, S_new
ranks.append(int(S.shape[0]))
t_iters.append(time.perf_counter() - t_it0)
reason = check_stop(step, float(np.sqrt(S @ S)), valid, e_hist,
(plateau_tol(truncation, tau, e_hist[-1])
if energy_plateau_tolerance is None else energy_plateau_tolerance),
conv=conv, amplitude_tol=amplitude_tol)
if reason:
stop = reason
break
return LowRankResult(energy=None, U=U.reshape(o, v, -1), S=S, iterations=it + 1,
converged=stop != 'maxiter', stop_reason=stop, rank_hist=ranks,
e_hist=e_hist,
diagnostics=dict(aug_rank_history=aug_ranks, t_loop=time.perf_counter() - t_loop0,
t_iter_history=t_iters, **tm))
[docs]
def bug_mp2_energy(U, S, pair_matvec):
"""``E = sum_z S_z U_z^T (2J - K) U_z`` (PySCF RMP2 convention)."""
o, v, r = U.shape
KU = pair_matvec(U).reshape(o * v, -1)
return float(jnp.sum(jnp.asarray(S) * jnp.sum(jnp.asarray(U).reshape(o * v, r) * KU, axis=0)))
[docs]
def kernel(B_ov, eia, tau=1e-4, **kw):
"""Low-rank DF-MP2 from the ov factor (:class:`LowRankResult`). The amplitudes
use the direct kernel, the energy the pair kernel ``2J - K``."""
res = bug_mp2_amplitudes(df_kernel(B_ov, direct_only=True), eia, tau=tau, **kw)
res.energy = bug_mp2_energy(res.U, res.S, df_kernel(B_ov))
return res
# --------------------------------------------------------------------------
# host-backed: B_ov and every pair-height array in host memory, streamed to the
# device one row panel at a time. Rows are zero-padded to whole panels so each
# compiled kernel sees one shape; zero rows add nothing to any accumulation.
# --------------------------------------------------------------------------
@_partial(jax.jit, donate_argnums=(0,))
def _hb_project(X, Bp, Up):
return X + Bp.T @ Up
@_partial(jax.jit, donate_argnums=(0,))
def _hb_grams(acc, Bp, Up, dp, X, S):
"""Accumulate ``U^T d U``, ``U^T J U``, ``U^T U``, ``U^T D`` and the column norms
of the residual ``D = J U - d U S``."""
Ed, Gt, C, G1, nrm = acc
JUp, dUp = Bp @ X, dp[:, None] * Up
Dp = JUp - dUp * S[None, :]
return (Ed + Up.T @ dUp, Gt + Up.T @ JUp, C + Up.T @ Up, G1 + Up.T @ Dp,
nrm + jnp.sum(Dp * Dp, axis=0))
@_partial(jax.jit, static_argnums=(3, 4))
def _hb_select(G1, C, nrm, k, how):
"""``G = G1 + (G1 - C G1)`` (two-pass projection) and ``k`` columns of the
projected residual: the largest by norm (``'residual'``) or the leading ones."""
G = G1 + (G1 - C @ G1)
if k is None or k >= G1.shape[0]:
sel = jnp.arange(G1.shape[0])
elif how != 'residual':
sel = jnp.arange(k)
else:
nrm2 = nrm - 2.0 * jnp.sum(G1 * G, axis=0) + jnp.sum(G * (C @ G), axis=0)
sel = jnp.sort(jnp.argsort(-nrm2)[:k])
return G[:, sel], sel
@jax.jit
def _hb_residual(Bp, Up, dp, X, S, Gs, sel):
Dp = Bp @ X - (dp[:, None] * Up) * S[None, :]
return Dp[:, sel] - Up @ Gs
@_partial(jax.jit, donate_argnums=(0,))
def _hb_blocks(acc, Bp, Up, Qp, dp, Xq):
G_uq, G_qq, E_uq, E_qq = acc
JQp, dQp = Bp @ Xq, dp[:, None] * Qp
return (G_uq + Up.T @ JQp, G_qq + Qp.T @ JQp, E_uq + Up.T @ dQp, E_qq + Qp.T @ dQp)
@_partial(jax.jit, donate_argnums=(0, 1))
def _hb_gram(B, S, Up, Wp):
return B + Up.T @ Wp, S + Wp.T @ Wp
@jax.jit
def _hb_emit_orth(Up, Wp, B, C):
return (Wp - Up @ B) @ C
@_partial(jax.jit, donate_argnums=(0,))
def _hb_sylvester(E, G):
Y = sylvester(E, G)
return Y, jnp.sum(Y * G)
@_partial(jax.jit, donate_argnums=(0,))
def _hb_eigh(Y):
return jnp.linalg.eigh(Y)
@jax.jit
def _hb_exchange_trace(Ut, Bb, Sc):
P = jnp.matmul(Ut[:, None, :, :], jnp.transpose(Bb, (0, 2, 1))[None])
return jnp.sum(Sc * jnp.sum(P * jnp.transpose(P, (0, 1, 3, 2)), axis=(1, 2, 3)))
[docs]
def _hb_orth(U, W, panel, dim, rel_tol=1e-8, passes=2):
"""Streamed CholeskyQR2: directions orthonormal and orthogonal to ``U``.
Each pass accumulates ``U^T W`` and ``W^T W`` and emits ``(W - U U^T W) C``
from the Schur complement's eigenpairs; one pass leaves ``~1e-5`` near
convergence, two reach ``~1e-15``. The cut is on squared singular values,
floored above eps, and the count is capped at ``dim - r``: the complement of
``span(U)`` cannot hold more.
"""
nov, r = U.shape
Q = W
for _ in range(passes):
acc = (jnp.zeros((r, Q.shape[1])), jnp.zeros((Q.shape[1], Q.shape[1])))
for s in range(0, nov, panel):
acc = _hb_gram(*acc, bug_helper.put_rows(U, s, s + panel), bug_helper.put_rows(Q, s, s + panel))
B, Sg = acc
Sc = Sg - B.T @ B
lam, P = jnp.linalg.eigh((Sc + Sc.T) / 2)
lam = bug_helper.get_counted(lam)
keep = np.flatnonzero(lam > max(rel_tol ** 2, 1e-14) * max(float(lam.max()), 0.0))
keep = keep[np.argsort(-lam[keep])][:max(0, dim - r)]
if keep.size == 0:
return np.zeros((nov, 0))
C = P[:, jnp.asarray(keep)] / jnp.sqrt(jnp.asarray(lam[keep]))
out = bug_helper.host_empty((nov, keep.size))
for s in range(0, nov, panel):
out[s:s + panel] = bug_helper.get_counted(
_hb_emit_orth(bug_helper.put_rows(U, s, s + panel), bug_helper.put_rows(Q, s, s + panel), B, C))
Q = out
return Q
[docs]
def bug_mp2_amplitudes_host_backed(B_ov, eia, tau=1e-4, maxiter=100, conv=1e-10, r0=8, seed=0,
max_rank=None, aug_k=None, aug_sel='residual', truncation='relative',
energy_plateau_tolerance=None, amplitude_tol=None,
block_rows=None):
""":func:`bug_mp2_amplitudes` with ``B_ov`` and the basis in host memory.
Same start, iteration, truncation and stop; every pair-height array crosses
the bus one ``block_rows`` panel at a time. ``truncation`` is
``'relative'`` or ``'absolute'``.
"""
require_float64()
if truncation not in ('relative', 'absolute'):
raise ValueError("host-backed BUG-MP2 truncation must be 'relative' or 'absolute'")
o, v, naux = B_ov.shape
N = o * v
B2 = np.ascontiguousarray(np.asarray(B_ov, dtype=np.float64).reshape(N, naux))
r0 = min(int(r0), N)
U0 = np.linalg.qr(np.random.default_rng(seed).standard_normal((N, r0)))[0]
S = np.zeros(r0)
panel = int(min(N, block_rows or bug_helper.auto_block_rows(N, r0)))
Np = -(-N // panel) * panel
d = np.zeros(Np)
d[:N] = np.asarray(eia, dtype=np.float64).reshape(-1)
U = bug_helper.host_empty((Np, r0)); U[:] = 0.0
U[:N] = U0
e_hist, ranks, aug_ranks = [], [], []
stop, it = 'maxiter', -1
for it in range(maxiter):
r = U.shape[1]
Sd = jnp.asarray(S)
X = jnp.zeros((naux, r))
for s in range(0, Np, panel):
X = _hb_project(X, bug_helper.put_rows(B2, s, s + panel), bug_helper.put_rows(U, s, s + panel))
acc = tuple(jnp.zeros((r, r)) for _ in range(4)) + (jnp.zeros(r),)
for s in range(0, Np, panel):
acc = _hb_grams(acc, bug_helper.put_rows(B2, s, s + panel), bug_helper.put_rows(U, s, s + panel),
bug_helper.put_rows(d, s, s + panel), X, Sd)
E_uu, G_uu, C, G1, nrm = acc
k = None if aug_k is None else bug_core.requested_aug_width(r, o, v, aug_k=aug_k)
Gs, sel = _hb_select(G1, C, nrm, k, 'residual' if aug_sel == 'residual' else 'top')
W = bug_helper.host_empty((Np, int(sel.shape[0])))
for s in range(0, Np, panel):
W[s:s + panel] = bug_helper.get_counted(_hb_residual(
bug_helper.put_rows(B2, s, s + panel), bug_helper.put_rows(U, s, s + panel), bug_helper.put_rows(d, s, s + panel),
X, Sd, Gs, sel))
Qa = _hb_orth(U, W, panel, N)
del W
ra = Qa.shape[1]
aug_ranks.append(r + ra)
if ra:
Xq = jnp.zeros((naux, ra))
for s in range(0, Np, panel):
Xq = _hb_project(Xq, bug_helper.put_rows(B2, s, s + panel), bug_helper.put_rows(Qa, s, s + panel))
acc = (jnp.zeros((r, ra)), jnp.zeros((ra, ra)), jnp.zeros((r, ra)), jnp.zeros((ra, ra)))
for s in range(0, Np, panel):
acc = _hb_blocks(acc, bug_helper.put_rows(B2, s, s + panel), bug_helper.put_rows(U, s, s + panel),
bug_helper.put_rows(Qa, s, s + panel), bug_helper.put_rows(d, s, s + panel), Xq)
G_uq, G_qq, E_uq, E_qq = acc
E = jnp.block([[E_uu, E_uq], [E_uq.T, E_qq]])
G = jnp.block([[G_uu, G_uq], [G_uq.T, G_qq]])
else:
E, G = E_uu, G_uu
# Two compiled steps with donation, so few r_aug x r_aug arrays are live
# when the eigensolver asks for its workspace.
Y, e_dir = _hb_sylvester(E, G)
e_hist.append(float(bug_helper.get_counted(e_dir)))
lam, Q = _hb_eigh(Y)
lam = bug_helper.get_counted(lam)
order, rr = rank_cut(lam, tau, truncation)
if max_rank is not None:
rr = min(rr, max_rank)
keep = jnp.asarray(order[:rr])
Wq = Q[r:, keep] if ra else jnp.zeros((1, rr))
U_new, cross = bug_core.hostbacked_basis_update(
U, Qa if ra else np.zeros((Np, 1)), Q[:r, keep], Wq, block_rows=panel)
S_new = lam[order[:rr]]
step, valid = amplitude_step(S_new, S, bug_helper.get_counted(cross), U_new, U,
conv=conv, amplitude_tol=amplitude_tol,
scale=float(np.sqrt(S_new @ S_new)), block_rows=panel)
U, S = np.asarray(U_new), S_new
ranks.append(int(S.shape[0]))
reason = check_stop(step, float(np.sqrt(S @ S)), valid, e_hist,
(plateau_tol(truncation, tau, e_hist[-1])
if energy_plateau_tolerance is None else energy_plateau_tolerance),
conv=conv, amplitude_tol=amplitude_tol)
if reason:
stop = reason
break
return LowRankResult(energy=None, U=U[:N].reshape(o, v, -1), S=S, iterations=it + 1,
converged=stop != 'maxiter', stop_reason=stop, rank_hist=ranks,
e_hist=e_hist, diagnostics=dict(aug_rank_history=aug_ranks))
[docs]
def bug_mp2_energy_host_backed(B_ov, U, S, *, block_rows, col_block=64, aux_block=64):
"""``sum_z S_z <U_z, (2J - K) U_z>`` with ``B_ov`` and ``U`` on the host.
The direct part needs only ``X = B^T U``; the exchange is taken over column
chunks of ``U`` and aux slices of ``B``, as ``tr(P P)`` with ``P = U_z B_q^T``,
so ``K U`` is never formed.
"""
o, v, naux = B_ov.shape
N = o * v
B3 = np.asarray(B_ov, dtype=np.float64)
B2 = B3.reshape(N, naux)
Uh = np.asarray(U, dtype=np.float64).reshape(N, -1)
S = np.asarray(S, dtype=np.float64)
X = jnp.zeros((naux, Uh.shape[1]))
for s in range(0, N, block_rows):
X = _hb_project(X, bug_helper.put_rows(B2, s, s + block_rows), bug_helper.put_rows(Uh, s, s + block_rows))
direct = float(bug_helper.get_counted(jnp.sum(jnp.asarray(S) * jnp.sum(X * X, axis=0))))
exchange = 0.0
for c0 in range(0, Uh.shape[1], col_block):
Ut = jnp.transpose(bug_helper.put_counted(
np.ascontiguousarray(Uh[:, c0:c0 + col_block]).reshape(o, v, -1)), (2, 0, 1))
for q0 in range(0, naux, aux_block):
Bb = bug_helper.put_counted(np.ascontiguousarray(
np.transpose(B3[:, :, q0:q0 + aux_block], (2, 0, 1))))
exchange += float(bug_helper.get_counted(
_hb_exchange_trace(Ut, Bb, jnp.asarray(S[c0:c0 + col_block]))))
return 2.0 * direct - exchange
[docs]
def kernel_host_backed(B_ov, eia, tau=1e-4, *, block_rows=None, col_block=64, **kw):
""":func:`kernel` with ``B_ov`` and the basis in host memory."""
res = bug_mp2_amplitudes_host_backed(B_ov, eia, tau=tau, block_rows=block_rows, **kw)
panel = block_rows or bug_helper.auto_block_rows(B_ov.shape[0] * B_ov.shape[1], res.S.size)
res.energy = bug_mp2_energy_host_backed(B_ov, res.U, res.S, block_rows=panel,
col_block=col_block)
return res
[docs]
def low_rank_mp2(mf, tau: float = 1e-4, *, frozen: int = 0, host_backed: bool = False,
**kwargs) -> LowRankResult:
"""Low-rank closed-shell DF-MP2 of a PySCF density-fitted mean field.
``frozen`` drops the lowest orbitals; ``host_backed`` keeps the basis in host
memory (:func:`kernel_host_backed`). Other keywords go to
:func:`bug_mp2_amplitudes`.
"""
nocc = mf.mol.nelectron // 2 - frozen
e = np.asarray(mf.mo_energy)[frozen:]
_, B_ov, _ = extract_df_factors(mf, nocc, blocks=("ov",),
mo_coeff=np.asarray(mf.mo_coeff)[:, frozen:])
eia = e[:nocc, None] - e[None, nocc:]
return (kernel_host_backed if host_backed else kernel)(B_ov, eia, tau=tau, **kwargs)