Source code for pytc.solver.test.test_bug_mp2_hostbacked

"""Host-backed BUG-MP2 against the resident path and the dense definition.

Host-backed is the same arithmetic with a different residency, so every check
is against the resident path or the definition.  Panel sizes include values
that leave non-divisible tails.
"""
import unittest

import numpy as np

from pytc.solver import bug_helper


[docs] def _fixture(o=4, v=6, n_mu=9, naux=5, seed=0): """A random low-rank DF factor and denominators.""" rng = np.random.default_rng(seed) Xo = rng.standard_normal((n_mu, o)) Xv = rng.standard_normal((n_mu, v)) W = rng.standard_normal((n_mu, naux)) Xf = np.einsum('mi,ma->iam', Xo, Xv).reshape(o * v, n_mu) B_ov = 0.3 * (Xf @ W).reshape(o, v, naux) eia = -(np.linspace(0.9, 2.4, o * v).reshape(o, v)) return Xo, Xv, B_ov, eia
[docs] def _amp(U, S): A = np.asarray(U).reshape(-1, len(S)) return A @ np.diag(S) @ A.T
[docs] class TestHostBackedMP2(unittest.TestCase):
[docs] def test_df_host_backed_matches_resident(self): from pytc.solver import bug_mp2 as m _, _, B_ov, eia = _fixture() ref = m.kernel(B_ov, eia, tau=1e-8, maxiter=40, seed=0) for block_rows, col_block in ((5, 2), (7, 3), (24, 64)): with self.subTest(block_rows=block_rows, col_block=col_block): res = m.kernel_host_backed(B_ov, eia, tau=1e-8, maxiter=40, seed=0, block_rows=block_rows, col_block=col_block) self.assertLess(abs(res.energy - ref.energy), 1e-9 * max(1.0, abs(ref.energy))) self.assertLess(np.abs(_amp(res.U, res.S) - _amp(ref.U, ref.S)).max(), 1e-8)
[docs] def test_host_backed_matches_exact_mp2(self): """Against the definition, not just the other implementation.""" from pytc.solver import bug_mp2 as m _, _, B_ov, eia = _fixture() o, v, _ = B_ov.shape ovov = np.einsum('iaQ,jbQ->iajb', B_ov, B_ov) denom = eia[:, :, None, None] + eia[None, None, :, :] t2 = ovov / denom e_exact = float(np.sum(t2 * (2 * ovov - ovov.transpose(0, 3, 2, 1)))) e = m.kernel_host_backed(B_ov, eia, tau=1e-10, maxiter=60, seed=0, block_rows=5, col_block=2).energy self.assertLess(abs(e - e_exact), 1e-9 * max(1.0, abs(e_exact)))
[docs] def test_converged_solution_does_not_drift(self): """Extra iterations past convergence must not move the energy.""" from pytc.solver import bug_mp2 as m _, _, B_ov, eia = _fixture() e2 = m.kernel_host_backed(B_ov, eia, tau=1e-8, maxiter=2, seed=0, block_rows=5, col_block=2).energy e8 = m.kernel_host_backed(B_ov, eia, tau=1e-8, maxiter=8, seed=0, block_rows=5, col_block=2).energy self.assertLess(abs(e8 - e2), 1e-9 * max(1.0, abs(e2)))
[docs] def test_iteration_count_is_recorded_and_paths_agree(self): from pytc.solver import bug_mp2 as m _, _, B_ov, eia = _fixture() ir = m.kernel(B_ov, eia, tau=1e-8, maxiter=40, seed=0) ih = m.kernel_host_backed(B_ov, eia, tau=1e-8, maxiter=40, seed=0, block_rows=5, col_block=2) for res in (ir, ih): self.assertTrue(res.converged) self.assertEqual(len(res.rank_hist), res.iterations) self.assertLess(res.iterations, 40) # The paths orthogonalise differently, so where the exact step crosses # conv can differ by an iteration or two across BLAS builds; the answer must not. self.assertLess(abs(ir.energy - ih.energy), 1e-10 * abs(ir.energy))
[docs] def test_iteration_count_reports_an_unconverged_stop(self): """A maxiter stop must say so, and count exactly the iterations run.""" from pytc.solver import bug_mp2 as m _, _, B_ov, eia = _fixture() for fn, kw in ((m.kernel, {}), (m.kernel_host_backed, dict(block_rows=5, col_block=2))): with self.subTest(fn=fn.__name__): res = fn(B_ov, eia, tau=1e-14, maxiter=1, seed=0, **kw) self.assertEqual(res.iterations, 1) self.assertFalse(res.converged) self.assertEqual(res.stop_reason, 'maxiter')
[docs] def test_unified_stop_agrees_across_paths_and_is_accurate(self): """A decaying spectrum at a tight tau: both residencies stop on the shared rule and reach exact MP2. Their orthogonalisations differ, so the last steps differ (resolved exactly, not at the Gram roundoff) and the two may stop one iteration apart on different routes.""" from pytc.solver import bug_mp2 as m rng = np.random.default_rng(0) o, v, naux = 6, 20, 40 B_ov = rng.standard_normal((o, v, naux)) * (0.3 * 0.8 ** np.arange(naux)) eia = -np.linspace(0.5, 1.5, o)[:, None] - np.linspace(0.2, 6.0, v)[None, :] ovov = np.einsum('iaQ,jbQ->iajb', B_ov, B_ov) denom = eia[:, :, None, None] + eia[None, None, :, :] e_exact = float(np.sum(ovov / denom * (2 * ovov - ovov.transpose(0, 3, 2, 1)))) runs = {'resident': m.kernel(B_ov, eia, tau=1e-6, seed=0), 'hostbacked': m.kernel_host_backed(B_ov, eia, tau=1e-6, seed=0, block_rows=37, col_block=16, )} for name, res in runs.items(): with self.subTest(path=name): self.assertTrue(res.converged) self.assertIn(res.stop_reason, ('amplitude-step', 'energy-plateau')) self.assertLess(abs(res.energy - e_exact), 1e-6 * abs(e_exact)) self.assertLessEqual(abs(runs['resident'].iterations - runs['hostbacked'].iterations), 1) self.assertLess(abs(runs['resident'].energy - runs['hostbacked'].energy), 1e-9 * abs(e_exact))
[docs] def test_narrow_augmentation_matches_across_paths_and_exact_mp2(self): """aug_k < 1 adds a fraction of r per iteration instead of ~r -- the per-iteration cost lever. Both paths must take the same iterations and ranks, and still reach exact MP2.""" from pytc.solver import bug_mp2 as m rng = np.random.default_rng(1) o, v, naux = 4, 40, 60 B_ov = rng.standard_normal((o, v, naux)) * (0.3 * 0.9 ** np.arange(naux)) eia = -np.linspace(0.5, 1.5, o)[:, None] - np.linspace(0.2, 6.0, v)[None, :] ovov = np.einsum('iaQ,jbQ->iajb', B_ov, B_ov) denom = eia[:, :, None, None] + eia[None, None, :, :] e_exact = float(np.sum(ovov / denom * (2 * ovov - ovov.transpose(0, 3, 2, 1)))) kw = dict(tau=1e-8, maxiter=80, seed=0, aug_k=0.25) ir = m.kernel(B_ov, eia, **kw) ih = m.kernel_host_backed(B_ov, eia, block_rows=37, col_block=16, **kw) aug_r = ir.diagnostics['aug_rank_history'] k_floor = 2 * (o + v) # the fraction must actually bind somewhere, or this tests nothing new self.assertTrue(any(a - r < r for r, a in zip([8] + ir.rank_hist[:-1], aug_r))) self.assertGreater(ir.rank_hist[-1], k_floor) for res in (ir, ih): self.assertTrue(res.converged) self.assertEqual(ir.rank_hist, ih.rank_hist) self.assertEqual(aug_r, ih.diagnostics['aug_rank_history']) self.assertLess(abs(ih.energy - ir.energy), 1e-9 * abs(ir.energy)) self.assertLess(abs(ir.energy - e_exact), 1e-6 * abs(e_exact))
[docs] def test_kept_rank_never_exceeds_the_pair_dimension(self): """A basis cannot have more independent columns than the space has dimensions. The Gram cut is on SQUARED singular values, so a threshold of rel_tol^2 alone lands on machine epsilon and keeps dependent columns: this reported rank 188 in a 160-dimensional space until the eigenvalue floor was added. Saturate the space and check the invariant.""" from pytc.solver import bug_mp2 as m rng = np.random.default_rng(1) o, v, naux = 4, 40, 60 nov = o * v B_ov = rng.standard_normal((o, v, naux)) * (0.3 * 0.9 ** np.arange(naux)) eia = -np.linspace(0.5, 1.5, o)[:, None] - np.linspace(0.2, 6.0, v)[None, :] res = m.kernel_host_backed(B_ov, eia, tau=1e-10, maxiter=40, seed=0, aug_k=0.25, block_rows=37, col_block=16) self.assertLessEqual(max(res.rank_hist), nov) self.assertLessEqual(max(res.diagnostics['aug_rank_history']), nov) self.assertLessEqual(len(res.S), nov)
[docs] def test_no_basis_height_array_is_sent_whole(self): """Every transfer is a row panel or a column chunk, never the basis. Instruments the real transfer point, so any future code that sends ``U`` (or the residual block, or ``Qa``) in one piece fails here. """ from pytc.solver import bug_core, bug_mp2 as m _, _, B_ov, eia = _fixture() o, v, naux = B_ov.shape nov = o * v panel, col_block = 5, 2 sizes = [] real_put = bug_helper.put_counted def spy(a): sizes.append(np.asarray(a).shape) return real_put(a) bug_helper.put_counted = spy try: S = m.kernel_host_backed(B_ov, eia, tau=1e-8, maxiter=40, seed=0, block_rows=panel, col_block=col_block).S finally: bug_helper.put_counted = real_put r = len(S) self.assertGreater(r, col_block, "fixture too small to test chunking") self.assertTrue(sizes, "no transfers observed at all") for shp in sizes: rows = shp[0] if len(shp) else 1 cols = int(np.prod(shp[1:])) if len(shp) > 1 else 1 with self.subTest(shape=shp): # a row panel, or a column chunk of at most col_block columns is_panel = rows <= panel is_chunk = (len(shp) == 3 and shp[:2] == (o, v) and shp[2] <= col_block) is_small = int(np.prod(shp)) <= max(naux, r) ** 2 self.assertTrue(is_panel or is_chunk or is_small, shp)
[docs] def test_selection_rule_matches_the_resident_path(self): from pytc.solver import bug_mp2 as m rng = np.random.default_rng(1) o, v, naux = 4, 40, 60 B_ov = rng.standard_normal((o, v, naux)) * (0.3 * 0.9 ** np.arange(naux)) eia = -np.linspace(0.5, 1.5, o)[:, None] - np.linspace(0.2, 6.0, v)[None, :] for aug_sel in ('residual', 'amplitude'): with self.subTest(aug_sel=aug_sel): kw = dict(tau=1e-8, maxiter=80, seed=0, aug_k=0.25, aug_sel=aug_sel) ir = m.kernel(B_ov, eia, **kw) ih = m.kernel_host_backed(B_ov, eia, block_rows=37, col_block=16, **kw) self.assertTrue(ih.converged) self.assertLess(abs(ih.energy - ir.energy), 1e-9 * abs(ir.energy))
if __name__ == "__main__": unittest.main()