Source code for pytc.solver.bug_core

"""Shared machinery of the basis-update & Galerkin (BUG) low-rank solvers.

The result type, the stopping rule, truncation of the Galerkin core, DF factor
extraction, and the device kernels of the augment--Galerkin--truncate loop:
blocked products, row panels streamed from host memory, orthogonalisation and
counted host<->device transfers.  The dependency runs one way only:
methods -> bug_core.  Nothing here imports from the individual solvers.
"""
from __future__ import annotations

from dataclasses import dataclass, field
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 pytc.solver import bug_helper
from numpy.typing import NDArray

Array = NDArray[np.generic]


#: Why a BUG solve stopped.
StopReason = Literal['amplitude-step', 'energy-plateau', 'maxiter']


[docs] @dataclass class LowRankResult: """What every BUG solver returns. The doubles amplitude is ``T = U diag(S) U^T`` in the pair space (``U`` shaped ``(nocc, nvir, rank)`` or ``(nov, rank)`` as the solver keeps it). ``energy`` is the correlation energy, ``None`` only for amplitude-only building blocks. ``diagnostics`` holds the solver-specific detail (timings, augmentation widths, memory plan, ...). """ energy: float | None U: Any S: Any iterations: int converged: bool stop_reason: StopReason rank_hist: list[int] = field(default_factory=list) e_hist: list[float] = field(default_factory=list) t1: Any = None diagnostics: Any = None
[docs] class Float64NotEnabled(RuntimeError): """Raised when JAX is not in x64 mode: a float32 run agrees with any reference to ~1e-7, which looks like success rather than an error."""
[docs] def require_float64() -> bool: """Fail closed unless JAX actually produces float64 (``JAX_ENABLE_X64=1``).""" if jnp.zeros(1, dtype=jnp.float64).dtype != jnp.float64: raise Float64NotEnabled( "jax_enable_x64 is not in effect; set JAX_ENABLE_X64=1 before importing jax") return True
[docs] def extract_df_factors(mf, nocc, blocks=("oo", "ov", "vv"), mo_coeff=None): """PySCF DF 3-index MO factors ``B[p,q,Q]`` for the oo, ov and vv blocks. Returns ``(B_oo (o,o,naux), B_ov (o,v,naux), B_vv (v,v,naux))``; blocks not listed in ``blocks`` come back as ``None`` (B_vv is by far the largest, so a caller that needs only ov should say so). With ``PYTC_HOST_SCRATCH`` set, every block is built and returned in disk-backed :func:`bug_helper.host_empty` buffers, contiguous as ``(p, q, naux)``. """ from pyscf.ao2mo import _ao2mo mo = np.asarray(mf.mo_coeff if mo_coeff is None else mo_coeff, dtype=np.float64, order="F") nmo = mo.shape[1] with_df = mf.with_df naux = with_df.get_naoaux() scratch = bug_helper.host_scratch_dir() def _block(p0, p1, q0, q1): npq = (p1 - p0) * (q1 - q0) L = bug_helper.host_empty((naux, npq)) start = 0 for eri1 in with_df.loop(): block = _ao2mo.nr_e2(eri1, mo, (p0, p1, q0, q1), aosym="s2", mosym="s1", out=None) block = np.asarray(block, dtype=np.float64).reshape(-1, npq) L[start:start + block.shape[0]] = block start += block.shape[0] if not scratch: return L.reshape(naux, p1 - p0, q1 - q0).transpose(1, 2, 0) # PYTC_HOST_SCRATCH: transpose in row panels into a contiguous # (pq, naux) scratch buffer -- the layout every panel kernel reads. out = bug_helper.host_empty((npq, naux)) for r0 in range(0, npq, 8192): out[r0:r0 + 8192] = np.asarray(L[:, r0:r0 + 8192]).T del L return out.reshape(p1 - p0, q1 - q0, naux) B_oo = _block(0, nocc, 0, nocc) if "oo" in blocks else None B_ov = _block(0, nocc, nocc, nmo) if "ov" in blocks else None B_vv = _block(nocc, nmo, nocc, nmo) if "vv" in blocks else None return B_oo, B_ov, B_vv
# -------------------------------------------------------------------------- # Stopping: one rule for every BUG solver # -------------------------------------------------------------------------- @partial(jax.jit, donate_argnums=0) def _residual_gram_accum(H, Uo, Un, C): E = Uo - Un @ C return H + E.T @ E
[docs] def amplitude_step(S_new, S, cross, U_new, U_old, *, conv, amplitude_tol=None, scale=None, block_rows=8192): """``(||U' diag(S') U'^T - U diag(S) U^T||_F, valid)`` with ``cross = U'^T U``. The rank-sized Gram form ``S'.S' + S.S - 2 S'(C*C)S`` is a difference of ``O(||T||^2)`` terms, so it resolves a step only down to ``~sqrt(eps)||T||``. It decides the step when it is clearly above every stop threshold. Otherwise the step is recomputed without cancellation from the part of the old basis outside the new one, ``E = U - U' C`` with ``H = E^T E`` (row panels, rank-sized result): ``||K||^2 + 2 tr((CS)^T (CS) H) + sum_ij S_i S_j H_ij^2``, where ``CS = C diag(S)`` and ``K = diag(S') - CS C^T``. Every term is nonnegative, so that form is always valid. Ranks may differ. """ S_new = np.asarray(S_new, dtype=np.float64) S = np.asarray(S, dtype=np.float64) C = np.asarray(cross, dtype=np.float64) g = float(S_new @ S_new + S @ S - 2.0 * S_new @ ((C * C) @ S)) hi = max(conv, 0.0 if amplitude_tol is None else amplitude_tol * scale) if g - 1e3 * np.finfo(np.float64).eps * float(S_new @ S_new + S @ S) >= hi * hi: return float(np.sqrt(g)), True dev = lambda a: bug_helper.put_counted(a) if isinstance(a, np.ndarray) else a Cd = jnp.asarray(C) H = jnp.zeros((S.size, S.size), dtype=Cd.dtype) for s0 in range(0, U_old.shape[0], block_rows): H = _residual_gram_accum(H, dev(U_old[s0:s0 + block_rows]), dev(U_new[s0:s0 + block_rows]), Cd) H = np.asarray(bug_helper.get_counted(H)) CS = C * S[None, :] K = np.diag(S_new) - CS @ C.T step2 = float(np.sum(K * K) + 2.0 * np.sum((CS.T @ CS) * H) + S @ (H * H) @ S) return float(np.sqrt(step2)), True
[docs] def plateau_tol(truncation: str, tau: float, energy: float) -> float: """Energy change below which the iteration has settled under the cut. An energy cutoff is already in Hartree; an amplitude cutoff ``tau`` bounds a relative energy error of order ``tau**2``. Neither can go below the roundoff of the energy itself, or a tight ``tau`` never stops. That energy is a sum of ``rank**2`` terms; its iteration-to-iteration noise is ~1e-14 relative on one BLAS and several times that on another, so the floor is 1e-13. """ floor = 1e-13 * max(abs(energy), 1e-3) if truncation == 'energy': return max(tau, floor) return max(tau * tau * max(abs(energy), 1e-3), floor)
[docs] def energy_plateau(e_hist, tol: float, window: int = 3) -> bool: """The last ``window`` energy changes are all below ``tol``.""" return len(e_hist) > window and max( abs(e_hist[-1 - i] - e_hist[-2 - i]) for i in range(window)) < tol
[docs] def check_stop(step: float, scale: float, valid: bool, e_hist, tol: float, *, conv: float, amplitude_tol: float | None = None): """The stop rule of every BUG solver; returns the reason, or ``None`` to go on. ``step`` is ``||T' - T||`` (for CCSD also ``+ ||t1' - t1||``), ``scale`` the matching amplitude norm, and ``valid`` is ``False`` when the step came from a roundoff-negative Gram difference. The run stops on ``step < conv`` (``'amplitude-step'``) or on the energy settling below ``tol`` over three iterations (``'energy-plateau'``); ``amplitude_tol``, when given, additionally requires ``step < amplitude_tol * scale`` for either route. """ amp_ok = amplitude_tol is None or (valid and step < amplitude_tol * scale) if valid and step < conv and amp_ok: return 'amplitude-step' if amp_ok and energy_plateau(e_hist, tol): return 'energy-plateau' return None
# -------------------------------------------------------------------------- # Truncation (returns the isometry, not just the retained factor) # --------------------------------------------------------------------------
[docs] @dataclass(frozen=True) class TruncInfo: lam_max: float kept: int #: sum_i e_i over the discarded modes, the first-order energy the cut #: removes; None without an energy metric. discarded_energy: float | None = None
[docs] def sylvester(A, G): """Solve ``A X + X A = G`` for symmetric ``A`` via the symmetric eig route.""" lam, V = jnp.linalg.eigh(A) X = V @ ((V.T @ G @ V) / (lam[:, None] + lam[None, :])) @ V.T return (X + X.T) / 2
[docs] def requested_aug_width(rank: int, nocc: int, nvir: int, *, aug_k: float | None, max_rank: int | None = None) -> int: """Columns the augmentation selector will ask for at this rank. A fraction ``aug_k < 1`` has the floor ``2(nocc+nvir)``, which can exceed the fraction; an integer is a count. """ r0 = int(rank) if aug_k is None: requested = r0 # no fraction requested; the cap may still bind elif aug_k < 1: requested = min(max(round(aug_k * r0), 2 * (int(nocc) + int(nvir))), r0) else: requested = min(int(aug_k), r0) if max_rank is not None: requested = min(requested, max(int(max_rank) - r0, 0)) return int(requested)
DenseCore = Literal["device", "host"]
[docs] def run_dense(name: str, fn, *args, dense_core: DenseCore = "device"): """``fn(*args)`` for a dense core step, on the device or on the host CPU as chosen. Dense core steps (eigh of the n x n Galerkin core and the RPA Cholesky-Casida solve) need several n^2 arrays plus solver workspace, which can exceed the device memory. The caller picks where they run. ``"device"`` stops with a :class:`MemoryError` when the device runs out of memory instead of moving the step elsewhere. """ if dense_core == "host": host = [np.asarray(a) for a in args] with jax.default_device(jax.devices("cpu")[0]): out = jax.tree_util.tree_map(np.asarray, fn(*[jnp.asarray(a) for a in host])) return jax.tree_util.tree_map(jnp.asarray, out) if dense_core != "device": raise ValueError(f"dense_core must be 'device' or 'host', not {dense_core!r}") try: return jax.block_until_ready(fn(*args)) except jax.errors.JaxRuntimeError as exc: if "RESOURCE_EXHAUSTED" not in str(exc): raise raise MemoryError(f"{name}: device out of memory at shape {np.shape(args[0])}; " "rerun with dense_core='host'") from exc
[docs] def truncate_sym(M, tau: float, rmin: int = 1, max_rank: int | None = None, rule: str = 'relative', energy_metric=None, dense_core: DenseCore = "device"): """Tolerance-truncate a symmetric core ``M``. ``rule`` sets what ``tau`` bounds: ``'relative'`` keeps ``|s| > tau*max|s|``, ``'absolute'`` keeps ``|s| > tau``, and ``'energy'`` keeps the modes whose energy share ``|e_i|`` exceeds ``tau`` (Hartree), where ``e_i = s_i w_i^T G w_i`` for ``G = energy_metric`` so that the energy is ``sum_i e_i``. An absolute cut is the same in every system, so its error is extensive and cancels in energy differences; a relative one moves with each system's largest amplitude. ``dense_core`` picks where the eigendecomposition runs (:func:`run_dense`). Returns ``(W, s, info)``: the retained eigenvectors (the caller forms ``U_new = U_aug @ W``), the retained eigenvalues, and :class:`TruncInfo`. """ lam, Q = run_dense("truncate_sym eigh", jnp.linalg.eigh, M, dense_core=dense_core) e = None if energy_metric is None else lam * jnp.sum(Q * (energy_metric @ Q), axis=0) order, r = rank_cut(lam, tau, rule, e, rmin=rmin, max_rank=max_rank) sel = order[:r] dropped = None if e is None else float(jnp.sum(e[order[r:]])) return Q[:, sel], lam[sel], TruncInfo(lam_max=float(jnp.abs(lam).max()), kept=r, discarded_energy=dropped)
[docs] def rank_cut(lam, tau: float, rule: str = 'relative', e=None, rmin: int = 1, max_rank: int | None = None): """``(order, r)``: core modes by decreasing weight and how many ``rule`` keeps. The weight is ``|lam|`` (cut at ``tau * max|lam|`` or ``tau``) or, for ``'energy'``, the energy share ``|e|`` (cut at ``tau``); see :func:`truncate_sym`. """ if rule == 'energy': if e is None: raise ValueError("the energy rule needs the per-mode energies (energy_metric)") weight, cut = jnp.abs(e), tau elif rule in ('relative', 'absolute'): weight = jnp.abs(jnp.asarray(lam)) cut = tau * float(weight.max()) if rule == 'relative' else tau else: raise ValueError("rule must be 'relative', 'absolute' or 'energy'") order = jnp.argsort(-weight) r = max(rmin, int((weight > cut).sum())) return order, (r if max_rank is None else min(r, max_rank))
# -------------------------------------------------------------------------- # Device kernels: blocked products, row panels streamed from host memory, # orthogonalisation, and counted host<->device transfers # -------------------------------------------------------------------------- @jax.jit def _project_residual(U: Any, D: Any) -> Any: W = D - U @ (U.T @ D) return W - U @ (U.T @ W)
[docs] def project_directions(U, D, *, frac=None, kmin=None, kabs=None, how="residual"): """Project and optionally select augmentation directions once. ``how`` is ``'residual'`` (largest projected-residual norms), ``'top'`` (leading columns, amplitude ordering) or ``'svd'`` (leading left singular vectors of the projected residual). Residual selection ranks columns by the already-projected block. Returning those projected columns lets the following QR consume them directly; the previous path discarded this block, gathered the unprojected columns, and repeated the same two large Gram--Schmidt passes. """ r = U.shape[1] if kabs is not None: k = min(int(kabs), r) elif frac is not None: k = max(round(float(frac) * r), int(kmin or 0)) k = min(k, r) else: return _project_residual(U, D) if how == "top": return _project_residual(U, D[:, :k]) W = _project_residual(U, D) if k == D.shape[1]: return W if how == "svd": # The best rank-k capture of the external residual, scaled by its singular # values: unit vectors would hide a residual that is pure roundoff (a # basis that already spans the pair space) from orth_directions' drop rule. u, sv, _ = jnp.linalg.svd(W, full_matrices=False) return u[:, :k] * sv[None, :k] sel = jnp.sort(jnp.argsort(-jnp.linalg.norm(W, axis=0))[:k]) return W[:, sel]
@jax.jit def _pivoted_qr(W): Q, R, _ = jsp_linalg.qr(W, mode="economic", pivoting=True) return Q, jnp.abs(jnp.diag(R)) _tall_qr = jax.jit(lambda W: jnp.linalg.qr(W, mode="reduced")) _tall_qr_donated = jax.jit(lambda W: jnp.linalg.qr(W, mode="reduced"), donate_argnums=(0,)) @partial(jax.jit, donate_argnums=(0,)) def _hostbacked_update(cross, Up, Qp, Wu, Wq): """One panel of U_new = Ur Wu + Qa Wq, and its contribution to U_new^T Ur. The cross is accumulated here rather than in a second traversal: it is the only consumer of U_new that the iteration has, and re-reading a host-backed U_new to form an r x r matrix would double the transfer for no benefit. """ Unew_p = Up @ Wu + Qp @ Wq return cross + Unew_p.T @ Up, Unew_p
[docs] def hostbacked_basis_update(U_host: Any, Qa_host: Any, Wu: Any, Wq: Any, *, block_rows: int, trace_sink: list | None = None, out: Any = None): """Updated basis written to the HOST, with the cross accumulated in flight. Returns ``(U_new_host, cross)``. ``U_new`` never exists on the device at full height, and the ``r x r`` cross comes back on the device where the caller needs it. ``out`` optionally supplies a caller-owned contiguous destination, so the basis buffer can be reused across iterations instead of re-faulted every call. ``out=None`` allocates a new array. """ Um = np.asarray(U_host); Qm = np.asarray(Qa_host) nov = Um.shape[0] Um = Um.reshape(nov, -1); Qm = Qm.reshape(nov, -1) # Wu.shape is static metadata; reading it needs no transfer. r_new = int(Wu.shape[1]) r0 = Um.shape[1] panel = int(min(nov, max(1, block_rows))) step = _hostbacked_update cross = jnp.zeros((r_new, r0), dtype=Um.dtype) if out is None: out = bug_helper.host_empty((nov, r_new), dtype=Um.dtype) elif (out.shape != (nov, r_new) or out.dtype != Um.dtype or not out.flags['C_CONTIGUOUS']): raise ValueError( f"out is {out.shape} {out.dtype} " f"contiguous={out.flags['C_CONTIGUOUS']}, need " f"{(nov, r_new)} {Um.dtype} contiguous") elif np.shares_memory(out, Um) or np.shares_memory(out, Qm): raise ValueError("out aliases a live input -- ping-pong the buffers") for i, s0 in enumerate(range(0, nov, panel)): e0 = min(s0 + panel, nov) Up = bug_helper.put_counted(Um[s0:e0]) Qp = bug_helper.put_counted(Qm[s0:e0]) cross, Unew_p = step(cross, Up, Qp, Wu, Wq) out[s0:e0] = bug_helper.get_counted(Unew_p) jax.block_until_ready(cross) Up.delete(); Qp.delete(); del Unew_p if trace_sink is not None: trace_sink.append(('hb-update', i, bug_helper._live_bytes())) return out, cross
[docs] def orth_directions(W, rel_tol=1e-10, *, donate=False): """Rank-revealing QR of projected directions, optionally consuming ``W``. The RPA iteration never reads the residual block after this call. Donating it lets XLA reuse that device buffer for the equally shaped Q factor rather than holding both multi-GB arrays through the factorization. Pivoting the full tall matrix serializes column-norm updates and is slow. First reduce ``W = Q R`` with the accelerator's unpivoted tall QR, then pivot only the small square ``R``. Orthogonality of Q makes the second factorization rank-equivalent to pivoting W itself. When every direction survives (the common case), Q already spans the required subspace and no large post-rotation is needed. """ Q, R = (_tall_qr_donated if donate else _tall_qr)(W) Qr, diag_dev = _pivoted_qr(R) diag = np.asarray(jax.device_get(diag_dev)) empty = jnp.zeros((W.shape[0], 0), dtype=W.dtype) if diag.size == 0: return empty keep = diag > rel_tol * max(1.0, float(diag.max())) if not keep.any(): return empty if keep.all(): return Q return Q @ Qr[:, keep]