File size: 9,570 Bytes
f35e9c1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
"""Backend unit tests on a tiny random Qwen3.5 (CPU, fp32, seconds): Verdin's forward pass against transformers'
Qwen3_5TextModel run the way kev runs a hybrid backbone (one causal row per question = state + branch, positions
continuing; kev.model.DecisionModel.forward_rows_batch). Covers batching across requests, chunked prefill and multi-sweep
plans, the prefix cache, duplicate states in one batch, attention query chunking, the unknown head, and unmerged-LoRA
vs merged weights. Test-only dependency: transformers (>= 5.17; its torch reference kernels on CPU).

    python -m verdin.tests.test_tiny                          (CPU fp32; or pytest verdin/tests/test_tiny.py)
    python -m verdin.tests.test_tiny --device cuda --dtype bf16  (GPU kernels: fla, causal-conv1d, SDPA; looser tolerance)
"""
import argparse
import math
import random
import sys

import torch

sys.modules.setdefault("fla", None)           # transformers must take its torch reference kernels (CPU)
sys.modules.setdefault("causal_conv1d", None)

from verdin.config import Arch  # noqa: E402
from verdin.render import Encoded, Row  # noqa: E402
from verdin.torch_backend import TorchEngine, TorchModel, TorchOptions  # noqa: E402

# logits reach ~20 on this random model; transformers' own bf16 path drifts 0.64 from fp32 on it (Verdin's bf16: 0.40), and
# fla's Triton kernels may use TF32 dots even for fp32 inputs
TOL = {"cpu-fp32": 2e-4, "cuda-fp32": 0.05, "cuda-bf16": 1.0, "cpu-bf16": 1.0}
DEVICE, DTYPE = "cpu", "fp32"


def tiny(seed=0, unknown=False):
    from transformers import Qwen3_5TextConfig, Qwen3_5TextModel
    torch.manual_seed(seed)
    lt = ["linear_attention"] * 3 + ["full_attention"] + ["linear_attention"] * 3 + ["full_attention"]
    cfg = Qwen3_5TextConfig(vocab_size=300, hidden_size=128, intermediate_size=192, num_hidden_layers=8, num_attention_heads=4,
                            num_key_value_heads=2, head_dim=64, linear_conv_kernel_dim=4, linear_key_head_dim=64,
                            linear_value_head_dim=64, linear_num_key_heads=2, linear_num_value_heads=4, rms_norm_eps=1e-6,
                            layer_types=lt, rope_parameters={"rope_type": "default", "rope_theta": 10000000.0,
                                                             "partial_rotary_factor": 0.25, "mrope_section": [3, 3, 2],
                                                             "mrope_interleaved": True})
    cfg._attn_implementation = "eager"
    model = Qwen3_5TextModel(cfg).eval()
    with torch.no_grad():
        for name, p in model.named_parameters():
            if "norm" in name:
                p.normal_(0.0, 0.2)
            elif name.endswith("A_log"):
                p.uniform_(-1.0, 1.0)
            elif name.endswith("dt_bias"):
                p.normal_(0.0, 0.5)
            else:
                p.normal_(0.0, 0.08)
    head = {"q.weight": torch.randn(16, 128) * 0.2, "q.bias": torch.randn(16) * 0.1,
            "k.weight": torch.randn(16, 128) * 0.2, "k.bias": torch.randn(16) * 0.1}
    if unknown:
        head["unk_key"] = torch.randn(16) * 0.5
        head["unk_bias"] = torch.tensor(0.3)
    arch = Arch.from_hf_text_config(cfg.to_dict())
    return model, {k: v.detach().clone() for k, v in model.state_dict().items()}, head, arch


def ref_logits(model, head, enc, temperature=1.0):
    """kev's row form: one causal row per question through transformers, pointer head on <decide> / </opt>."""
    out, unk = [], []
    S = enc.state_ids
    with torch.no_grad():
        for r in enc.rows:
            ids = torch.tensor([S + r.ids]); pos = torch.arange(len(S) + len(r.ids))[None]
            h = model(input_ids=ids, position_ids=pos).last_hidden_state[0].float()
            qd = h[len(S) + r.decide] @ head["q.weight"].T + head["q.bias"]
            ko = h[[len(S) + o for o in r.opts]] @ head["k.weight"].T + head["k.bias"]
            scale = 1 / math.sqrt(head["q.weight"].shape[0])
            out.append(((ko @ qd) * scale).tolist())
            if "unk_key" in head:
                unk.append(float((qd @ head["unk_key"]) * scale + head["unk_bias"]))
    return out, unk


def rand_request(rng, n_state, n_q):
    S = [rng.randrange(1, 300) for _ in range(n_state)]
    rows = []
    for _ in range(n_q):
        K = rng.randint(1, 5)
        ids, opts = [rng.randrange(1, 300) for _ in range(rng.randint(1, 6))], []
        for _ in range(K):
            ids += [rng.randrange(1, 300) for _ in range(rng.randint(1, 7))]
            opts.append(len(ids) - 1)
        ids.append(rng.randrange(1, 300))
        rows.append(Row(ids, len(ids) - 1, opts))
    return Encoded(S, rows)


def engine(sd, head, arch, lora=None, fuse=True, **kw):
    opts = TorchOptions(device=DEVICE, dtype=DTYPE, **kw)
    return TorchEngine(TorchModel(arch, lambda n: sd[n], head, 1.0, opts, "fp32", lora=lora, fuse=fuse))


def maxdiff(a, b):
    return max(abs(x - y) for ra, rb in zip(a, b) for x, y in zip(ra, rb))


def check(eng, model, head, encs, label):
    res = eng.run(encs)
    worst = 0.0
    for e, r in zip(encs, res):
        ref, unk = ref_logits(model, head, e)
        worst = max(worst, maxdiff(ref, r.logits))
        if unk:
            worst = max(worst, max(abs(a - b) for a, b in zip(unk, r.unknown)))
        assert all(len(x) == len(y) for x, y in zip(ref, r.logits))
    tol = TOL[f"{DEVICE.split(':')[0]}-{DTYPE}"]
    print(f"  {label}: max |dlogit| = {worst:.2e}  ({DEVICE} {DTYPE}, tol {tol:g})")
    assert worst < tol, f"{label}: {worst}"
    return res


def test_all():
    rng = random.Random(0)
    model, sd, head, arch = tiny(0)
    reqs = [rand_request(rng, n, q) for n, q in ((1, 1), (5, 2), (70, 3), (130, 1), (64, 4), (200, 2))]
    e = engine(sd, head, arch)
    check(e, model, head, reqs[:1], "single request, 1-token state")
    check(e, model, head, [reqs[2]], "single request, 3 questions")
    check(e, model, head, reqs, "batch of 6 requests")
    # chunked prefill + split rows across sweeps
    e2 = engine(sd, head, arch, prefill_chunk=48, max_sweep_tokens=80, max_sweep_rows=3)
    check(e2, model, head, reqs, "multi-sweep (prefill_chunk 48, 80 tokens / sweep, 3 rows / sweep)")
    # attention query chunking (force tiny score blocks)
    e3 = engine(sd, head, arch, prefill_chunk=100)
    e3.m.attn_elems = 4 * 40
    if DEVICE.startswith("cuda"):
        print(f"  kernels: {e3.m.describe()}")
    check(e3, model, head, reqs, "attention query chunking")
    # prefix cache: second run hits
    e4 = engine(sd, head, arch, prefix_cache=8, prefix_cache_min_tokens=0)
    first = e4.run(reqs)
    again = check(e4, model, head, reqs, "prefix cache (second pass)")
    assert all(r.cache_hit for r in again) and not any(r.cache_hit for r in first)
    e6 = engine(sd, head, arch, prefix_cache=8, prefix_cache_min_tokens=0, prefill_chunk=48, max_sweep_tokens=80, max_sweep_rows=3)
    e6.run(reqs)
    again = check(e6, model, head, reqs, "prefix cache + multi-sweep (second pass)")
    assert all(r.cache_hit for r in again)
    # the same state twice in one batch (and different questions)
    dup = Encoded(reqs[4].state_ids, reqs[2].rows)
    check(engine(sd, head, arch, prefill_chunk=40, max_sweep_tokens=60), model, head, [reqs[4], dup, reqs[1], dup], "duplicate states in a batch")
    # unknown head
    model_u, sd_u, head_u, arch_u = tiny(1, unknown=True)
    check(engine(sd_u, head_u, arch_u), model_u, head_u, reqs[:4], "unknown head")
    # unmerged LoRA vs merged weights (convert's verification path)
    targets = [k for k in sd if k.endswith("_proj.weight") or ".in_proj_" in k or k.endswith("out_proj.weight")]
    lora, merged = {}, dict(sd)
    for k in targets:
        out_f, in_f = sd[k].shape
        a, b = torch.randn(4, in_f) * 0.05, torch.randn(out_f, 4) * 0.05
        lora[k] = (a, b, 2.0)
        merged[k] = sd[k] + 2.0 * b @ a
    with torch.no_grad():
        model.load_state_dict(merged)
    check(engine(sd, head, arch, lora=lora, fuse=False), model, head, reqs, "unmerged LoRA (base + s*B@A) vs merged reference")
    check(engine(merged, head, arch), model, head, reqs, "merged weights")
    # out-of-memory handling (simulated): only the request that does not fit alone is refused
    e5 = engine(sd, head, arch)
    real = e5._run

    def fake(reqs, keep=frozenset()):
        if any(r.enc.n_state > 150 for r in reqs):
            raise torch.OutOfMemoryError("simulated")
        return real(reqs, keep)
    e5._run = fake
    res = e5.run(reqs)
    assert [r.error is not None for r in res] == [e.n_state > 150 for e in reqs], [r.error for r in res]
    assert all(r.logits is not None for r, e in zip(res, reqs) if e.n_state <= 150)
    assert "too many tokens" in str(next(r.error for r in res if r.error is not None))
    print("  simulated OOM: only the oversized request refused")
    print("tiny backend tests: OK")


if __name__ == "__main__":
    ap = argparse.ArgumentParser()
    ap.add_argument("--device", default="cpu")
    ap.add_argument("--dtype", default="fp32")
    ap.add_argument("--branch-gdr", default="chunk")
    a = ap.parse_args()
    DEVICE, DTYPE = a.device, a.dtype
    if a.branch_gdr != "chunk":
        _engine = engine
        engine = lambda *x, **k: _engine(*x, branch_gdr=a.branch_gdr, **k)   # noqa: E731
    if DEVICE.startswith("cuda"):
        import transformers.models.qwen3_5.modeling_qwen3_5  # noqa: F401 - binds transformers' torch reference kernels now
        del sys.modules["fla"], sys.modules["causal_conv1d"]    # ... so that only Verdin picks up the GPU kernels
    test_all()