"""BUG-CCSD against PySCF DF-RCCSD.
The reference for the doubles action is PySCF's DF-RCCSD numerator: at a
state (t1, T) the pair-form ``update_amps`` doubles times the denominator is
the matrix N(t1, T), so ``doubles_action(V)`` must equal ``N V``.
"""
import unittest
from unittest import mock
import jax
jax.config.update("jax_enable_x64", True)
import numpy as np # noqa: E402
from pyscf import cc, gto, scf # noqa: E402
from pytc.solver import bug_ccsd, bug_helper # noqa: E402
WATER = "O 0 0 0; H 0 -0.757 0.587; H 0 0.757 0.587"
[docs]
def _water(basis, atom=WATER):
return scf.RHF(gto.M(atom=atom, basis=basis, verbose=0)).density_fit().run(conv_tol=1e-11)
[docs]
class NumeratorTest(unittest.TestCase):
"""Doubles action, projected core, singles and energy at a random state."""
[docs]
@classmethod
def setUpClass(cls):
mf = _water("6-31g", WATER + "; O 3 0 0; H 3 0.757 0.587; H 3 -0.757 0.587")
frozen = 2
mycc = cc.RCCSD(mf, frozen=frozen)
eris = mycc.ao2mo()
# Canonical HF: the solver uses the exact diagonal Fock matrix.
eris.mo_energy = mf.mo_energy[frozen:]
eris.fock = np.diag(eris.mo_energy)
o, v = mycc.nocc, mycc.nmo - mycc.nocc
rng = np.random.default_rng(3)
rank = 7
U = np.linalg.qr(rng.standard_normal((o * v, rank)))[0]
S = 0.05 * rng.standard_normal(rank)
t1 = 0.01 * rng.standard_normal((o, v))
t2 = ((U * S) @ U.T).reshape(o, v, o, v).transpose(0, 2, 1, 3)
t1_new, t2_new = mycc.update_amps(t1, t2, eris)
eia = eris.mo_energy[:o, None] - eris.mo_energy[None, o:]
eijab = eia[:, None, :, None] + eia[None, :, None, :]
cls.N = (t2_new * eijab).transpose(0, 2, 1, 3).reshape(o * v, o * v)
cls.singles = t1_new * eia
cls.energy = mycc.energy(t1, t2, eris)
cls.t1, cls.U, cls.S = t1, U.reshape(o, v, rank), S
cls.B = bug_ccsd.extract_df_factors(mf, o, mo_coeff=mf.mo_coeff[:, frozen:])
cls.rng = rng
def _cache(self, mode):
return bug_ccsd.build_state(self.t1, self.U, self.S, *self.B,
direct=bug_ccsd.DFDirectBlocks(self.B[1]),
quadratic_mode=mode, quadratic_block=2)
[docs]
def assertClose(self, got, want):
self.assertLess(np.linalg.norm(got - want) / np.linalg.norm(want), 1e-13)
[docs]
def test_doubles_action_matches_pyscf(self):
o, v, _ = self.U.shape
V = self.rng.standard_normal((o, v, 5))
for mode in ("device", "host"):
with self.subTest(mode=mode):
got = bug_ccsd.doubles_action(self.t1, self.U, self.S, V, *self.B, self._cache(mode))
self.assertClose(got, self.N @ V.reshape(o * v, -1))
[docs]
def test_projected_core_matches_pyscf(self):
o, v, rank = self.U.shape
U = self.U.reshape(o * v, rank)
W = self.rng.standard_normal((o * v, 4))
Q = np.linalg.qr(W - U @ (U.T @ W))[0]
got = bug_ccsd.projected_doubles(self.t1, self.U, self.S, Q.reshape(o, v, -1),
*self.B, self._cache("device"))
self.assertClose(got, Q.T @ self.N @ Q)
[docs]
def test_singles_and_energy_match_pyscf(self):
got = bug_ccsd.singles_numerator(self.t1, self.U, self.S, *self.B, self._cache("device"))
self.assertClose(got, self.singles)
self.assertAlmostEqual(bug_ccsd.energy(self.t1, self.U, self.S, self.B[1]),
self.energy, delta=1e-14)
[docs]
class KernelBlockingTest(unittest.TestCase):
[docs]
def test_crossed_amplitude_probe_blocks_match_single_call(self):
rng = np.random.default_rng(12)
U = rng.normal(size=(5, 7, 9))
S = rng.normal(size=9)
V = rng.normal(size=(5, 7, 23))
whole = bug_ccsd.crossed_amplitude_action(U, S, V, rank_block=4, probe_block=64)
blocked = bug_ccsd.crossed_amplitude_action(U, S, V, rank_block=4, probe_block=5)
np.testing.assert_allclose(blocked, whole, rtol=1e-13, atol=1e-13)
[docs]
def test_parked_quadratic_operator_matches_resident(self):
rng = np.random.default_rng(16)
o, v, naux, rank = 7, 5, 9, 6
B = rng.normal(size=(o, v, naux))
U = np.linalg.qr(rng.normal(size=(o * v, rank)))[0].reshape(o, v, rank)
S = rng.normal(size=rank)
t1 = 0.1 * rng.normal(size=(o, v))
direct = np.einsum("kcP,ldP->kcld", B, B)
M = rng.normal(size=(o * v, 4))
want = bug_ccsd.QuadraticOperator(t1, U, S, direct, block=7) @ M
for resident in (False, True):
op = bug_ccsd.QuadraticOperator(t1, U, S, direct, block=3, apply_rows=4,
resident=resident)
np.testing.assert_allclose(op @ M, want, rtol=1e-12, atol=1e-12 * np.abs(want).max())
[docs]
class SolverTest(unittest.TestCase):
OPTIONS = dict(tau=3e-3, maxiter=5, energy_plateau_tolerance=1e-14, damp=1.0,
aug_precond="jacobi", aug_warmup=True, aug_sel="svd", aug_k=4)
[docs]
@classmethod
def setUpClass(cls):
cls.mf = _water("cc-pvdz")
[docs]
def test_frozen_core_matches_pyscf_at_full_rank(self):
mf = _water("6-31g")
ref = cc.CCSD(mf, frozen=1)
ref.conv_tol = 1e-10
ref.kernel()
out = bug_ccsd.low_rank_ccsd(mf, tau=1e-8, maxiter=80, energy_plateau_tolerance=1e-11,
frozen=1, quadratic_block=2)
self.assertEqual(out.U.shape[:2], (4, 8))
self.assertAlmostEqual(out.energy, ref.e_corr, delta=5e-8)
[docs]
def test_projected_remeasurement_matches_full_action(self):
# The solver's Q^T N Q comes from the projected kernels; the full action
# on Q gives the same Galerkin core.
calls = []
full = bug_ccsd.projected_doubles
def via_full_action(t1, U, S, Q, B_oo, B_ov, B_vv, cache, **_):
o, v, k = Q.shape
nQ = bug_ccsd.doubles_action(t1, U, S, Q, B_oo, B_ov, B_vv, cache)
got = full(t1, U, S, Q, B_oo, B_ov, B_vv, cache)
calls.append(np.abs(got - Q.reshape(o * v, k).T @ nQ).max() / np.abs(got).max())
return got
with mock.patch.object(bug_ccsd, "projected_doubles", via_full_action):
bug_ccsd.low_rank_ccsd(self.mf, **self.OPTIONS)
self.assertTrue(calls)
self.assertLess(max(calls), 1e-12)
[docs]
def test_host_parked_operator_reproduces_device_trajectory(self):
runs = {mode: bug_ccsd.low_rank_ccsd(self.mf, quadratic_mode=mode, quadratic_block=2,
**self.OPTIONS)
for mode in ("device", "host")}
np.testing.assert_allclose(runs["host"].e_hist, runs["device"].e_hist,
rtol=0, atol=1e-12)
self.assertEqual(runs["host"].rank_hist, runs["device"].rank_hist)
[docs]
def test_host_dense_core_reproduces_device_trajectory(self):
runs = {where: bug_ccsd.low_rank_ccsd(self.mf, dense_core=where, **self.OPTIONS)
for where in ("device", "host")}
np.testing.assert_allclose(runs["host"].e_hist, runs["device"].e_hist,
rtol=0, atol=1e-12)
self.assertEqual(runs["host"].rank_hist, runs["device"].rank_hist)
self.assertEqual(runs["host"].diagnostics["dense_core"], "host")
[docs]
def test_streamed_df_factors_reproduce_resident_trajectory(self):
resident = bug_ccsd.low_rank_ccsd(self.mf, **self.OPTIONS)
# Only B_vv exceeds the limit: 19^2 * naux doubles against B_ov's 5*19*naux.
limit = 8 * 5 * 19 * 100 * 1.5
with mock.patch.object(bug_helper, "RESIDENT_LIMIT_BYTES", limit), \
mock.patch.object(bug_helper, "AUX_CHUNK_BYTES", 8 * 19 * 19 * 7):
bug_helper.release_device_copies()
copies = []
streamed = bug_ccsd.low_rank_ccsd(
self.mf, **self.OPTIONS,
callback=lambda info: copies.append(len(bug_helper._HOST_CHUNKS)))
# One host copy of B_vv shared by every consumer, whatever width each streams it at.
self.assertEqual(set(copies), {1})
np.testing.assert_allclose(streamed.e_hist, resident.e_hist, rtol=0, atol=1e-10)
self.assertEqual(streamed.rank_hist, resident.rank_hist)
[docs]
def test_restart_from_callback_state_continues_the_trajectory(self):
"""A run checkpointed through the callback's (U, S, t1) and restarted through
``init`` reproduces the uninterrupted run (no warm-up: it is per-run state)."""
opts = dict(self.OPTIONS, aug_warmup=False, maxiter=6)
full = bug_ccsd.low_rank_ccsd(self.mf, **opts)
saved = {}
def keep(info):
if info["iteration"] == 2:
saved["state"] = tuple(np.array(x, copy=True) for x in info["state"])
bug_ccsd.low_rank_ccsd(self.mf, **dict(opts, maxiter=3), callback=keep)
rest = bug_ccsd.low_rank_ccsd(self.mf, **dict(opts, maxiter=3), init=saved["state"])
np.testing.assert_allclose(rest.e_hist, full.e_hist[3:6], rtol=0, atol=1e-12)
self.assertEqual(rest.rank_hist, full.rank_hist[3:6])
[docs]
def test_device_cache_is_released_when_setup_fails(self):
"""The warm start runs after B_ov is cached on the device; a failure
there must not leave the factor behind."""
from unittest import mock
bug_helper.release_device_copies()
with mock.patch.object(bug_ccsd, "mp2_start", side_effect=RuntimeError("boom")):
with self.assertRaises(RuntimeError):
bug_ccsd.low_rank_ccsd(self.mf, **self.OPTIONS)
self.assertEqual(len(bug_helper._ON_DEVICE), 0)
[docs]
def test_device_cache_does_not_grow_per_iteration(self):
sizes = []
bug_ccsd.low_rank_ccsd(self.mf, quadratic_mode="host",
callback=lambda info: sizes.append(len(bug_helper._ON_DEVICE)),
**self.OPTIONS)
self.assertEqual(len(set(sizes)), 1, sizes)
if __name__ == "__main__":
unittest.main()