lorapop / code /tests /test_cross.py
bryan7264's picture
Add files using upload-large-folder tool
a4054b7 verified
Raw History Blame Contribute Delete
2.3 kB
# MIT License, Bryan Cheng, 2026.
import torch
from src.run.cross import NDIR, direction_pieces
def test_direction_pieces_sum_and_expressed_svd():
g = torch.Generator().manual_seed(0)
p, q, r, k = 40, 30, 8, 20
A, B = torch.randn(r, q, generator=g, dtype=torch.float64), torch.randn(p, r, generator=g, dtype=torch.float64)
Q, _ = torch.linalg.qr(torch.randn(q, k, generator=g, dtype=torch.float64))
lam = torch.linspace(5, 0.1, k, dtype=torch.float64)
pcs = direction_pieces(A, B, Q, lam)
assert len(pcs) == NDIR + 1
D = B @ A
S = sum(b.double() @ a.double() for a, b in pcs)
assert torch.allclose(S, D, atol=1e-4)
P = Q * lam.sqrt()[None, :]
E = D @ P
s = torch.linalg.svdvals(E)
Ej = [(b.double() @ a.double()) @ P for a, b in pcs]
for j in range(NDIR):
assert abs(float(Ej[j].norm()) - float(s[j])) < 1e-3 * float(s[0])
for i in range(NDIR + 1):
for j in range(i + 1, NDIR + 1):
assert abs(float((Ej[i] * Ej[j]).sum())) < 1e-3 * float(s[0]) ** 2
def test_direction_pieces_low_rank():
g = torch.Generator().manual_seed(1)
A, B = torch.randn(2, 12, generator=g), torch.randn(10, 2, generator=g)
Q, _ = torch.linalg.qr(torch.randn(12, 6, generator=g))
pcs = direction_pieces(A, B, Q, torch.ones(6))
assert pcs[2] is None and pcs[3] is None and pcs[NDIR] is not None
def test_hw_center_removes_group_offset_using_training_rows_only():
import numpy as np
from src.analysis.crosses import hw_center
rng = np.random.default_rng(0)
n = 400
hw = np.array(["A|[128, 256]"] * (n // 2) + ["B|[32, 64]"] * (n // 2))
y = rng.normal(size=n) + np.where(hw == "B|[32, 64]", 0.5, 0.0)
Y = np.stack([y, y, y])[:, :, None]
rows = np.ones(n, bool)
rows[::5] = False # held-out rows do not inform the adjustment
Z = hw_center(Y, hw, rows)
ga, gb = hw == "A|[128, 256]", hw == "B|[32, 64]"
assert abs(np.mean(Z[0, ga & rows, 0]) - np.mean(Z[0, gb & rows, 0])) < 1e-12
Y2 = Y.copy()
Y2[:, ~rows] += 100.0 # changing held-out values must not change the shift applied to training rows
assert np.allclose(hw_center(Y2, hw, rows)[:, rows], Z[:, rows])
assert np.allclose(hw_center(Y, np.array(["A"] * n), rows), Y) # one group: unchanged