Source code for pytc.solver.bug_rpa

"""BUG-dRPA: low-rank direct RPA, matrix-free and iterative.

The Riccati amplitude is kept as ``T = U diag(S) U^T`` in the occupied-virtual
pair space.  Each iteration augments ``U`` with projected-residual directions,
solves the Galerkin (Casida) problem in the augmented space exactly, damps and
truncates.  Two residencies:

* ``host_backed=False`` -- ``B_ov`` and ``U`` on the device;
* ``host_backed=True`` -- ``B_ov`` and every pair-height array in host memory,
  streamed to the device one row panel at a time, for systems whose
  pair-height arrays do not fit in device memory.
"""

from __future__ import annotations

import logging
import time
from functools import partial
from typing import Any, Literal

import jax
import jax.numpy as jnp
import jax.scipy.linalg as jsp_linalg
import numpy as np
from numpy.typing import NDArray

from pytc.solver.bug_core import (LowRankResult, check_stop, extract_df_factors, plateau_tol,
                                  require_float64, requested_aug_width, truncate_sym)
from pytc.solver import bug_core, bug_helper

_logger = logging.getLogger(__name__)

Array = NDArray[np.generic]
Truncation = Literal["relative", "absolute", "energy"]


@jax.jit
def df_matvec(B_ov: Any, V: Any) -> Any:
    """Direct DF pair matrix on pair-space vectors: ``B (B.T V)``, returned as ``(o*v, k)``."""
    n = B_ov.shape[0] * B_ov.shape[1]
    B = jnp.reshape(B_ov, (n, B_ov.shape[2]))
    X = jnp.reshape(V, (n, V.shape[2]))
    return B @ (B.T @ X)


@jax.jit
def df_weighted_energy(B_ov: Any, U: Any, S: Any) -> Any:
    """Direct-DF correlation energy without a pair-space intermediate.

    The DF action is ``B (B.T V)``, so
    ``E = sum_r S_r U_r.T B B.T U_r = sum_r S_r ||B.T U_r||^2``.  Stopping at the
    ``naux x r`` projection removes the full-height ``B @ X`` result, the second
    GEMM that produced it, and the elementwise product that reduced it, which
    together would set the peak device memory for one scalar.
    """
    n = B_ov.shape[0] * B_ov.shape[1]
    X = jnp.reshape(B_ov, (n, B_ov.shape[2])).T @ U
    return jnp.sum(S * jnp.einsum('qr,qr->r', X, X))


@partial(jax.jit, donate_argnums=(0,))
def _panel_accumulate(X, Bp, Vp):
    """``X + Bp.T @ Vp`` with ``X`` donated, so the accumulator is updated in place.

    Without donation each panel would allocate a fresh ``naux x k`` factor and
    leave two alive at once.
    """
    return X + Bp.T @ Vp


@partial(jax.jit, donate_argnums=(0, 1, 2, 3, 4))
def _fused_accum(Ed, Bt, C, G1, nrmD2, Bp, Up, dp, X, S):
    """Fold one panel into all five accumulators, donating every one.

    The update must be inside the compiled boundary: doing ``Ed + eD`` in Python
    lets the old and new accumulator sets coexist, which is invisible to a
    per-panel memory analysis and is exactly the class of defect this design
    exists to remove.  ``BUp`` and ``Dp`` are panel-sized and die in-program, so
    no ``nov``-height object is ever formed.
    """
    BUp = Bp @ X
    Dp = 2.0 * BUp * (1.0 + S[None, :]) + (dp[:, None] * Up) * S[None, :]
    return (Ed + Up.T @ (dp[:, None] * Up),
            Bt + Up.T @ BUp,
            C + Up.T @ Up,
            G1 + Up.T @ Dp,
            nrmD2 + jnp.sum(Dp * Dp, axis=0))


@partial(jax.jit, donate_argnums=(0,))
def _fused_emit_store(out, Bp, Up, dp, X, S, Gs, sel, start):
    """Emit one panel's selected residual columns and store them, donating ``out``.

    Emit and store are one program with ``out`` donated, so the full-height
    result is updated in place; returning a panel and slicing it in outside
    would let two ``nov x k`` outputs coexist.
    """
    BUp = Bp @ X
    Dp = 2.0 * BUp * (1.0 + S[None, :]) + (dp[:, None] * Up) * S[None, :]
    blk = Dp[:, sel] - Up @ Gs
    start = jnp.asarray(start)
    zero = jnp.zeros((), dtype=start.dtype)
    return jax.lax.dynamic_update_slice(out, blk, (start, zero))


@jax.jit
def _fused_emit_panel(Bp, Up, dp, X, S, Gs, sel):
    """One panel of the selected residual, returned rather than stored.

    The stored variant donates a full-height ``out``; host-backed has no such
    array, so this returns the panel and the caller copies it down.
    """
    BUp = Bp @ X
    Dp = 2.0 * BUp * (1.0 + S[None, :]) + (dp[:, None] * Up) * S[None, :]
    return Dp[:, sel] - Up @ Gs


[docs] def fused_host_streamed_core(B_host: Any, U: Any, S: Any, d: Any, *, block_rows: int, k: int | None = None, how: str = "residual", emit_to_host: bool = False, trace_sink: list | None = None): """Core Grams and the selected projected residual, without forming ``BU``. Three host-DF traversals. Every accumulator update and the result store are inside donated compiled boundaries, so nothing of height ``nov`` and no duplicate accumulator set exists at any point. The identities used are exact:: G2 = G1 - C G1 since U.T W = U.T D - (U.T U) G1 ||D - U G||^2 = ||D||^2 - 2 diag(G1.T G) + diag(G.T C G) """ Bm = np.asarray(B_host) B2 = Bm.reshape(-1, Bm.shape[-1]) nov, naux = B2.shape host_basis = isinstance(U, np.ndarray) Ud = U if host_basis else U.reshape(nov, -1) r = int(np.asarray(U).shape[-1]) if host_basis else Ud.shape[1] if host_basis: Ud = np.asarray(U).reshape(nov, -1) panel = int(min(nov, max(1, block_rows))) dv = d.reshape(-1) if not host_basis else None dh = (np.asarray(d) if isinstance(d, np.ndarray) else bug_helper.get_counted(d)).reshape(-1) accum, emit_store = _fused_accum, _fused_emit_store gram = _panel_accumulate def panels(): for i, s0 in enumerate(range(0, nov, panel)): yield i, s0, min(s0 + panel, nov) # When U arrives on the HOST the basis is panelled from there: slicing a # device Ud would require the full nov x r array to be resident, which is # exactly what host-backed removes. Both paths hand the kernels the same # panel, so the arithmetic is identical either way. if host_basis: Uh = np.asarray(U).reshape(nov, -1) def slices(s0, e0): return (bug_helper.put_counted(Uh[s0:e0]), bug_helper.put_counted(dh[s0:e0])) else: def slices(s0, e0): return (jax.lax.dynamic_slice(Ud, (s0, 0), (e0 - s0, r)), jax.lax.dynamic_slice(dv, (s0,), (e0 - s0,))) X = jnp.zeros((naux, r), dtype=Ud.dtype) for i, s0, e0 in panels(): Bp = bug_helper.put_counted(B2[s0:e0]) X = gram(X, Bp, slices(s0, e0)[0]) jax.block_until_ready(X) Bp.delete(); del Bp if trace_sink is not None: trace_sink.append(('fused-pass1', i, bug_helper._live_bytes())) z2 = lambda: jnp.zeros((r, r), dtype=Ud.dtype) acc = (z2(), z2(), z2(), z2(), jnp.zeros((r,), dtype=Ud.dtype)) for i, s0, e0 in panels(): Bp = bug_helper.put_counted(B2[s0:e0]) up, dp = slices(s0, e0) acc = accum(*acc, Bp, up, dp, X, S) jax.block_until_ready(acc[3]) Bp.delete(); del Bp if trace_sink is not None: trace_sink.append(('fused-pass2', i, bug_helper._live_bytes())) Ed, Bt, C, G1, nrmD2 = acc G = G1 + (G1 - C @ G1) if k is None or k >= r: sel = jnp.arange(r) elif how != "residual": sel = jnp.arange(k) # leading columns: amplitude order else: nrm2 = nrmD2 - 2.0 * jnp.sum(G1 * G, axis=0) + jnp.sum(G * (C @ G), axis=0) sel = jnp.sort(jnp.argsort(-nrm2)[:k]) Gs = G[:, sel] ksel = int(sel.shape[0]) if emit_to_host: # host-backed: the residual block is the next nov x k device array, and # keeping it would defeat the mode. Each panel is emitted, copied down # and released, so only one panel of it is ever resident. out_h = bug_helper.host_empty((nov, ksel), dtype=Ud.dtype) emit_panel = _fused_emit_panel for i, s0, e0 in panels(): Bp = bug_helper.put_counted(B2[s0:e0]) up, dp = slices(s0, e0) blk = emit_panel(Bp, up, dp, X, S, Gs, sel) out_h[s0:e0] = bug_helper.get_counted(blk) Bp.delete(); del Bp, blk if trace_sink is not None: trace_sink.append(('fused-pass3-host', i, bug_helper._live_bytes())) return Ed, 2.0 * Bt, out_h out = jnp.empty((nov, ksel), dtype=Ud.dtype) for i, s0, e0 in panels(): Bp = bug_helper.put_counted(B2[s0:e0]) up, dp = slices(s0, e0) out = emit_store(out, Bp, up, dp, X, S, Gs, sel, s0) jax.block_until_ready(out) Bp.delete(); del Bp if trace_sink is not None: trace_sink.append(('fused-pass3', i, bug_helper._live_bytes())) return Ed, 2.0 * Bt, out
[docs] def df_weighted_energy_host_streamed(B_host: Any, U: Any, S: Any, *, block_rows: int, trace_sink: list | None = None) -> Any: """``sum_r S_r ||B.T U_r||^2`` with ``B`` host-resident. This is the first pass of the streamed DF action and nothing more: the energy needs only the auxiliary factor, so ``B`` is traversed once and the pair-space vector is never formed on either side. """ B2 = np.asarray(B_host).reshape(-1, np.asarray(B_host).shape[-1]) nov, naux = B2.shape host_basis = isinstance(U, np.ndarray) Ud = np.asarray(U).reshape(nov, -1) if host_basis else U.reshape(nov, -1) r = Ud.shape[1] panel = int(min(nov, max(1, block_rows))) accum = _panel_accumulate X = jnp.zeros((naux, r), dtype=Ud.dtype) for i3, s in enumerate(range(0, nov, panel)): e = min(s + panel, nov) Bp = bug_helper.put_counted(B2[s:e]) Up = (bug_helper.put_counted(Ud[s:e]) if host_basis else jax.lax.dynamic_slice(Ud, (s, 0), (e - s, r))) X = accum(X, Bp, Up) jax.block_until_ready(X) Bp.delete() if host_basis: Up.delete() del Bp, Up if trace_sink is not None: trace_sink.append(('energy', i3, bug_helper._live_bytes())) return jnp.sum(S * jnp.einsum('qr,qr->r', X, X))
@partial(jax.jit, static_argnames=('n_panel', 'panel')) def _streamed_core_gram(U, BU, d, n_panel, panel): """The two ``r x r`` core Grams, accumulated over row panels. ``Ed_uu = U.T @ (d U)`` and ``Bt_uu = 2 U.T @ BU`` both contract ``nov`` away into ``r x r``. Written eagerly, the first materialises ``d[:, None] * U`` at full height -- ``nov x r`` -- purely to be contracted immediately. Accumulating both per panel removes it and costs one pass. The clamped tail panel repeats rows, so each contribution is masked to the rows its panel owns. """ nov, r = U.shape def body(i, acc): Ed, Bt = acc s, Up, BUp, dp = _panel_slices(U, BU, d, i, panel) Um = Up * _owned(i, s, U.dtype, panel) return (Ed + Um.T @ (dp[:, None] * Up), Bt + Um.T @ BUp) Ed, Bt = jax.lax.fori_loop( 0, n_panel, body, (jnp.zeros((r, r), U.dtype), jnp.zeros((r, r), U.dtype))) return Ed, 2.0 * Bt
[docs] def streamed_core_grams(U, BU, d, *, block_rows=None): """``(U.T @ (d U), 2 U.T @ BU)`` without a full-height intermediate.""" nov, r = U.shape if nov < 2 or r == 0: return U.T @ (d[:, None] * U), 2 * (U.T @ BU) n_panel, panel = _panel_plan(nov, block_rows) return _streamed_core_gram(U, BU, d, n_panel, panel)
@partial(jax.jit, static_argnames=('n_panel', 'panel')) def _basis_update(Ur, Qa, Wu, Wq, n_panel, panel): """Row-panelled ``Ur @ Wu + Qa @ Wq``. The eager expression evaluates both products before adding them, leaving two extra full-height results alive at the point that sets the run's HBM high-water. Writing the sum panel by panel into a single carried output leaves one full result plus ``panel x r`` scratch. The final panel is clamped to end at ``nov``, so it repeats rows and writes the same values -- idempotent, and no multi-GB operand is padded. """ nov = Ur.shape[0] def body(i, out): s = jnp.minimum(i * panel, nov - panel) blk = (jax.lax.dynamic_slice(Ur, (s, 0), (panel, Ur.shape[1])) @ Wu + jax.lax.dynamic_slice(Qa, (s, 0), (panel, Qa.shape[1])) @ Wq) return jax.lax.dynamic_update_slice(out, blk, (s, 0)) return jax.lax.fori_loop(0, n_panel, body, jnp.empty((nov, Wu.shape[1]), dtype=Ur.dtype))
[docs] def basis_update(Ur, Qa, Wu, Wq, *, block_rows: int | None = None): """Form the updated amplitude basis without extra full-height results.""" nov, r = Ur.shape[0], Wu.shape[1] if nov < 2 or r == 0: return Ur @ Wu + Qa @ Wq if block_rows is None: block_rows = bug_helper.auto_block_rows(nov, r) panel = int(min(nov, max(1, block_rows))) return _basis_update(Ur, Qa, Wu, Wq, -(-nov // panel), panel)
@partial(jax.jit, donate_argnums=(0, 1, 2, 3)) def _hostbacked_core_accum(Bt_uq, Bt_qq, Ed_uq, Ed_qq, Bp, Up, Qp, dp, Xq): """All four cross/diagonal core blocks from one panel. BQa is formed for the panel only. Building it at full height is the ``nov x ra`` allocation the host-backed mode exists to remove. """ BQp = Bp @ Xq dQp = dp[:, None] * Qp return (Bt_uq + 2.0 * (Up.T @ BQp), Bt_qq + 2.0 * (Qp.T @ BQp), Ed_uq + Up.T @ dQp, Ed_qq + Qp.T @ dQp)
[docs] def hostbacked_core_blocks(B_host: Any, U_host: Any, Qa_host: Any, d: Any, Ed_uu: Any, Bt_uu: Any, *, block_rows: int, trace_sink: list | None = None): """Projected core blocks with every tall operand on the host. Two traversals. The first builds ``X_q = B^T Qa`` (``naux x ra``, an N^2 object); the second accumulates the four remaining core blocks, forming each panel's ``BQa`` inside the compiled boundary and discarding it there. Returns ``(Ed + Bt, Bt)`` exactly as :func:`rpa_core_blocks` does, so the eigenproblem downstream cannot tell which path produced it. """ Bm = np.asarray(B_host) B2 = Bm.reshape(-1, Bm.shape[-1]) nov, naux = B2.shape Um = np.asarray(U_host).reshape(nov, -1) Qm = np.asarray(Qa_host).reshape(nov, -1) r0, ra = Um.shape[1], Qm.shape[1] # d_pair may already exist on the host; fetch it only when it does not. dv = (np.asarray(d) if isinstance(d, np.ndarray) else bug_helper.get_counted(d)).reshape(-1) panel = int(min(nov, max(1, block_rows))) dtype = Um.dtype xq = hostbacked_xq Xq = jnp.zeros((naux, ra), dtype=dtype) for i, s0 in enumerate(range(0, nov, panel)): e0 = min(s0 + panel, nov) Bp = bug_helper.put_counted(B2[s0:e0]) Qp = bug_helper.put_counted(Qm[s0:e0]) Xq = xq(Xq, Bp, Qp) jax.block_until_ready(Xq) Bp.delete(); Qp.delete() if trace_sink is not None: trace_sink.append(('hb-core-pass1', i, bug_helper._live_bytes())) accum = _hostbacked_core_accum acc = (jnp.zeros((r0, ra), dtype=dtype), jnp.zeros((ra, ra), dtype=dtype), jnp.zeros((r0, ra), dtype=dtype), jnp.zeros((ra, ra), dtype=dtype)) for i, s0 in enumerate(range(0, nov, panel)): e0 = min(s0 + panel, nov) Bp = bug_helper.put_counted(B2[s0:e0]) Up = bug_helper.put_counted(Um[s0:e0]) Qp = bug_helper.put_counted(Qm[s0:e0]) dp = bug_helper.put_counted(dv[s0:e0]) acc = accum(*acc, Bp, Up, Qp, dp, Xq) jax.block_until_ready(acc[0]) Bp.delete(); Up.delete(); Qp.delete(); dp.delete() if trace_sink is not None: trace_sink.append(('hb-core-pass2', i, bug_helper._live_bytes())) Bt_uq, Bt_qq, Ed_uq, Ed_qq = acc Bt = jnp.block([[Bt_uu, Bt_uq], [Bt_uq.T, Bt_qq]]) Ed = jnp.block([[Ed_uu, Ed_uq], [Ed_uq.T, Ed_qq]]) return Ed + Bt, Bt
@jax.jit def rpa_core_blocks(U, Qa, BQa, d, Ed_uu, Bt_uu): # The pair operator and diagonal orbital-energy operator are symmetric. # Their lower cross blocks are therefore exact transposes of the upper # blocks; forming both sides separately was one redundant O(N r k) # GEMM and, for E, another full N x k scaled-basis temporary. """Build the augmented RPA core matrices in one compiled program. Keeping the complete block algebra in one XLA program lets the row-scaled ``dQa`` storage die before the two returned core matrices become live in Python. """ Bt_uq = 2 * (U.T @ BQa) Bt_qq = 2 * (Qa.T @ BQa) # Stream the diagonal-weighted Gram matrices over rows. The eager # expression materialises all of d[:,None] * Qa even though each row is # consumed exactly once by the two reductions. bn = min(4096, U.shape[0]) nb = U.shape[0] // bn nm = nb * bn acc = (jnp.zeros((U.shape[1], Qa.shape[1]), dtype=U.dtype), jnp.zeros((Qa.shape[1], Qa.shape[1]), dtype=U.dtype)) def weighted_gram(ib, carry): start = ib * bn Ub = jax.lax.dynamic_slice( U, (start, 0), (bn, U.shape[1])) Qb = jax.lax.dynamic_slice( Qa, (start, 0), (bn, Qa.shape[1])) db = jax.lax.dynamic_slice(d, (start,), (bn,)) dQb = db[:, None] * Qb return (carry[0] + Ub.T @ dQb, carry[1] + Qb.T @ dQb) Ed_uq, Ed_qq = jax.lax.fori_loop(0, nb, weighted_gram, acc) if nm < U.shape[0]: dQt = d[nm:, None] * Qa[nm:] Ed_uq = Ed_uq + U[nm:].T @ dQt Ed_qq = Ed_qq + Qa[nm:].T @ dQt Bt = jnp.block([[Bt_uu, Bt_uq], [Bt_uq.T, Bt_qq]]) Ed = jnp.block([[Ed_uu, Ed_uq], [Ed_uq.T, Ed_qq]]) return Ed + Bt, Bt @jax.jit def core_sym_eig(E: Any, Bt: Any) -> tuple[Any, Any, Any]: """Device Cholesky-Casida projected RPA core solve. Returns ``(T, min_w2, min_cholesky_diagonal)``. A failed factorization maps both diagnostics to ``-inf`` so the host-side stability guard fails loudly instead of silently accepting NaN amplitudes. """ H = E - Bt H = (H + H.T) / 2 L = jnp.linalg.cholesky(H) cholesky_ok = jnp.all(jnp.isfinite(L)) C = L.T @ (E + Bt) @ L C = (C + C.T) / 2 w2, W = jnp.linalg.eigh(C) w = jnp.sqrt(jnp.clip(w2, 0.0, None)) w = jnp.where(w > 1e-14, w, 1e-14) wh = jnp.sqrt(w) P = jsp_linalg.solve_triangular( L.T, W * wh[None, :], lower=False) Q = L @ (W / wh[None, :]) X = P + Q Y = P - Q T = -jnp.linalg.solve(X.T, Y.T).T min_w2 = jnp.where(cholesky_ok, jnp.min(w2), -jnp.inf) min_cholesky = jnp.where( cholesky_ok, jnp.min(jnp.diag(L)), -jnp.inf) return (T + T.T) / 2, min_w2, min_cholesky @jax.jit def _rpa_projected_residual(U, V, S, BU, d): # The omitted RPA residual terms are U @ C and therefore vanish under # the following projection. Build only the orthogonal component and # keep its elementwise assembly plus both Gram--Schmidt passes inside # one compiled program so XLA can reuse the nov x rank temporaries. D = 2 * BU * (1 + S[None, :]) + d[:, None] * V * S[None, :] W = D - U @ (U.T @ D) return W - U @ (U.T @ W)
[docs] def _panel_plan(nov: int, block_rows): """Row panel and panel count, clamped to the array.""" panel = int(min(nov, max(1, block_rows if block_rows else 8192))) return -(-nov // panel), panel
[docs] def _panel_slices(U, BU, d, i, panel): nov, r = U.shape s = jnp.minimum(i * panel, nov - panel) return (s, jax.lax.dynamic_slice(U, (s, 0), (panel, r)), jax.lax.dynamic_slice(BU, (s, 0), (panel, r)), jax.lax.dynamic_slice(d, (s,), (panel,)))
[docs] def _residual_panel(Up, BUp, dp, S): return 2.0 * BUp * (1.0 + S[None, :]) + (dp[:, None] * Up) * S[None, :]
[docs] def _owned(i, s, dtype, panel): """Mask to the rows panel ``i`` owns: the clamped tail panel repeats rows.""" return ((s + jnp.arange(panel)) >= i * panel).astype(dtype)[:, None]
@partial(jax.jit, static_argnames=('n_panel', 'panel')) def _residual_gram(U, S, BU, d, n_panel, panel): """Combined projection Gram ``G1 + G2`` of the residual, in row panels. The residual is ``D = 2 BU (1+S) + d U S`` deflated twice against ``U``. Both Grams contract over ``nov`` into ``r x r``, so no stage needs ``D`` at full height -- it is rebuilt per panel rather than stored. Because ``W - U G2 = D - U (G1 + G2)``, one combined Gram serves every later pass. """ r = U.shape[1] def g1(i, G): s, Up, BUp, dp = _panel_slices(U, BU, d, i, panel) return G + Up.T @ (_residual_panel(Up, BUp, dp, S) * _owned(i, s, U.dtype, panel)) G1 = jax.lax.fori_loop(0, n_panel, g1, jnp.zeros((r, r), U.dtype)) def g2(i, G): s, Up, BUp, dp = _panel_slices(U, BU, d, i, panel) Wp = _residual_panel(Up, BUp, dp, S) - Up @ G1 return G + Up.T @ (Wp * _owned(i, s, U.dtype, panel)) return G1 + jax.lax.fori_loop(0, n_panel, g2, jnp.zeros((r, r), U.dtype)) @partial(jax.jit, static_argnames=('n_panel', 'panel')) def _residual_emit(U, S, BU, d, G, sel, n_panel, panel): """Columns ``sel`` of the projected residual ``D - U G``, panel by panel.""" nov = U.shape[0] def body(i, out): s, Up, BUp, dp = _panel_slices(U, BU, d, i, panel) Wp = _residual_panel(Up, BUp, dp, S) - Up @ G return jax.lax.dynamic_update_slice(out, Wp[:, sel], (s, 0)) return jax.lax.fori_loop(0, n_panel, body, jnp.empty((nov, sel.shape[0]), U.dtype)) @partial(jax.jit, static_argnames=('n_panel', 'panel')) def _residual_colnorm2(U, S, BU, d, G, n_panel, panel): r = U.shape[1] def body(i, sq): s, Up, BUp, dp = _panel_slices(U, BU, d, i, panel) Wp = (_residual_panel(Up, BUp, dp, S) - Up @ G) * _owned(i, s, U.dtype, panel) return sq + jnp.sum(Wp * Wp, axis=0) return jax.lax.fori_loop(0, n_panel, body, jnp.zeros((r,), U.dtype))
[docs] def projected_residual(U, S, BU, d, *, k=None, how="residual", block_rows=None): """RPA residual ``D = 2 BU (1+S) + d U S`` deflated twice against ``U``. All ``r`` columns, or ``k`` of them: the largest by norm (``how='residual'``, selected from streamed column norms, so only the chosen columns are ever emitted at full height) or the leading ones (``how='top'``). Row panels keep every intermediate at ``panel x r``. """ nov, r = U.shape if k is not None and k >= r: k = None if k is not None and how != "residual": return _rpa_projected_residual(U, U[:, :k], S[:k], BU[:, :k], d) if nov < 2 or r == 0: W = _rpa_projected_residual(U, U, S, BU, d) return W if k is None else W[:, jnp.sort(jnp.argsort(-jnp.linalg.norm(W, axis=0))[:k])] n_panel, panel = _panel_plan(nov, block_rows) G = _residual_gram(U, S, BU, d, n_panel, panel) sel = (jnp.arange(r) if k is None else jnp.sort(jnp.argsort(-_residual_colnorm2(U, S, BU, d, G, n_panel, panel))[:k])) return _residual_emit(U, S, BU, d, G, sel, n_panel, panel)
@partial(jax.jit, donate_argnums=(0,)) def _gram_accum(G, panel): """Accumulate Q^T Q one panel at a time; donates the accumulator.""" return G + panel.T @ panel @jax.jit def _emit_q_panel(panel, T): """One panel of Q = W T, written straight into the host-side output.""" return panel @ T
[docs] def streamed_reorthogonalize(U_host: Any, Q_host: Any, *, block_rows: int, tol: float = 1e-10): """Second Gram-Schmidt pass of host-resident ``Q`` against the host basis ``U``, streamed by row panels: ``C = U^T Q``; if ``max|C| > tol``, ``Q <- Q - U C`` (in place). Returns ``max|C|`` before the correction. A single projection of the residual against ``U`` loses orthogonality at large rank ("twice is enough"); a non-orthonormal ``[U | Q]`` makes the projected Casida problem indefinite.""" n = U_host.shape[0] if Q_host.shape[1] == 0 or U_host.shape[1] == 0: return 0.0 panel = int(min(n, max(1, block_rows))) C = jnp.zeros((U_host.shape[1], Q_host.shape[1]), dtype=Q_host.dtype) for s0 in range(0, n, panel): ub = bug_helper.put_counted(np.asarray(U_host[s0:s0 + panel])) qb = bug_helper.put_counted(np.asarray(Q_host[s0:s0 + panel])) C = C + ub.T @ qb ub.delete(); qb.delete() err = float(jnp.abs(C).max()) if err > tol: for s0 in range(0, n, panel): ub = bug_helper.put_counted(np.asarray(U_host[s0:s0 + panel])) qb = bug_helper.put_counted(np.asarray(Q_host[s0:s0 + panel])) Q_host[s0:s0 + panel] = bug_helper.get_counted(qb - ub @ C) ub.delete(); qb.delete() return err
[docs] def streamed_orth_directions(W_host: Any, rel_tol: float = 1e-10, *, block_rows: int, orth_tol: float = 1e-8, max_passes: int = 2, trace_sink: list | None = None): """Rank-revealing orthonormal basis of a HOST-resident block. Returns ``(Q_host, kept, diagnostics)`` with ``Q_host`` a NumPy array, so nothing of height ``nov`` is left on the device. Three passes over the host data, none of which materialises a tall device array: 1. ``R`` by sequential TSQR (:func:`streamed_tsqr_r`). 2. Pivot the small ``R`` and drop the numerically dependent columns -- the same rank decision the in-core path makes, on the same matrix. 3. Emit ``Q = W T`` panel by panel, then MEASURE ``||Q^T Q - I||``; if it is not tight, orthogonalise the emitted ``Q`` once more (CholeskyQR2). The gate in step 3 is not decoration. Recovering ``Q`` from a triangular factor loses orthogonality when ``W`` is ill-conditioned, and an unorthogonal basis corrupts the projected core silently -- the energy stays plausible. Measuring and repeating is the standard remedy. """ Wm = np.asarray(W_host) diags: dict[str, Any] = {"passes": 0, "kept": 0, "orth_error": None, "orth_tol": orth_tol, "orth_error_history": []} # Zero augmentation width is a legitimate capped state, not an error: the # resident path supports it, so the host-backed path must too. Handled # before the reshape, which cannot infer -1 from an empty array. if Wm.shape[-1] == 0: nrow0 = int(Wm.shape[0]) if Wm.ndim >= 1 else 0 return np.zeros((nrow0, 0), dtype=Wm.dtype), 0, diags W2 = Wm.reshape(-1, Wm.shape[-1]) nrow, k = W2.shape if nrow == 0: return np.zeros((0, 0), dtype=W2.dtype), 0, diags R = streamed_tsqr_r(W2, block_rows=block_rows) # Pivot the small R: W P = Q (Qr Rr). The kept directions are the leading # pivoted columns, Q Qr[:, :m] = W P[:, :m] Rr[:m, :m]^{-1}; only the leading # nonsingular block is inverted, so a dependent column of W cannot make the # solve singular. _, Rr, piv = jsp_linalg.qr(R, mode="economic", pivoting=True) diag = np.abs(np.diag(bug_helper.get_counted(Rr))) if diag.size == 0 or not (diag > rel_tol * max(1.0, float(diag.max()))).any(): return np.zeros((nrow, 0), dtype=W2.dtype), 0, diags nkeep = int((diag > rel_tol * max(1.0, float(diag.max()))).sum()) diags["kept"] = nkeep diags["dropped"] = int(diag.size - nkeep) inv = jsp_linalg.solve_triangular(Rr[:nkeep, :nkeep], jnp.eye(nkeep, dtype=W2.dtype)) T = jnp.zeros((k, nkeep), dtype=W2.dtype).at[piv[:nkeep]].set(inv) panel = int(min(nrow, max(1, block_rows))) emit = _emit_q_panel gram = _gram_accum Q_host = bug_helper.host_empty((nrow, nkeep), dtype=W2.dtype) src = W2 for p in range(max_passes): G = jnp.zeros((nkeep, nkeep), dtype=W2.dtype) for s0 in range(0, nrow, panel): blk = bug_helper.put_counted(src[s0:s0 + panel]) qb = emit(blk, T) blk.delete() G = gram(G, qb) Q_host[s0:s0 + panel] = bug_helper.get_counted(qb) del qb if trace_sink is not None: trace_sink.append(('tsqr-emit', p, s0, bug_helper._live_bytes())) G = bug_helper.get_counted(jax.block_until_ready(G)) err = float(np.abs(G - np.eye(nkeep, dtype=G.dtype)).max()) diags["passes"] = p + 1 diags["orth_error"] = err diags["orth_error_history"].append(err) if err <= orth_tol: break # Not orthogonal enough: orthogonalise what was just emitted, Q <- Q R2^{-1} # (CholeskyQR2). Q is well conditioned, so this pass reaches roundoff; # re-applying a corrected T to the original W would inherit cond(W) again. R2 = streamed_tsqr_r(Q_host, block_rows=block_rows) T = jsp_linalg.solve_triangular(R2, jnp.eye(nkeep, dtype=W2.dtype)) src = Q_host else: # Every pass used and still not orthogonal. Returning here would hand # back a basis that is not a basis: the projected core would be formed # against non-orthonormal columns and the energy would stay plausible # while being wrong. Refuse. A caller who hits this should raise # rel_tol so the offending near-dependent columns are dropped instead. raise RuntimeError( f"streamed_orth_directions: ||Q^T Q - I|| = {diags['orth_error']:.3e} " f"still exceeds orth_tol={orth_tol:.3e} after {max_passes} passes " f"(kept {nkeep} of {int(diag.size)} columns). The block is too " "ill-conditioned to orthogonalise this way; raise rel_tol to drop " "the dependent directions.") return Q_host, nkeep, diags
@partial(jax.jit, donate_argnums=(0,)) def hostbacked_xq(X, Bp, Qp): """Accumulate X_q = B^T Qa one panel at a time. Donates the accumulator.""" return X + Bp.T @ Qp @jax.jit def _panel_qr_r(panel): """R factor of one row panel. Q is discarded -- only R crosses the tree.""" return jnp.linalg.qr(panel, mode="r")
[docs] def streamed_tsqr_r(W_host: Any, *, block_rows: int) -> Any: """R factor of a host-resident tall matrix, by panel reduction. Sequential TSQR: each row panel contributes its own ``R_p``, and the running factor is re-reduced against it. Only ``k x k`` state ever exists, so the tall ``Q`` is never formed -- which is the whole point, since ``Q`` is exactly the ``nov x k`` array the host-backed mode exists to keep off the device. This is numerically the stable half. Recovering ``Q`` from ``R`` is the delicate half, and is gated separately in :func:`streamed_orth_directions`. """ Wm = np.asarray(W_host) # A capped max_rank can leave zero augmentation width. reshape(-1, 0) # cannot infer the row count from an empty array, so the width is handled # before any reshape rather than after it. if Wm.shape[-1] == 0: return jnp.zeros((0, 0), dtype=Wm.dtype) W2 = Wm.reshape(-1, Wm.shape[-1]) nrow, k = W2.shape panel = int(min(nrow, max(1, block_rows))) qr_r = _panel_qr_r acc = None for s0 in range(0, nrow, panel): blk = bug_helper.put_counted(W2[s0:s0 + panel]) r_p = qr_r(blk) blk.delete() if acc is None: acc = r_p else: # Re-reduce the stacked pair: R([R_acc; R_p]) == R(all rows so far). acc = qr_r(jnp.concatenate([acc, r_p], axis=0)) acc = jax.block_until_ready(acc) return acc
[docs] def _initial_guess( n_pair: int, init: tuple[Array, Array] | None, ) -> tuple[Array, Array]: """Normalize and validate a low-rank initial factorization.""" if init is None: rng = np.random.default_rng(0) rank = min(8, n_pair) basis, _ = np.linalg.qr(rng.standard_normal((n_pair, rank))) return basis, np.zeros(rank) basis_raw, values_raw = init basis_array = np.asarray(basis_raw) if basis_array.size % n_pair: raise ValueError("init U cannot be reshaped into the pair space") basis = basis_array.reshape(n_pair, -1) values = np.asarray(values_raw) if values.ndim != 1: raise ValueError("init S must be a one-dimensional array") if basis.shape[1] != values.size: raise ValueError("init U column count must match the length of S") if values.size == 0 or values.size > n_pair: raise ValueError("init rank must be between one and the pair dimension") gram_error = float(np.linalg.norm( basis.T @ basis - np.eye(basis.shape[1]), ord=np.inf)) if gram_error > 1e-8: raise ValueError( f"init U must have orthonormal columns; error={gram_error:.3e}") return basis, values
[docs] def kernel(B_ov: Array, eia: Array, tau: float = 1e-4, maxiter: int = 100, conv: float = 1e-10, rmin: int = 1, damp: float = 0.7, max_rank: int | None = None, init: tuple[Array, Array] | None = None, aug_k: float | None = None, aug_sel: Literal["amplitude", "residual"] = "residual", energy_plateau_tolerance: float | None = None, amplitude_tol: float | None = None, truncation: Truncation = 'relative', host_backed: bool = False, block_rows: int | None = None, dense_core: bug_core.DenseCore = "device") -> LowRankResult: """Low-rank closed-shell dRPA from the DF factor ``B_ov (nocc, nvir, naux)`` and ``eia = e_i - e_a``. ``tau``/``truncation`` cut the Galerkin core (:func:`bug_core.truncate_sym`); ``damp`` mixes the new core with the old amplitudes; ``aug_k`` is the count, or fraction of the rank, of residual directions added per iteration (``None``: as many as the rank), chosen by projected-residual norm (``aug_sel='residual'``) or in amplitude order (``'amplitude'``). ``host_backed`` keeps ``B_ov`` and the basis in host memory; ``block_rows`` is the row panel of the streamed kernels (default from the device arena). ``dense_core`` runs the core solve and the truncation eigh on the device (``"device"``; out of memory stops the run) or on the host CPU (``"host"``). Stops by :func:`bug_core.check_stop`. ``U`` is returned as ``(nocc, nvir, rank)``. """ require_float64() if np.ndim(B_ov) != 3 or tuple(np.shape(B_ov)[:2]) != tuple(np.shape(eia)): raise ValueError("need B_ov (nocc, nvir, naux) and eia (nocc, nvir)") if not 0 < damp <= 1: raise ValueError("damp must be in (0, 1]") if maxiter < 1: raise ValueError("maxiter must be at least 1") if aug_sel not in ("amplitude", "residual"): raise ValueError("aug_sel must be 'amplitude' or 'residual'") if truncation not in ("relative", "absolute", "energy") or not tau >= 0: raise ValueError("truncation must be relative/absolute/energy with tau >= 0") if dense_core not in ("device", "host"): raise ValueError("dense_core must be 'device' or 'host'") o, v, naux = B_ov.shape N = o * v d = jax.device_put((-np.asarray(eia)).reshape(-1)) B = None if host_backed else jax.device_put(B_ov) U0, S0 = _initial_guess(N, init) U = np.asarray(U0) if host_backed else jax.device_put(U0) S = jax.device_put(S0) panel = block_rows or bug_helper.auto_block_rows(N, S.shape[0]) how = 'residual' if aug_sel == 'residual' else 'top' rank_hist, aug_rank_hist, e_hist, iter_times = [], [], [], [] min_w2_hist, max_s_hist, cross_hist = [], [], [] converged, stop_reason, it = False, 'maxiter', -1 for it in range(maxiter): t0 = time.perf_counter() r0 = S.shape[0] Ur = U.reshape(N, r0) requested = r0 if aug_k is not None: requested = requested_aug_width(r0, o, v, aug_k=aug_k, max_rank=max_rank) elif max_rank is not None: requested = min(requested, max(int(max_rank) - r0, 0)) k = None if requested >= r0 else requested # Core Grams, selected projected residual and the augmenting directions. # The augmented basis [Ur | Qa] is never formed: the core blocks and the # update U_aug W = Ur W[:r0] + Qa W[r0:] read the two halves separately. if host_backed: Ed_uu, Bt_uu, Wdir = fused_host_streamed_core( B_ov, Ur, S, d, block_rows=panel, k=k, how=how, emit_to_host=True) Qa, _, _ = streamed_orth_directions(Wdir, block_rows=panel) del Wdir # cross-orthogonality to the kept basis: re-project and re-orthonormalize if it drifted xorth = streamed_reorthogonalize(Ur, Qa, block_rows=panel) if xorth > 1e-10: Qa, _, _ = streamed_orth_directions(Qa, block_rows=panel) cross_hist.append(xorth) E, Bt = hostbacked_core_blocks(B_ov, Ur, Qa, d, Ed_uu, Bt_uu, block_rows=panel) else: # One matvec: B B^T acts column by column, so B B^T (U S) = (B B^T U) S. BU = df_matvec(B, Ur.reshape(o, v, r0)) Ed_uu, Bt_uu = streamed_core_grams(Ur, BU, d, block_rows=panel) Wdir = projected_residual(Ur, S, BU, d, k=k, how=how, block_rows=panel) del BU Qa = bug_core.orth_directions(Wdir, donate=True) del Wdir BQa = df_matvec(B, Qa.reshape(o, v, -1)) E, Bt = rpa_core_blocks(Ur, Qa, BQa, d, Ed_uu, Bt_uu) del BQa aug_rank_hist.append(r0 + Qa.shape[1]) Y, min_w2, min_cholesky = bug_core.run_dense("core_sym_eig", core_sym_eig, E, Bt, dense_core=dense_core) min_w2, min_cholesky = map(float, jax.device_get((min_w2, min_cholesky))) if min_cholesky <= 0: raise RuntimeError("Cholesky factorization of A-B failed: zero/negative orbital-gap " "mode, so the stabilizing direct-RPA branch is undefined") if min_w2 < -1e-8: raise RuntimeError(f"negative Casida eigenvalue w2={min_w2:.3e} (imaginary " "excitation): RPA instability") M = (damp * Y).at[jnp.arange(r0), jnp.arange(r0)].add((1 - damp) * S) W, S_new, _ = truncate_sym((M + M.T) / 2, tau, rmin=rmin, max_rank=max_rank, rule=truncation, energy_metric=Bt / 2.0, dense_core=dense_core) e_hist.append(float(jax.device_get(jnp.sum(S_new * jnp.sum(W * ((Bt / 2.0) @ W), axis=0))))) del E, Bt, Y, M if host_backed: U_new, cross = bug_core.hostbacked_basis_update(Ur, Qa, W[:r0], W[r0:], block_rows=panel) else: U_new = basis_update(Ur, Qa, W[:r0], W[r0:], block_rows=panel) cross = U_new.T @ Ur del Qa step, valid = bug_core.amplitude_step( jax.device_get(S_new), jax.device_get(S), jax.device_get(cross), U_new, Ur, conv=conv, amplitude_tol=amplitude_tol, scale=float(np.sqrt(float(jax.device_get(S_new @ S_new)))), block_rows=panel) U, S = U_new, S_new rank_hist.append(int(S.shape[0])) min_w2_hist.append(min_w2) max_s = float(jax.device_get(jnp.max(jnp.abs(S)))) max_s_hist.append(max_s) iter_times.append(time.perf_counter() - t0) # max|U^T Q| is measured only on the host-backed path orth = f" max|U^T Q| {cross_hist[-1]:.2e}" if host_backed else "" _logger.info("bug_rpa it %d rank %d aug %d E %.10f |dT| %.2e min_w2 %.3e%s t %.0fs", it + 1, rank_hist[-1], aug_rank_hist[-1], e_hist[-1], step, min_w2, orth, iter_times[-1]) if max_s >= 1.0: raise RuntimeError(f"unphysical RPA solution: max|S|={max_s:.3e} >= 1 " "(wrong branch / instability)") reason = check_stop(step, float(np.sqrt(float(jax.device_get(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: converged, stop_reason = True, reason break # E = sum_r S_r ||B^T U_r||^2 needs only the naux x r projection. E_c = float(jax.device_get( df_weighted_energy_host_streamed(B_ov, U, S, block_rows=panel) if host_backed else df_weighted_energy(B, U, S))) stats = bug_helper.device_memory_stats() return LowRankResult( energy=E_c, U=np.asarray(jax.device_get(U)).reshape(o, v, -1), S=np.asarray(jax.device_get(S)), iterations=it + 1, converged=converged, stop_reason=stop_reason, rank_hist=rank_hist, e_hist=e_hist, diagnostics=dict(aug_rank_hist=aug_rank_hist, iter_times=iter_times, min_w2_hist=min_w2_hist, max_s_hist=max_s_hist, cross_orth_hist=cross_hist, dense_core=dense_core, device_peak_bytes=stats.get('peak_bytes_in_use') if stats else None))
[docs] def pair_window(mo_occ: Array, occ_tol: float = 1e-6) -> tuple[Array, Array]: """Orbitals that can give (``f > 0``) and take (``f < 2``) an electron. For integer occupations these are the occupied and virtual sets; smearing makes them overlap in the partially filled window around the Fermi level. """ f = np.asarray(mo_occ) return np.flatnonzero(f > occ_tol), np.flatnonzero(f < 2 - occ_tol)
[docs] def weighted_pairs(B: Array, mo_energy: Array, mo_occ: Array, occ_tol: float = 1e-6) -> tuple[Array, Array]: """Direct-RPA pair factors and gaps for a (possibly) fractional reference. ``B`` holds ``(p q|P)`` for ``p, q`` in :func:`pair_window`, shape ``(|O|, |V|, naux)``. With spin-summed occupations ``f``, the pair ``p -> q`` enters chi_0 with weight ``n = (f_p - f_q) / 2``, which folds into the factors as ``sqrt(n) B``; the problem is then an ordinary one in ``(sqrt(n) B, e_q - e_p)`` and :func:`kernel` solves it unchanged. Every pair of the window with ``n > 0`` is kept, however small ``n``: as in fcdmft, ``occ_tol`` only selects the orbitals. (Near-degenerate pairs have tiny ``n`` and tiny gap but a finite ``n / gap``; cutting them at ``n > occ_tol`` moved a 36-Cu slab by 2e-6 Ha against fcdmft.) Pairs with no weight (equal occupations, or the wrong direction) get zero factors and a positive dummy gap, so they decouple exactly. Integer occupations return ``(B, e_i - e_a)``. """ f, e = np.asarray(mo_occ), np.asarray(mo_energy) O, V = pair_window(f, occ_tol) n = (f[O][:, None] - f[V][None, :]) / 2 gap = e[V][None, :] - e[O][:, None] live = (n > 0) & (gap > 0) w = np.where(live, np.sqrt(np.where(live, n, 0.0)), 0.0) if bug_helper.host_scratch_dir(): # weight panel by panel into a scratch buffer nO, nV, naux = np.shape(B) Bf, wf = np.asarray(B).reshape(nO * nV, naux), w.reshape(-1) B_w = bug_helper.host_empty((nO * nV, naux), dtype=Bf.dtype) for r0 in range(0, nO * nV, 8192): B_w[r0:r0 + 8192] = Bf[r0:r0 + 8192] * wf[r0:r0 + 8192, None] B_w = B_w.reshape(nO, nV, naux) else: B_w = B * w[..., None] return B_w, -np.where(live, gap, np.abs(gap) + 1.0)
[docs] def rpa_inputs(mf, sigma: float | None = None, method: str = 'fermi', occ_tol: float = 1e-6, frozen: int = 0) -> tuple[Array, Array]: """``(B, eia)`` for :func:`kernel` from a closed-shell PySCF DF mean field. ``frozen`` drops the lowest ``frozen`` orbitals. ``sigma`` (Hartree) and ``method`` (``'fermi'`` or ``'gauss'``) are PySCF's own smearing keywords: given ``sigma``, the SCF is re-run through ``pyscf.scf.addons.smearing`` from ``mf``'s density, so the occupations are self-consistent. An ``mf`` that is already smeared is used as it is. """ from pyscf.scf import addons if sigma is not None: mf = addons.smearing(mf, sigma=sigma, method=method) mf.kernel(mf.make_rdm1() if getattr(mf, 'mo_coeff', None) is not None else None) f, e = np.asarray(mf.mo_occ)[frozen:], np.asarray(mf.mo_energy)[frozen:] C = np.asarray(mf.mo_coeff)[:, frozen:] O, V = pair_window(f, occ_tol) _, B, _ = extract_df_factors(mf, len(O), blocks=("ov",), mo_coeff=np.hstack([C[:, O], C[:, V]])) return weighted_pairs(B, e, f, occ_tol)
[docs] def low_rank_rpa(mf, tau: float = 1e-4, *, frozen: int = 0, occ_tol: float = 1e-6, **kwargs) -> LowRankResult: """Low-rank closed-shell dRPA of a PySCF density-fitted mean field. ``frozen`` drops the lowest orbitals; a Fermi- or Gaussian-smeared ``mf`` is treated with fractional occupations (see :func:`rpa_inputs`). Every other keyword is a solver control of :func:`kernel`, which takes the DF factors directly. """ return kernel(*rpa_inputs(mf, occ_tol=occ_tol, frozen=frozen), tau=tau, **kwargs)