File size: 3,358 Bytes
a4054b7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
# MIT License, Bryan Cheng, 2026.
"""Unit tests on toy inputs (CPU). Run: python -m pytest -q tests/test_core.py"""
import json
import math
import os
import sys

import numpy as np
import torch
from safetensors.torch import save_file

sys.path.insert(0, os.path.join(os.path.dirname(__file__), ".."))
from src.lorapop.adapters import load_adapter  # noqa: E402
from src.lorapop.deltas import DeltaLinear, set_updates  # noqa: E402
from src.lorapop.genotype import allele, module_loci  # noqa: E402
from src.lorapop.kinship import module_gram  # noqa: E402
from src.lorapop.battery import _halves  # noqa: E402

torch.manual_seed(0)


def _factors(n, p=12, q=10, ranks=(2, 3, 4)):
    return [(torch.randn(ranks[i % len(ranks)], q), torch.randn(p, ranks[i % len(ranks)])) for i in range(n)]


def test_gram_matches_dense_raw_and_weighted():
    f = _factors(5)
    f[2] = None
    P = torch.randn(10, 6)
    for PP in (None, P):
        G = module_gram(f, PP, device="cpu")
        for i in range(5):
            for j in range(5):
                if f[i] is None or f[j] is None:
                    assert G[i, j] == 0
                    continue
                Di = f[i][1] @ f[i][0]
                Dj = f[j][1] @ f[j][0]
                C = torch.eye(10) if PP is None else PP @ PP.T
                ref = float(torch.trace(Di @ C @ Dj.T))
                assert math.isclose(float(G[i, j]), ref, rel_tol=1e-4, abs_tol=1e-4)


def test_adapter_scale_and_rslora(tmp_path):
    A = torch.randn(4, 8)
    B = torch.randn(6, 4)
    for rs in (False, True):
        d = tmp_path / f"ad{int(rs)}"
        d.mkdir()
        save_file({"base_model.model.model.layers.0.self_attn.q_proj.lora_A.weight": A,
                   "base_model.model.model.layers.0.self_attn.q_proj.lora_B.weight": B},
                  str(d / "adapter_model.safetensors"))
        json.dump({"peft_type": "LORA", "r": 4, "lora_alpha": 8, "use_rslora": rs}, open(d / "adapter_config.json", "w"))
        ad = load_adapter(str(d))
        A2, B2 = ad["mods"]["0.q_proj"]
        s = 8 / math.sqrt(4) if rs else 8 / 4
        assert torch.allclose(B2, B * s) and torch.allclose(A2, A)


def test_delta_path_equals_merged():
    lin = torch.nn.Linear(10, 12, bias=False)
    w = DeltaLinear(lin)
    A, B = torch.randn(3, 10), torch.randn(12, 3)
    set_updates({"k": w}, {"k": [(A, B, 0.5)]}, dtype=torch.float32, device="cpu")
    x = torch.randn(4, 10)
    ref = x @ (lin.weight + 0.5 * B @ A).T
    assert torch.allclose(w(x), ref, atol=1e-5)


def test_genotype_axis_and_allele_projection():
    q, p, n = 10, 12, 7
    f = _factors(n, p, q)
    lam, V = torch.rand(q) + 0.1, torch.linalg.qr(torch.randn(q, q))[0]
    P = V * lam.sqrt()[None, :]
    loci = module_loci(f, P, var_frac=0.999, max_loci=5, device="cpu")
    E = torch.stack([(B @ A @ P).flatten() for A, B in f])
    Ec = E - E.mean(0)
    for l in range(loci["n_loci"]):
        D = allele(f, loci["U"][:, l].float(), loci["lam"][l].float(), V, device="cpu")
        L = (D @ P).flatten()  # expressed axis of the allele
        assert math.isclose(float(L.norm()), 1.0, rel_tol=1e-3)
        g = (Ec @ L).double()
        assert torch.allclose(g, loci["g"][:, l], rtol=1e-3, atol=1e-3)


def test_halves_disjoint_cover():
    h = _halves(101, 3)
    assert set(np.unique(h)) == {0, 1} and abs(int(h.sum()) - 50) <= 1