Source code for pytc.solver.test.test_bug_kernels

"""Native-unittest gates for the JAX BUG kernels and solver backends."""

import unittest

import numpy as np

from pytc.solver import bug_core, bug_helper, bug_rpa
from pyscf import gto, scf

import jax

jax.config.update("jax_enable_x64", True)

from pytc.solver.bug_core import extract_df_factors
from pytc.solver.bug_rpa import kernel


[docs] class TestBugJax(unittest.TestCase):
[docs] @classmethod def setUpClass(cls): cls.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(cls.mol).density_fit().run() cls.nocc = cls.mol.nelectron // 2 mo_e = np.asarray(cls.mf.mo_energy) cls.eia = (mo_e[:cls.nocc, None] - mo_e[None, cls.nocc:]) _, cls.B_ov, _ = extract_df_factors(cls.mf, cls.nocc)
[docs] def test_explicit_gemm_kernels_match_numpy(self): from pytc.solver import bug_core rng = np.random.default_rng(7) o, v, q, rp = 3, 7, 11, 4 V = rng.standard_normal((o, v, rp)) Bov = rng.standard_normal((o, v, q)) got = np.asarray(jax.device_get(bug_rpa.df_matvec(Bov, V))) B = Bov.reshape(o * v, q) ref = B @ (B.T @ V.reshape(o * v, rp)) np.testing.assert_allclose(got, ref, rtol=2e-13, atol=2e-13) n, r0, ra = 29, 6, 4 U, _ = np.linalg.qr(rng.standard_normal((n, r0))) Qa, _ = np.linalg.qr(rng.standard_normal((n, ra))) B = rng.standard_normal((n, 13)) BU = B @ (B.T @ U) BQa = B @ (B.T @ Qa) d = rng.standard_normal(n) Ed_uu = U.T @ (d[:, None] * U) Bt_uu = 2 * (U.T @ BU) got_E, got_Bt = bug_rpa.rpa_core_blocks( U, Qa, BQa, d, Ed_uu, Bt_uu) got_E, got_Bt = map(np.asarray, jax.device_get((got_E, got_Bt))) Uaug = np.concatenate((U, Qa), axis=1) BUaug = np.concatenate((BU, BQa), axis=1) ref_Bt = 2 * (Uaug.T @ BUaug) ref_E = Uaug.T @ (d[:, None] * Uaug) + ref_Bt np.testing.assert_allclose(got_Bt, ref_Bt, rtol=2e-13, atol=2e-13) np.testing.assert_allclose(got_E, ref_E, rtol=2e-13, atol=2e-13) # Cross the 4096-row streaming boundary and exercise the tail block. n, r0, ra = 4111, 5, 3 U, _ = np.linalg.qr(rng.standard_normal((n, r0))) Qa, _ = np.linalg.qr(rng.standard_normal((n, ra))) B = rng.standard_normal((n, 7)) BU = B @ (B.T @ U) BQa = B @ (B.T @ Qa) d = rng.standard_normal(n) Ed_uu = U.T @ (d[:, None] * U) Bt_uu = 2 * (U.T @ BU) got_E, got_Bt = bug_rpa.rpa_core_blocks( U, Qa, BQa, d, Ed_uu, Bt_uu) got_E, got_Bt = map(np.asarray, jax.device_get((got_E, got_Bt))) Uaug = np.concatenate((U, Qa), axis=1) BUaug = np.concatenate((BU, BQa), axis=1) ref_Bt = 2 * (Uaug.T @ BUaug) ref_E = Uaug.T @ (d[:, None] * Uaug) + ref_Bt np.testing.assert_allclose(got_Bt, ref_Bt, rtol=2e-13, atol=2e-13) np.testing.assert_allclose(got_E, ref_E, rtol=2e-13, atol=2e-13)
[docs] def test_cholesky_core_matches_two_eigensolve_reference(self): from pytc.solver import bug_core rng = np.random.default_rng(29) for rank in (17, 61): q, _ = np.linalg.qr(rng.standard_normal((rank, rank))) gaps = np.linspace(0.7, 2.1, rank) coupling = np.linspace(0.002, 0.03, rank) Bt = (q * coupling) @ q.T E = np.diag(gaps) + Bt lam_m, Vm = np.linalg.eigh(E - Bt) s = np.sqrt(lam_m) G = Vm.T @ (E + Bt) @ Vm C = s[:, None] * G * s[None, :] w2, W = np.linalg.eigh((C + C.T) / 2) w = np.maximum(np.sqrt(np.clip(w2, 0.0, None)), 1e-14) P = W / s[:, None] Q = s[:, None] * W X = P * np.sqrt(w)[None, :] + Q / np.sqrt(w)[None, :] Y = P * np.sqrt(w)[None, :] - Q / np.sqrt(w)[None, :] ref = -Vm @ np.linalg.solve(X.T, Y.T).T @ Vm.T ref = (ref + ref.T) / 2 got, got_w2, got_chol = bug_rpa.core_sym_eig(E, Bt) got, got_w2, got_chol = map( np.asarray, jax.device_get((got, got_w2, got_chol))) np.testing.assert_allclose(got, ref, rtol=2e-12, atol=2e-12) np.testing.assert_allclose( got_w2, w2.min(), rtol=2e-12, atol=2e-12) self.assertGreater(float(got_chol), 0.0) residual = Bt + E @ got + got @ E + got @ Bt @ got self.assertLess(np.abs(residual).max(), 2e-12)
[docs] def test_cholesky_core_flags_non_positive_input(self): from pytc.solver import bug_core E = np.diag([1.0, 0.5]) Bt = np.diag([0.1, 0.6]) _, min_w2, min_cholesky = bug_rpa.core_sym_eig(E, Bt) min_w2, min_cholesky = map( np.asarray, jax.device_get((min_w2, min_cholesky))) self.assertTrue(np.isneginf(min_w2)) self.assertTrue(np.isneginf(min_cholesky))
[docs] def test_projected_selection_reuses_the_ranked_block(self): from scipy.linalg import qr from pytc.solver import bug_core rng = np.random.default_rng(11) U, _ = np.linalg.qr(rng.standard_normal((37, 9))) D = rng.standard_normal((37, 9)) W = D - U @ (U.T @ D) W = W - U @ (U.T @ W) k = 4 sel = np.sort(np.argsort(-np.linalg.norm(W, axis=0))[:k]) got = np.asarray(jax.device_get( bug_core.project_directions(U, D, kabs=k, how="residual"))) np.testing.assert_allclose(got, W[:, sel], rtol=2e-13, atol=2e-13) Q = np.asarray(jax.device_get(bug_core.orth_directions(got))) np.testing.assert_allclose(Q.T @ Q, np.eye(Q.shape[1]), rtol=2e-13, atol=2e-13) np.testing.assert_allclose(U.T @ Q, 0.0, rtol=0.0, atol=2e-13) # Tall QR followed by pivoting only its small R factor must retain the # same rank/subspace as pivoting the full tall matrix, including a # deliberately deficient block that takes the slow cleanup path. base = rng.standard_normal((53, 6)) rank_def = np.column_stack((base, base[:, 0] - 2 * base[:, 3], base[:, 2], np.zeros(53))) Qref, Rref, _ = qr(rank_def, mode="economic", pivoting=True) diag = np.abs(np.diag(Rref)) keep = diag > 1e-10 * max(1.0, float(diag.max())) Qref = Qref[:, keep] Qgot = np.asarray(jax.device_get( bug_core.orth_directions(rank_def))) self.assertEqual(Qgot.shape[1], Qref.shape[1]) np.testing.assert_allclose(Qgot.T @ Qgot, np.eye(Qgot.shape[1]), rtol=2e-13, atol=2e-13) np.testing.assert_allclose(Qgot @ Qgot.T, Qref @ Qref.T, rtol=2e-13, atol=2e-13)
[docs] def test_rpa_residual_drops_only_projected_span_terms(self): from pytc.solver import bug_core rng = np.random.default_rng(19) n, r = 41, 11 U, _ = np.linalg.qr(rng.standard_normal((n, r))) S = rng.standard_normal(r) BU = rng.standard_normal((n, r)) d = rng.standard_normal(n) US = U * S[None, :] BUs = BU * S[None, :] A = U.T @ (d[:, None] * U) + 2 * (U.T @ BU) D = (2 * BU + d[:, None] * US + 2 * BUs + U @ (S[:, None] * A) + 2 * U @ (S[:, None] * (U.T @ BUs))) ref = D - U @ (U.T @ D) ref = ref - U @ (U.T @ ref) got = np.asarray(jax.device_get( bug_rpa.projected_residual(U, S, BU, d))) np.testing.assert_allclose(got, ref, rtol=2e-13, atol=2e-13) k = 4 sel = np.sort(np.argsort(-np.linalg.norm(ref, axis=0))[:k]) got = np.asarray(jax.device_get( bug_rpa.projected_residual( U, S, BU, d, k=k, how="residual"))) np.testing.assert_allclose(got, ref[:, sel], rtol=2e-13, atol=2e-13) got = np.asarray(jax.device_get( bug_rpa.projected_residual( U, S, BU, d, k=k, how="top"))) np.testing.assert_allclose(got, ref[:, :k], rtol=2e-13, atol=2e-13)
[docs] class TestStreamedResidualSelection(unittest.TestCase): """Oracle gates for the block_rows-streamed projected residual. Every path is checked against the dense kernel it replaces, at widths that do not divide nov so the clamped tail panel is always exercised -- that tail repeats rows, which writes tolerate and Gram/norm accumulations do not. """ SHAPES = ((1000, 12), (1001, 12), (997, 31), (37, 5)) WIDTHS = (32, 128, 333) @staticmethod def _case(nov, r, seed): rng = np.random.default_rng(seed) return (np.linalg.qr(rng.standard_normal((nov, r)))[0], 0.1 * rng.standard_normal(r), rng.standard_normal((nov, r)), 0.5 + rng.random(nov))
[docs] def test_full_width_matches_dense(self): from pytc.solver import bug_core for nov, r in self.SHAPES: U, S, BU, d = self._case(nov, r, 17) ref = np.asarray(jax.device_get( bug_rpa._rpa_projected_residual(U, U, S, BU, d))) scale = max(np.abs(ref).max(), 1e-300) for block_rows in self.WIDTHS + (nov, 2 * nov): with self.subTest(nov=nov, block_rows=block_rows): got = np.asarray(jax.device_get( bug_rpa.projected_residual( U, S, BU, d, block_rows=block_rows))) self.assertEqual(got.shape, ref.shape) self.assertLess(np.abs(got - ref).max() / scale, 1e-12)
[docs] def test_top_k_selection_matches_dense(self): """Selection runs off streamed norms, so it must pick the same columns.""" from pytc.solver import bug_core for nov, r in self.SHAPES: U, S, BU, d = self._case(nov, r, 17) ref = np.asarray(jax.device_get( bug_rpa._rpa_projected_residual(U, U, S, BU, d))) scale = max(np.abs(ref).max(), 1e-300) k = max(1, round(0.35 * r)) sel = np.sort(np.argsort(-np.linalg.norm(ref, axis=0))[:k]) for block_rows in self.WIDTHS: with self.subTest(nov=nov, block_rows=block_rows): got = np.asarray(jax.device_get( bug_rpa.projected_residual( U, S, BU, d, k=k, block_rows=block_rows))) self.assertEqual(got.shape, (nov, k)) self.assertLess(np.abs(got - ref[:, sel]).max() / scale, 1e-12)
[docs] def test_leading_column_path_unchanged(self): """how != 'residual' keeps the dense kernel: different algebra, untouched.""" from pytc.solver import bug_core for nov, r in self.SHAPES: U, S, BU, d = self._case(nov, r, 17) k = max(1, round(0.35 * r)) ref = np.asarray(jax.device_get( bug_rpa._rpa_projected_residual( U, U[:, :k], S[:k], BU[:, :k], d))) scale = max(np.abs(ref).max(), 1e-300) for block_rows in self.WIDTHS: with self.subTest(nov=nov, block_rows=block_rows): got = np.asarray(jax.device_get( bug_rpa.projected_residual( U, S, BU, d, k=k, how="amplitude", block_rows=block_rows))) self.assertLess(np.abs(got - ref).max() / scale, 1e-12)
[docs] def test_streamed_residual_stays_orthogonal(self): """Panelling must not cost the double Gram-Schmidt: U.T @ W vanishes.""" from pytc.solver import bug_core U, S, BU, d = self._case(997, 21, 9) for block_rows in (64, 333): with self.subTest(block_rows=block_rows): W = np.asarray(jax.device_get( bug_rpa.projected_residual(U, S, BU, d, block_rows=block_rows))) self.assertLess( np.abs(U.T @ W).max() / max(np.abs(W).max(), 1e-300), 1e-13)
[docs] class TestStreamedCoreGrams(unittest.TestCase): """Oracle gate for the panelled core Grams. ``Ed_uu`` written eagerly materialises ``d[:, None] * U`` at full height purely to contract it away. These check the panelled form against the dense expression at several ranks and at widths that do not divide nov, so the clamped tail -- which repeats rows and must be masked out of the accumulation -- is always exercised. """
[docs] def test_matches_dense_at_several_ranks_and_tails(self): from pytc.solver import bug_core rng = np.random.default_rng(23) for nov, r in ((1000, 8), (1001, 12), (997, 31), (853, 47), (37, 5)): U = np.linalg.qr(rng.standard_normal((nov, r)))[0] BU = rng.standard_normal((nov, r)) d = 0.5 + rng.random(nov) Ed_ref = U.T @ (d[:, None] * U) Bt_ref = 2 * (U.T @ BU) for block_rows in (32, 128, 333, nov, 2 * nov): with self.subTest(nov=nov, r=r, block_rows=block_rows): Ed, Bt = bug_rpa.streamed_core_grams( U, BU, d, block_rows=block_rows) Ed = np.asarray(jax.device_get(Ed)) Bt = np.asarray(jax.device_get(Bt)) self.assertEqual(Ed.shape, (r, r)) self.assertEqual(Bt.shape, (r, r)) self.assertLess(np.abs(Ed - Ed_ref).max() / max(np.abs(Ed_ref).max(), 1e-300), 1e-12) self.assertLess(np.abs(Bt - Bt_ref).max() / max(np.abs(Bt_ref).max(), 1e-300), 1e-12)
[docs] def test_symmetry_of_the_metric_gram(self): """Ed_uu is U.T diag(d) U and must stay symmetric under panelling.""" from pytc.solver import bug_core rng = np.random.default_rng(5) nov, r = 997, 23 U = np.linalg.qr(rng.standard_normal((nov, r)))[0] BU = rng.standard_normal((nov, r)) d = 0.5 + rng.random(nov) for block_rows in (64, 333): with self.subTest(block_rows=block_rows): Ed, _ = bug_rpa.streamed_core_grams(U, BU, d, block_rows=block_rows) Ed = np.asarray(jax.device_get(Ed)) self.assertLess(np.abs(Ed - Ed.T).max() / max(np.abs(Ed).max(), 1e-300), 1e-13)
[docs] class TestExecutionPlanner(unittest.TestCase): """Gates for the resident-vs-streamed planner. The planner decides from exact shapes and the runtime arena, never from a system size. Its bound is a structural count of the arrays the iteration holds, so these check the decision boundary and the direction of the bound rather than any particular constant. """ ARENA = int(126.4 * 1024**3)
[docs] def test_host_limit_is_the_minimum_of_all_sources(self): """Not the first parsable source -- the smallest enforceable one. cgroup, Slurm and physical RAM can disagree. Only the smallest is actually enforced, so taking the first that parses makes stale environment metadata dangerous instead of merely conservative. """ import os from unittest import mock from pytc.solver import bug_core # Slurm claims 512 GiB on a machine with far less: must bind low. with mock.patch.dict(os.environ, {"SLURM_MEM_PER_NODE": str(512 * 1024)}): binding, sources = bug_helper.host_memory_limits() finite = [v for v in sources.values() if isinstance(v, int) and v > 0] self.assertEqual(binding, min(finite)) self.assertLess(binding, 512 * 1024 ** 3) self.assertEqual(sources["slurm_mem_per_node"], 512 * 1024 ** 3) # every source is recorded, present or not, for the receipt for key in ("cgroup_v2", "cgroup_v1", "slurm_mem_per_node", "slurm_mem_per_cpu_total", "physical"): self.assertIn(key, sources)
[docs] def test_selection_width_uses_the_orbital_floor(self): """2(nocc+nvir) dominates the fraction when the rank is small against it.""" from pytc.solver.bug_core import requested_aug_width self.assertEqual(requested_aug_width(7924, 281, 1409, aug_k=0.35), 3380) self.assertGreater(requested_aug_width(7924, 281, 1409, aug_k=0.35), round(0.35 * 7924)) self.assertEqual(requested_aug_width(int(113.2 * 200), 803, 4026, aug_k=0.35), 9658)
[docs] class TestHostStreamedDF(unittest.TestCase): """Gates for the input-streamed DF action. The streamed path must be the same arithmetic with a different residency, so it is checked against the device path it replaces rather than against a tolerance chosen for it. """
[docs] def test_energy_matches_device_path(self): from pytc.solver import bug_core rng = np.random.default_rng(6) for o, v, naux, r in ((8, 40, 30, 17), (11, 37, 29, 23)): B = rng.standard_normal((o, v, naux)) U = rng.standard_normal((o * v, r)) S = rng.standard_normal(r) ref = float(bug_rpa.df_weighted_energy(B, U, S)) for block_rows in (7, 16, o * v): with self.subTest(o=o, block_rows=block_rows): got = float(bug_rpa.df_weighted_energy_host_streamed( B, U, S, block_rows=block_rows)) self.assertLess(abs(got - ref) / max(abs(ref), 1e-300), 1e-12)
[docs] class TestFusedStreamedCore(unittest.TestCase): """Gates for the fused output-streamed core. The design's whole claim is that the core Grams and the selected residual can be produced without ever allocating a full-height BU, using two exact identities. These check the identities against the implementation they replace, at widths that leave non-divisible tails. """ SHAPES = ((8, 40, 30, 12), (11, 37, 29, 9), (13, 41, 23, 17))
[docs] def test_matches_current_implementation(self): from pytc.solver import bug_core rng = np.random.default_rng(41) for o, v, naux, r in self.SHAPES: nov = o * v B = rng.standard_normal((o, v, naux)) U = np.linalg.qr(rng.standard_normal((nov, r)))[0] S = 0.1 * rng.standard_normal(r) d = 0.5 + rng.random(nov) BU = np.asarray(jax.device_get( bug_rpa.df_matvec(B, U.reshape(o, v, r)))) Ed_ref, Bt_ref = bug_rpa.streamed_core_grams(U, BU, d, block_rows=nov) Ed_ref = np.asarray(jax.device_get(Ed_ref)) Bt_ref = np.asarray(jax.device_get(Bt_ref)) k = max(1, round(0.35 * r)) W_ref = np.asarray(jax.device_get( bug_rpa.projected_residual(U, S, BU, d, k=k, block_rows=nov))) for block_rows in (7, 16, nov): with self.subTest(nov=nov, r=r, block_rows=block_rows): Ed, Bt, W = bug_rpa.fused_host_streamed_core( B, U, S, d, block_rows=block_rows, k=k) for got, ref in ((Ed, Ed_ref), (Bt, Bt_ref), (W, W_ref)): got = np.asarray(jax.device_get(got)) self.assertEqual(got.shape, ref.shape) self.assertLess( np.abs(got - ref).max() / max(np.abs(ref).max(), 1e-300), 1e-12)
[docs] def test_selects_the_same_columns(self): """Norms come from an identity, not from a materialised residual.""" from pytc.solver import bug_core rng = np.random.default_rng(7) o, v, naux, r = 11, 37, 29, 13 nov = o * v B = rng.standard_normal((o, v, naux)) U = np.linalg.qr(rng.standard_normal((nov, r)))[0] S = 0.1 * rng.standard_normal(r) d = 0.5 + rng.random(nov) BU = np.asarray(jax.device_get(bug_rpa.df_matvec(B, U.reshape(o, v, r)))) W_full = np.asarray(jax.device_get( bug_rpa.projected_residual(U, S, BU, d, block_rows=nov))) k = 5 sel_ref = np.sort(np.argsort(-np.linalg.norm(W_full, axis=0))[:k]) _, _, W = bug_rpa.fused_host_streamed_core(B, U, S, d, block_rows=16, k=k) W = np.asarray(jax.device_get(W)) self.assertLess(np.abs(W - W_full[:, sel_ref]).max() / max(np.abs(W_full).max(), 1e-300), 1e-12)
[docs] def test_streamed_path_never_builds_full_bu(self): """Host-backed never forms the full-height B B^T U: the full-height matvec must not be called at all.""" from unittest import mock from pyscf import gto, scf from pytc.solver.bug_rpa import low_rank_rpa mf = scf.RHF(gto.M(atom='H 0 0 0; F 0 0 0.92', basis='6-31g', verbose=0)).density_fit().run() with mock.patch.object(bug_rpa, 'df_matvec', side_effect=AssertionError('full-height BU')): res = low_rank_rpa(mf, tau=1e-6, host_backed=True, block_rows=7) self.assertTrue(res.converged)
[docs] def test_fused_boundaries_actually_alias(self): """Donation is a request, not a guarantee -- it is only real if the compiled executable aliases the donated argument onto its output. A refactor that adds a use after the donation silently drops the alias and doubles the resident cost, which no numerical test would notice.""" from pytc.solver import bug_core nov, naux, r, pn, k = 512, 40, 12, 128, 7 S = lambda *sh: jax.ShapeDtypeStruct(sh, np.float64) accum = bug_rpa._fused_accum m = accum.lower(S(r, r), S(r, r), S(r, r), S(r, r), S(r), S(pn, naux), S(pn, r), S(pn), S(naux, r), S(r)).compile().memory_analysis() # Every one of the five accumulators comes back aliased, so none is # copied. Compare against the exact payload rather than # output_size_in_bytes: the latter carries a few tens of bytes of # tuple-descriptor overhead that is not a buffer. self.assertEqual(m.alias_size_in_bytes, (4 * r * r + r) * 8) self.assertLess(m.output_size_in_bytes - m.alias_size_in_bytes, 4096) emit = bug_rpa._fused_emit_store m2 = emit.lower(S(nov, k), S(pn, naux), S(pn, r), S(pn), S(naux, r), S(r), S(r, k), jax.ShapeDtypeStruct((k,), np.int32), jax.ShapeDtypeStruct((), np.int32)).compile().memory_analysis() # the full-height output is written in place, never rebuilt per panel self.assertEqual(m2.alias_size_in_bytes, nov * k * 8) self.assertEqual(m2.output_size_in_bytes, m2.alias_size_in_bytes)
[docs] class TestStreamedTSQR(unittest.TestCase): """Out-of-core rank-revealing QR for the host-backed mode.""" def _mk(self, n, k, decades, seed=3): rng = np.random.default_rng(seed) U, _ = np.linalg.qr(rng.standard_normal((n, k))) V, _ = np.linalg.qr(rng.standard_normal((k, k))) return np.ascontiguousarray( U @ np.diag(np.logspace(0, -decades, k)) @ V.T)
[docs] def test_matches_in_core_rank_and_subspace(self): """Same rank decision and same span as orth_directions, no tall device array. Panel width must not change the answer.""" from pytc.solver import bug_core rng = np.random.default_rng(7) cases = { 'full rank': rng.standard_normal((900, 24)), 'deficient': rng.standard_normal((900, 18)) @ rng.standard_normal((18, 24)), 'one column': rng.standard_normal((500, 1)), } for name, W in cases.items(): W = np.ascontiguousarray(W, dtype=np.float64) ref = np.asarray(jax.device_get( bug_core.orth_directions(jax.device_put(W)))) for block_rows in (64, 128, 4096): with self.subTest(case=name, block_rows=block_rows): Q, kept, d = bug_rpa.streamed_orth_directions( W, block_rows=block_rows) self.assertEqual(kept, ref.shape[1]) self.assertIsInstance(Q, np.ndarray) # host, not device np.testing.assert_allclose( Q.T @ Q, np.eye(kept), atol=1e-12) # projectors agree => same subspace, any column signs np.testing.assert_allclose( Q @ Q.T, ref @ ref.T, atol=1e-10)
[docs] def test_tsqr_r_matches_dense_r(self): """Panel reduction must give the same R as a dense QR, up to signs.""" from pytc.solver import bug_core W = self._mk(700, 12, 4) R = np.asarray(jax.device_get( bug_rpa.streamed_tsqr_r(W, block_rows=97))) ref = np.linalg.qr(W, mode='r') # R is unique up to row sign; compare |R| and the Gram it implies np.testing.assert_allclose(np.abs(R), np.abs(ref), atol=1e-10) np.testing.assert_allclose(R.T @ R, W.T @ W, rtol=1e-9, atol=1e-12)
[docs] def test_orthogonality_gate_fires_and_then_refuses(self): """The gate must have polarity: fire when needed, refuse when it cannot deliver, and never return a basis that is not orthonormal. Recovering Q from a triangular factor loses orthogonality on an ill-conditioned block. Returning it anyway would corrupt the projected core while leaving the energy plausible. """ from pytc.solver import bug_core mild = self._mk(600, 16, 6) Q, kept, d = bug_rpa.streamed_orth_directions(mild, block_rows=100) self.assertEqual(d['passes'], 1) # no second pass needed self.assertLess(d['orth_error'], d['orth_tol']) hard = self._mk(600, 16, 10) with self.assertRaises(RuntimeError): # one pass cannot deliver bug_rpa.streamed_orth_directions(hard, block_rows=100, max_passes=1) # the second (CholeskyQR2) pass does Q, kept, d = bug_rpa.streamed_orth_directions(hard, block_rows=100) self.assertEqual((d['passes'], kept), (2, 16)) np.testing.assert_allclose(Q.T @ Q, np.eye(kept), atol=1e-12) # the remedy named in the error message must actually work Q, kept, d = bug_rpa.streamed_orth_directions( hard, rel_tol=1e-6, block_rows=100) self.assertLess(d['orth_error'], d['orth_tol']) self.assertLess(kept, 16) np.testing.assert_allclose(Q.T @ Q, np.eye(kept), atol=1e-8)
[docs] def test_second_pass_actually_improves(self): """A retry that does not help is not a remedy. The gate is set from the first pass's own error on this machine, so the test does not depend on how much roundoff a particular BLAS produces. """ from pytc.solver import bug_core W = self._mk(600, 16, 10) _, _, one = bug_rpa.streamed_orth_directions(W, block_rows=100, max_passes=1, orth_tol=1.0) e1 = one['orth_error'] self.assertGreater(e1, 1e-12) # the fixture is ill-conditioned Q, kept, d = bug_rpa.streamed_orth_directions( W, block_rows=100, max_passes=2, orth_tol=e1 / 2) self.assertEqual(d['passes'], 2) # first pass failed the gate hist = d['orth_error_history'] self.assertAlmostEqual(hist[0], e1, delta=1e-3 * e1) self.assertLess(hist[1], e1 / 2) # the retry helped enough np.testing.assert_allclose(Q.T @ Q, np.eye(kept), atol=1e-6)
[docs] class TestHostBackedPhases(unittest.TestCase): """Phases that must stop materialising full-height device arrays.""" def _case(self, nov, naux, r0, ra, seed=5): rng = np.random.default_rng(seed) B = rng.standard_normal((nov, naux)) * 0.05 U = np.linalg.qr(rng.standard_normal((nov, r0)))[0] Qa = np.linalg.qr(rng.standard_normal((nov, ra)))[0] d = 0.6 + rng.random(nov) return B, U, Qa, d
[docs] def test_core_blocks_match_in_core_at_every_panel(self): """The eigenproblem downstream must not be able to tell which path ran.""" from pytc.solver import bug_core for nov, naux, r0, ra in ((512, 29, 11, 7), (1000, 37, 17, 13)): B, U, Qa, d = self._case(nov, naux, r0, ra) Ed_uu = U.T @ (d[:, None] * U) Bt_uu = 2 * (U.T @ (B @ (B.T @ U))) ref = bug_rpa.rpa_core_blocks( jax.device_put(U), jax.device_put(Qa), jax.device_put(B @ (B.T @ Qa)), jax.device_put(d), jax.device_put(Ed_uu), jax.device_put(Bt_uu)) refE, refBt = [np.asarray(jax.device_get(x)) for x in ref] for panel in (64, 128, nov): with self.subTest(nov=nov, panel=panel): got = bug_rpa.hostbacked_core_blocks( B, U, Qa, d, jax.device_put(Ed_uu), jax.device_put(Bt_uu), block_rows=panel) gE, gBt = [np.asarray(jax.device_get(x)) for x in got] np.testing.assert_allclose(gE, refE, rtol=1e-11, atol=1e-13) np.testing.assert_allclose(gBt, refBt, rtol=1e-11, atol=1e-13)
[docs] def test_basis_update_lands_on_host_and_cross_agrees(self): """U_new must come back as a NumPy array -- a device array here would be the full-height allocation this phase exists to avoid.""" from pytc.solver import bug_core rng = np.random.default_rng(11) for nov, r0, ra, rn in ((800, 13, 9, 15), (512, 7, 5, 9)): U = np.linalg.qr(rng.standard_normal((nov, r0)))[0] Qa = np.linalg.qr(rng.standard_normal((nov, ra)))[0] Wu = jax.device_put(rng.standard_normal((r0, rn))) Wq = jax.device_put(rng.standard_normal((ra, rn))) ref = np.asarray(jax.device_get(bug_rpa.basis_update( jax.device_put(U), jax.device_put(Qa), Wu, Wq))) for panel in (64, 256, nov): with self.subTest(nov=nov, panel=panel): got, cross = bug_core.hostbacked_basis_update( U, Qa, Wu, Wq, block_rows=panel) self.assertIsInstance(got, np.ndarray) np.testing.assert_allclose(got, ref, rtol=1e-12, atol=1e-14) np.testing.assert_allclose( np.asarray(jax.device_get(cross)), ref.T @ U, rtol=1e-10, atol=1e-13)
[docs] def test_panelling_holds_no_full_height_device_array(self): """Trace the live device bytes per panel: they must stay bounded by the panel, not grow toward the full height.""" from pytc.solver import bug_core nov, naux, r0, ra = 4096, 31, 9, 7 B, U, Qa, d = self._case(nov, naux, r0, ra) for fn, kwargs in ( (lambda sink: bug_rpa.hostbacked_core_blocks( B, U, Qa, d, jax.device_put(U.T @ (d[:, None] * U)), jax.device_put(2 * (U.T @ (B @ (B.T @ U)))), block_rows=256, trace_sink=sink), {}), (lambda sink: bug_core.hostbacked_basis_update( U, Qa, jax.device_put(np.eye(r0, 5)), jax.device_put(np.zeros((ra, 5))), block_rows=256, trace_sink=sink), {}), ): sink = [] fn(sink) self.assertGreater(len(sink), 4) # actually panelled live = [e[-1] for e in sink if isinstance(e[-1], int)] if live: # bounded: the spread across panels must not scale with nov self.assertLess(max(live) - min(live), nov * 8 * (r0 + ra))
[docs] class TestHostBackedEndToEnd(unittest.TestCase): """host-backed must be the same solver, with nothing tall on the device.""" def _sys(self, o=8, v=40, naux=30, seed=11): rng = np.random.default_rng(seed) return (0.05 * rng.standard_normal((o, v, naux)), -(0.6 + rng.random((o, v))))
[docs] def test_tsqr_transfers_are_counted_to_the_byte(self): """The TSQR panels are the largest H->D traffic there is, and they moved through device_array() rather than the counter -- charged to compute_s, invalidating the compute/transfer fit. Tied to a known panel and pass count, not merely `h2d_bytes > 0`. """ from pytc.solver import bug_core rng = np.random.default_rng(7) nov, k, panel = 4096, 12, 512 W = np.ascontiguousarray(rng.standard_normal((nov, k))) npan = -(-nov // panel) bug_helper.reset_transfer_counters() Q, kept, d = bug_rpa.streamed_orth_directions(W, block_rows=panel) c = bug_helper.transfer_counters() self.assertEqual(d['passes'], 1) # pin the pass count wp = panel * k * 8 # one TSQR traversal + one emission traversal; R stays on the device self.assertEqual(c['put_calls'], 2 * npan) self.assertEqual(c['put_bytes'], 2 * npan * wp) # Q comes back whole, exactly once self.assertGreaterEqual(c['get_bytes'], nov * kept * 8)
[docs] class TestBasisBuffers(unittest.TestCase): """Reused host buffers for the host-backed basis update. The buffers exist because ``np.empty`` per call re-faults the destination, which is slower than reusing a pre-touched buffer. These gates cover byte-identity, the ownership contract, and the cap that the host memory plan relies on. """ NOV, R0, Q, RN, PANEL = 3000, 24, 11, 27, 512
[docs] @classmethod def setUpClass(cls): from pytc.solver import bug_core cls.bj = bug_core rng = np.random.default_rng(0) cls.U = np.ascontiguousarray(rng.standard_normal((cls.NOV, cls.R0))) cls.Qa = np.ascontiguousarray(rng.standard_normal((cls.NOV, cls.Q))) cls.Wu = jax.device_put(rng.standard_normal((cls.R0, cls.RN))) cls.Wq = jax.device_put(rng.standard_normal((cls.Q, cls.RN)))
def _update(self, **kw): return self.bj.hostbacked_basis_update( self.U, self.Qa, self.Wu, self.Wq, block_rows=self.PANEL, **kw)
[docs] def test_out_rejects_shape_dtype_and_noncontiguous(self): for bad, why in ( (np.empty((self.NOV, self.RN + 1)), 'shape'), (np.empty((self.NOV, self.RN), dtype=np.float32), 'dtype'), (np.empty((self.NOV, self.RN + 3))[:, :self.RN], 'strides')): with self.subTest(why=why), self.assertRaises(ValueError): self._update(out=bad)
[docs] def test_out_rejects_a_buffer_aliasing_a_live_input(self): # One allocation, two overlapping contiguous views: this clears the # shape, dtype and contiguity gates, so only the alias check can catch # it -- and it is exactly what a single self-overwriting pool would do. pool = np.zeros(self.NOV * self.RN) u = pool[:self.NOV * self.R0].reshape(self.NOV, self.R0) out = pool.reshape(self.NOV, self.RN) self.assertTrue(np.shares_memory(u, out)) with self.assertRaises(ValueError): self.bj.hostbacked_basis_update(u, self.Qa, self.Wu, self.Wq, block_rows=self.PANEL, out=out)
if __name__ == '__main__': unittest.main()