Source code for pytc.solver.test.test_bug_rpa

"""Tests for the low-rank direct-RPA solver.

The core cross-check (``core_sym_eig`` vs an independent Newton-Kleinman
iteration) is the guard that makes changes to the core safe.
"""
import os
import tempfile
import unittest
from functools import lru_cache
from unittest.mock import patch

import numpy as np
from pyscf import gto, scf
from scipy.linalg import solve_sylvester

from pytc.solver.bug_core import extract_df_factors
from pytc.solver.bug_rpa import core_sym_eig, kernel, rpa_inputs

# Stored dRPA correlation energy for the cc-pVDZ water monomer below, in Ha,
# from the frequency-integral form and cross-checked against a dense Casida
# diagonalisation; fcdmft's frequency RPA reproduces it.
E_RPA_H2O_CCPVDZ = -0.2311485476


[docs] @lru_cache(maxsize=1) def _h2o_mf(): """Water/cc-pVDZ DF-RHF shared by the regression inputs.""" mol = gto.M( atom='O 0 0 0; H 0 0.757 0.587; H 0 -0.757 0.587', basis='cc-pvdz', verbose=0) return scf.RHF(mol).density_fit().run()
[docs] @lru_cache(maxsize=1) def _h2o_problem(): """Build the shared water/cc-pVDZ pair-space regression input once.""" mf = _h2o_mf() mol = mf.mol nocc = mol.nelectron // 2 mo_e = np.asarray(mf.mo_energy) eia = mo_e[:nocc, None] - mo_e[None, nocc:] _, B_ov, _ = extract_df_factors(mf, nocc) return B_ov, eia
[docs] def _core_nk_ref(E, Bt, nk=40, conv=1e-13): """Independent Newton-Kleinman reference for E Y + Y E + Y Bt Y + Bt = 0.""" Y = solve_sylvester(E, E, -Bt) Y = (Y + Y.T) / 2 for _ in range(nk): a = E + Y @ Bt b = E + Bt @ Y q = Y @ Bt @ Y - Bt Ynew = solve_sylvester(a, b, q) Ynew = (Ynew + Ynew.T) / 2 if np.linalg.norm(Ynew - Y) < conv: Y = Ynew break Y = Ynew return Y
[docs] def _care_res(T, E, Bt): return np.abs(Bt + E @ T + T @ E + T @ Bt @ T).max()
[docs] class TestLowScalingRPA(unittest.TestCase):
[docs] def test_core_matches_newton_kleinman(self): rng = np.random.default_rng(0) for rc in (80, 200): X_ = rng.standard_normal((rc, rc)) E = X_ @ X_.T / rc + rc * np.eye(rc) Y_ = rng.standard_normal((rc, rc)) * 0.01 Bt = (Y_ + Y_.T) / 2 E = E + 2 * Bt T = np.asarray(core_sym_eig(E, Bt)[0]) Tref = _core_nk_ref(E, Bt) rel = np.abs(T - Tref).max() / max(np.abs(Tref).max(), 1.0) self.assertLess(rel, 1e-10) self.assertLess(_care_res(T, E, Bt), 1e-11) # A-B can remain positive while A+B has a negative mode. The # resulting imaginary Casida frequency is an instability, not a root # that may be clipped into the physical branch. self.assertLess(float(core_sym_eig(np.zeros((1, 1)), -np.ones((1, 1)))[1]), 0)
[docs] def test_h2o_energy_anchor_and_lowrank_gate(self): B_ov, eia = _h2o_problem() res = kernel(B_ov, eia, tau=1e-4) # low-rank vs the stored reference energy within the 1e-4 Ha gate self.assertLess(abs(E_RPA_H2O_CCPVDZ - res.energy), 1e-4) self.assertTrue(res.converged)
[docs] def test_topk_residual_selection(self): # the reduced-width augmentation must stay within the gate and converge B_ov, eia = _h2o_problem() res = kernel(B_ov, eia, tau=1e-4, aug_k=0.35, aug_sel='residual') self.assertLess(abs(E_RPA_H2O_CCPVDZ - res.energy), 1e-4) self.assertTrue(res.converged)
[docs] def test_truncation_rule_is_validated(self): B_ov, eia = _h2o_problem() with self.assertRaises(ValueError): kernel(B_ov, eia, truncation='rank') with self.assertRaises(ValueError): kernel(B_ov, eia, tau=-1e-6, truncation='energy') kernel(B_ov, eia, tau=2.0, truncation='energy', maxiter=1)
[docs] class TestAmplitudeStop(unittest.TestCase):
[docs] def test_amplitude_stop_is_a_true_step_below_conv(self): """At tau=1e-8 a Gram step that cancels to zero at an actual step of 1.1e-9 must not stop the run. The step that stops the run must be the real ||T' - T||, below conv.""" from pytc.solver import bug_core from pytc.solver.bug_rpa import low_rank_rpa mf = scf.RHF(gto.M(atom='H 0 0 0; H 0 0 0.74', basis='sto-3g', verbose=0)).density_fit().run() orig, dense = bug_core.amplitude_step, [] def record(*a, **k): S_new, S, _, Un, Uo = (np.asarray(x) for x in a[:5]) dense.append(np.linalg.norm((Un * S_new) @ Un.T - (Uo * S) @ Uo.T)) return orig(*a, **k) with patch.object(bug_core, 'amplitude_step', record): res = low_rank_rpa(mf, tau=1e-8, conv=1e-10) self.assertEqual(res.stop_reason, 'amplitude-step') self.assertLess(dense[-1], 1e-10)
[docs] class TestResidencies(unittest.TestCase): """Resident and host-backed solves of the same problem, against stored reference results (water/cc-pVDZ).""" CHECKPOINTS = ( # rule, tau, aug_k, energy (Ha), rank ('relative', 1e-4, None, -0.23114854129798545, 79), ('relative', 1e-4, 0.35, -0.23114854129798623, 79), ('absolute', 1e-4, None, -0.2311482555236661, 66), ('energy', 1e-7, None, -0.2311478492991681, 61), )
[docs] def test_both_residencies_reproduce_the_numpy_checkpoints(self): B_ov, eia = _h2o_problem() for rule, tau, aug_k, e_ref, rank in self.CHECKPOINTS: for host_backed in (False, True): with self.subTest(rule=rule, aug_k=aug_k, host_backed=host_backed): res = kernel(B_ov, eia, tau=tau, truncation=rule, aug_k=aug_k, host_backed=host_backed, block_rows=37) self.assertTrue(res.converged) # The energy rule stops on a 1e-7 Ha plateau, so the last # digits depend on the BLAS; 1e-8 is the checkpoints' gate. self.assertLess(abs(res.energy - e_ref), 1e-8) self.assertEqual(res.S.size, rank)
[docs] def test_panel_width_does_not_change_the_answer(self): B_ov, eia = _h2o_problem() ref = kernel(B_ov, eia, tau=1e-4, aug_k=0.35) for block_rows in (1, 7, 95, 4096): with self.subTest(block_rows=block_rows): res = kernel(B_ov, eia, tau=1e-4, aug_k=0.35, host_backed=True, block_rows=block_rows) self.assertLess(abs(res.energy - ref.energy), 1e-12) self.assertEqual(res.rank_hist, ref.rank_hist) self.assertIsInstance(res.U, np.ndarray)
[docs] def test_selection_rule_is_honoured_in_both_residencies(self): B_ov, eia = _h2o_problem() for aug_sel in ('residual', 'amplitude'): with self.subTest(aug_sel=aug_sel): ref = kernel(B_ov, eia, tau=1e-4, aug_k=4, aug_sel=aug_sel, maxiter=3) hb = kernel(B_ov, eia, tau=1e-4, aug_k=4, aug_sel=aug_sel, maxiter=3, host_backed=True, block_rows=37) np.testing.assert_allclose(hb.e_hist, ref.e_hist, rtol=0, atol=1e-12) r = kernel(B_ov, eia, tau=1e-4, aug_k=4, aug_sel='residual', maxiter=3, host_backed=True) a = kernel(B_ov, eia, tau=1e-4, aug_k=4, aug_sel='amplitude', maxiter=3, host_backed=True) self.assertGreater(abs(r.e_hist[-1] - a.e_hist[-1]), 1e-6)
[docs] def test_max_rank_caps_the_basis_in_both_residencies(self): B_ov, eia = _h2o_problem() for host_backed in (False, True): with self.subTest(host_backed=host_backed): res = kernel(B_ov, eia, tau=1e-8, max_rank=20, maxiter=15, host_backed=host_backed, block_rows=37) self.assertLessEqual(max(res.rank_hist), 20) self.assertLessEqual(max(res.diagnostics['aug_rank_hist']), 40)
[docs] def test_analytic_two_level_soft_mode_and_negative_gap(self): # One pair excitation gives a scalar Riccati equation # b t^2 + (delta + 2 b) t + b = 0, # whose stabilizing root approaches -1 as delta -> 0 from above. b = 0.7 B_ov = np.sqrt(b) * np.ones((1, 1, 1)) for delta in (1.0, 1e-2, 1e-8): root = -2 * b / (delta + 2 * b + np.sqrt(delta * (delta + 4 * b))) res = kernel(B_ov, np.array([[-delta]]), tau=1e-12) self.assertTrue(res.converged) self.assertLess(abs(res.S[0] - root), 1e-8) self.assertLess(abs(res.energy - b * root), 1e-8) with self.assertRaisesRegex(RuntimeError, "Cholesky factorization of A-B failed"): kernel(B_ov, np.array([[1e-2]]), tau=1e-12)
[docs] def _disk_backed(a): """True if ``a`` is, or views, an ``np.memmap``.""" while isinstance(a, np.ndarray): if isinstance(a, np.memmap): return True a = a.base return False
[docs] class TestHostScratch(unittest.TestCase): """PYTC_HOST_SCRATCH moves the pair-height host buffers to disk-backed memmaps; the numbers must not change."""
[docs] def setUp(self): self.tmp = tempfile.TemporaryDirectory() self.env = patch.dict(os.environ, {"PYTC_HOST_SCRATCH": self.tmp.name})
[docs] def tearDown(self): self.tmp.cleanup()
[docs] def test_factors_and_host_backed_solve_match_in_core(self): mf = _h2o_mf() B_ref, e_ref = rpa_inputs(mf) ref = kernel(B_ref, e_ref, tau=1e-4, host_backed=True, block_rows=37) with self.env: B, eia = rpa_inputs(mf) self.assertTrue(_disk_backed(B)) self.assertTrue(B.flags["C_CONTIGUOUS"]) np.testing.assert_array_equal(np.asarray(B), np.asarray(B_ref)) np.testing.assert_array_equal(eia, e_ref) res = kernel(B, eia, tau=1e-4, host_backed=True, block_rows=37) self.assertTrue(_disk_backed(res.U)) self.assertLess(abs(res.energy - ref.energy), 1e-12) self.assertEqual(res.S.size, ref.S.size) self.assertEqual(os.listdir(self.tmp.name), []) # files unlinked at creation
[docs] class TestDenseCorePlacement(unittest.TestCase): """``dense_core`` places the core solve and the truncation eigh explicitly: ``"host"`` gives the device energy, and a device out-of-memory error stops the run instead of moving the step."""
[docs] def test_host_core_matches_device(self): B, eia = rpa_inputs(_h2o_mf()) ref = kernel(B, eia, tau=1e-4, host_backed=True, block_rows=37) res = kernel(B, eia, tau=1e-4, host_backed=True, block_rows=37, dense_core="host") self.assertLess(abs(res.energy - ref.energy), 1e-12) self.assertEqual(res.S.size, ref.S.size) self.assertEqual(res.diagnostics["dense_core"], "host")
[docs] def test_device_out_of_memory_stops(self): import jax from pytc.solver import bug_rpa B, eia = rpa_inputs(_h2o_mf()) def oom(E, Bt): raise jax.errors.JaxRuntimeError("RESOURCE_EXHAUSTED: Unable to allocate device workspace") with patch.object(bug_rpa, "core_sym_eig", side_effect=oom), \ self.assertRaisesRegex(MemoryError, "dense_core='host'"): kernel(B, eia, tau=1e-4, host_backed=True, block_rows=37)
[docs] def test_host_core_never_tries_the_device(self): from pytc.solver import bug_rpa B, eia = rpa_inputs(_h2o_mf()) ref = kernel(B, eia, tau=1e-4, host_backed=True, block_rows=37) devices = [] def record(E, Bt): devices.append({d.platform for d in E.devices()}) return core_sym_eig(E, Bt) with patch.object(bug_rpa, "core_sym_eig", side_effect=record): res = kernel(B, eia, tau=1e-4, host_backed=True, block_rows=37, dense_core="host") self.assertTrue(devices) self.assertTrue(all(d == {"cpu"} for d in devices)) self.assertLess(abs(res.energy - ref.energy), 1e-12)
[docs] def test_rejects_unknown_placement(self): B, eia = rpa_inputs(_h2o_mf()) with self.assertRaises(ValueError): kernel(B, eia, dense_core="auto")
[docs] class TestTruncationPlacement(unittest.TestCase):
[docs] def setUp(self): rng = np.random.default_rng(3) A = rng.standard_normal((40, 40)) self.M = A + A.T
[docs] def test_host_eigh_matches_device(self): from pytc.solver import bug_core W0, s0, _ = bug_core.truncate_sym(self.M, 1e-2) W, s, _ = bug_core.truncate_sym(self.M, 1e-2, dense_core="host") np.testing.assert_allclose(np.asarray(s), np.asarray(s0), atol=1e-12) np.testing.assert_allclose(np.abs(np.asarray(W)), np.abs(np.asarray(W0)), atol=1e-10)
[docs] def test_device_out_of_memory_stops(self): import jax from pytc.solver import bug_core def oom(X): raise jax.errors.JaxRuntimeError("RESOURCE_EXHAUSTED: syevBatched workspace") with patch.object(bug_core.jnp.linalg, "eigh", side_effect=oom), \ self.assertRaisesRegex(MemoryError, "truncate_sym eigh"): bug_core.truncate_sym(self.M, 1e-2)
[docs] def test_other_device_errors_propagate(self): import jax from pytc.solver import bug_core def fail(X): raise jax.errors.JaxRuntimeError("INTERNAL: something else") with patch.object(bug_core.jnp.linalg, "eigh", side_effect=fail), \ self.assertRaises(jax.errors.JaxRuntimeError): bug_core.truncate_sym(self.M, 1e-2)
[docs] class TestPrecisionGuard(unittest.TestCase):
[docs] def test_kernel_requires_float64(self): from pytc.solver import bug_rpa from pytc.solver.bug_core import Float64NotEnabled with patch.object(bug_rpa, 'require_float64', side_effect=Float64NotEnabled('x64')): with self.assertRaises(Float64NotEnabled): kernel(np.ones((1, 1, 1)), -np.ones((1, 1)))
[docs] class TestFractionalOccupation(unittest.TestCase): """Smeared references: weighted pairs in the unchanged solver."""
[docs] @classmethod def setUpClass(cls): from pyscf.scf import addons mol = gto.M(atom='O 0 0 0; H 0 0.757 0.587; H 0 -0.757 0.587', basis='cc-pvdz', verbose=0) cls.mf = scf.RHF(mol).density_fit().run() cls.smeared = addons.smearing(cls.mf, sigma=0.1, method='fermi').run()
@staticmethod def _frequency_drpa(smeared, nw=200, w0=0.05, occ_tol=0.0): """Direct integral over every pair p < q with weight (f_p - f_q) / 2, p able to give (f_p > occ_tol) and q able to take (f_q < 2 - occ_tol).""" f, e = smeared.mo_occ, smeared.mo_energy nmo = len(e) L, _, _ = extract_df_factors(smeared, nmo, blocks=("oo",)) p, q = np.triu_indices(nmo, 1) n = (f[p] - f[q]) / 2 keep = (n > 1e-12) & (f[p] > occ_tol) & (f[q] < 2 - occ_tol) B = np.sqrt(n[keep])[:, None] * L[p[keep], q[keep]] d = e[q[keep]] - e[p[keep]] x, wx = np.polynomial.legendre.leggauss(nw) w = w0 * (1 + x) / (1 - x) energy = 0.0 for wi, ji in zip(w, wx * w0 * 2 / (1 - x) ** 2): Bs = B * np.sqrt(4 * d / (wi ** 2 + d ** 2))[:, None] lam = np.linalg.eigvalsh(Bs.T @ Bs) energy += ji * np.sum(np.log1p(lam) - lam) return energy / (2 * np.pi)
[docs] def test_integer_occupations_give_the_ov_problem(self): B, eia = rpa_inputs(self.mf) B_ov, eia_ov = _h2o_problem() np.testing.assert_allclose(eia, eia_ov, rtol=0, atol=1e-12) np.testing.assert_allclose(np.abs(B), np.abs(B_ov), rtol=0, atol=1e-12)
[docs] def test_smeared_energy_matches_direct_frequency_integral(self): self.assertGreater(np.sum((self.smeared.mo_occ > 1e-3) & (self.smeared.mo_occ < 2 - 1e-3)), 1) ref = self._frequency_drpa(self.smeared) # A tight window reproduces every weighted pair; the default 1e-6 window # (fcdmft's threshold) drops only orbitals with f < 1e-6 or f > 2 - 1e-6. for occ_tol, gate in ((1e-10, 1e-9), (1e-6, 1e-7)): B, eia = rpa_inputs(self.smeared, occ_tol=occ_tol) res = kernel(B, eia, tau=1e-8, conv=1e-11) with self.subTest(occ_tol=occ_tol): self.assertTrue(res.converged) self.assertLess(abs(res.energy - ref), gate) # Inside its window every pair counts, as in fcdmft's metal response. self.assertLess(abs(res.energy - self._frequency_drpa(self.smeared, occ_tol=occ_tol)), 1e-9)
[docs] def test_pyscf_smearing_keywords_rerun_the_scf(self): B, eia = rpa_inputs(self.mf, sigma=0.1, method='fermi') B_ref, eia_ref = rpa_inputs(self.smeared) np.testing.assert_allclose(eia, eia_ref, rtol=0, atol=1e-7) np.testing.assert_allclose(np.abs(B), np.abs(B_ref), rtol=0, atol=1e-6)
if __name__ == '__main__': unittest.main()