|
| 1 | +"""The 27B's one-stream attention caches stay within the admitted window, as its startup estimate assumes.""" |
| 2 | + |
| 3 | +import importlib |
| 4 | +from types import SimpleNamespace |
| 5 | + |
| 6 | +import pytest |
| 7 | +import torch |
| 8 | + |
| 9 | +from tests.test_cuda_geometry import allocations # noqa: F401 |
| 10 | + |
| 11 | +Q = "tensorfold.families.qwen3_5.cuda." |
| 12 | +WINDOW = 32768 |
| 13 | +END = WINDOW - 1 # the engine commits at most context_window - 1 rows |
| 14 | +_gen = torch.Generator().manual_seed(27) |
| 15 | +KEYS, VALUES = torch.randn(END, 1, 2, generator=_gen).bfloat16(), torch.randn(END, 1, 2, generator=_gen).bfloat16() |
| 16 | + |
| 17 | + |
| 18 | +def _weights(pattern): |
| 19 | + """Enough of ``Weights`` for ``State``: ``pattern`` holds True for a GDN layer, False for an attention layer.""" |
| 20 | + |
| 21 | + config = SimpleNamespace(k_heads=1, dk=2, v_heads=1, dv=2, conv_kernel=4, kv_heads=1, head_dim=2, vocab=8) |
| 22 | + return SimpleNamespace(config=config, layers=[SimpleNamespace(linear=x) for x in pattern], |
| 23 | + norm=torch.ones(1, dtype=torch.bfloat16), head=SimpleNamespace(n=8)) |
| 24 | + |
| 25 | + |
| 26 | +def _host(monkeypatch, pattern=(True, False, True, False)): |
| 27 | + """The three prefill entries on the host, ``prefill_chunk`` cut to its cache writes, and every buffer size left.""" |
| 28 | + |
| 29 | + forward = importlib.import_module(Q + "forward") |
| 30 | + prefill = importlib.import_module(Q + "prefill") |
| 31 | + decode = importlib.import_module(Q + "decode") |
| 32 | + decode_tp = importlib.import_module(Q + "decode_tp") |
| 33 | + sizes = [] |
| 34 | + |
| 35 | + def chunk(w, tokens, st, *, tp=False, capture_taps=False, last=True): # the kernels need a GPU |
| 36 | + a, b = st.pos, st.pos + int(tokens.shape[0]) |
| 37 | + for i, kv in enumerate(st.kv): |
| 38 | + if kv is not None: |
| 39 | + kbuf, vbuf = prefill._grow(st, i, b) |
| 40 | + kbuf[a:b], vbuf[a:b] = KEYS[a:b], VALUES[a:b] |
| 41 | + sizes.append(kbuf.shape[0]) |
| 42 | + st.pos = b |
| 43 | + return (torch.zeros((1, 2), dtype=torch.bfloat16) if last else None), None |
| 44 | + |
| 45 | + monkeypatch.setattr(prefill, "prefill_chunk", chunk) |
| 46 | + monkeypatch.setattr(forward, "_mm", lambda x, w, xs=None: torch.zeros((1, 8))) |
| 47 | + for mod in (decode, decode_tp): |
| 48 | + monkeypatch.setattr(mod, "sample_rows", lambda logits, positions, sampling: [3]) |
| 49 | + monkeypatch.setattr(decode_tp, "_share", lambda values, rank, device: [3] if values is None else list(values)) |
| 50 | + w = _weights(pattern) |
| 51 | + entries = {"one": lambda n, **kw: decode.prefill(w, range(1, n + 1), None, **kw)[0], |
| 52 | + "rank 0": lambda n, **kw: decode_tp.prefill_tp(w, range(1, n + 1), None, 0, **kw)[0], |
| 53 | + "rank 1": lambda n, **kw: decode_tp.prefill_tp(w, range(1, n + 1), None, 1, **kw)[0]} |
| 54 | + return entries, sizes, forward |
| 55 | + |
| 56 | + |
| 57 | +def _intact(st, end): |
| 58 | + for kv in st.kv: |
| 59 | + if kv is not None: |
| 60 | + assert torch.equal(kv[0][:end], KEYS[:end]) and torch.equal(kv[1][:end], VALUES[:end]) |
| 61 | + |
| 62 | + |
| 63 | +@pytest.mark.parametrize("entry", ["one", "rank 0", "rank 1"]) |
| 64 | +@pytest.mark.parametrize("prompt,unbounded", [(29815, 59624), (31015, 62024), (31497, 62992)]) |
| 65 | +def test_a_fresh_prompt_stays_within_the_limit(allocations, monkeypatch, entry, prompt, unbounded): # noqa: F811 |
| 66 | + entries, sizes, _ = _host(monkeypatch) |
| 67 | + st = entries[entry](prompt) |
| 68 | + assert st.limit == 0 and max(sizes) == unbounded # without a limit: about twice the window |
| 69 | + sizes.clear() |
| 70 | + st = entries[entry](prompt, limit=WINDOW) |
| 71 | + assert st.limit == WINDOW and max(sizes) == WINDOW |
| 72 | + _intact(st, prompt) |
| 73 | + |
| 74 | + |
| 75 | +def test_a_31015_token_prompt_doubles_on_its_last_three_rows(allocations, monkeypatch): # noqa: F811 |
| 76 | + entries, sizes, _ = _host(monkeypatch) |
| 77 | + entries["one"](31015) |
| 78 | + assert list(dict.fromkeys(sizes)) == [3876, 7753, 15506, 31012, 62024] |
| 79 | + sizes.clear() |
| 80 | + entries["one"](31015, limit=WINDOW) |
| 81 | + assert list(dict.fromkeys(sizes)) == [3876, 7753, 15506, 31012, 32768] |
| 82 | + |
| 83 | + |
| 84 | +@pytest.mark.parametrize("entry", ["one", "rank 0", "rank 1"]) |
| 85 | +def test_a_resumed_prompt_keeps_its_state_limit(allocations, monkeypatch, entry): # noqa: F811 |
| 86 | + entries, sizes, _ = _host(monkeypatch) |
| 87 | + for limit, largest in ((0, 64000), (WINDOW, WINDOW)): |
| 88 | + kept = entries[entry](16000, limit=limit) |
| 89 | + sizes.clear() |
| 90 | + st = entries[entry](32100, state=kept) # the engine's cached prompt ends carry the limit |
| 91 | + assert st.limit == limit and max(sizes) == largest |
| 92 | + _intact(st, 32100) |
| 93 | + other = entries[entry](4) |
| 94 | + other.limit = 777 |
| 95 | + assert entries[entry](10, state=other, limit=WINDOW).limit == 777 and other.pos == 4 |
| 96 | + |
| 97 | + |
| 98 | +@pytest.mark.parametrize("limit,largest", [(0, 64000), (WINDOW, WINDOW)]) |
| 99 | +def test_a_reply_committed_to_the_window_end_stays_within_the_limit(allocations, monkeypatch, # noqa: F811 |
| 100 | + limit, largest): |
| 101 | + entries, sizes, forward = _host(monkeypatch, pattern=(False, False)) # commit replays GDN rows on a GPU |
| 102 | + st = entries["one"](16000, limit=limit) |
| 103 | + width = 12 # the one-stream verify window (max_rows) |
| 104 | + while st.pos < END: |
| 105 | + n = min(width, END - st.pos) |
| 106 | + record = [forward.AttentionRecord(KEYS[st.pos:st.pos + n], VALUES[st.pos:st.pos + n]) for _ in st.kv] |
| 107 | + rows = torch.arange(n, dtype=torch.int32) |
| 108 | + forward.commit(st, record, list(range(n)), (rows, torch.tensor([n], dtype=torch.int32), rows.long())) |
| 109 | + sizes += [kv[0].shape[0] for kv in st.kv] |
| 110 | + assert max(sizes) == largest |
| 111 | + _intact(st, END) |
| 112 | + |
| 113 | + |
| 114 | +def _engine(tp, rank): |
| 115 | + from tensorfold.families.qwen3_5.cuda.engine import Qwen27Engine |
| 116 | + |
| 117 | + engine = object.__new__(Qwen27Engine) |
| 118 | + engine.tp, engine.rank, engine.max_rows, engine.allow_copy = tp, rank, 12, True |
| 119 | + engine.w = SimpleNamespace(norm=SimpleNamespace(device="cpu")) |
| 120 | + engine.draft, engine.cache, engine.multi, engine.scheduler = None, [], None, None |
| 121 | + engine.context_window = WINDOW |
| 122 | + return engine |
| 123 | + |
| 124 | + |
| 125 | +class _Followed(Exception): |
| 126 | + pass |
| 127 | + |
| 128 | + |
| 129 | +def test_engine_prefills_within_its_context_window(allocations, monkeypatch): # noqa: F811 |
| 130 | + decode = importlib.import_module(Q + "decode") |
| 131 | + decode_tp = importlib.import_module(Q + "decode_tp") |
| 132 | + limits = [] |
| 133 | + |
| 134 | + def prefill(w, prompt, sampling, draft=None, *, state=None, limit=0): |
| 135 | + limits.append(("one", limit)) |
| 136 | + return SimpleNamespace(pos=len(prompt)), 5 |
| 137 | + |
| 138 | + def prefill_tp(w, prompt, sampling, rank, draft=None, *, state=None, limit=0): |
| 139 | + limits.append((f"rank {rank}", limit)) |
| 140 | + return SimpleNamespace(pos=len(prompt)), 5 |
| 141 | + |
| 142 | + done = SimpleNamespace(seconds=0.0, rounds=0, widths=[]) |
| 143 | + monkeypatch.setattr(decode, "prefill", prefill) |
| 144 | + monkeypatch.setattr(decode, "draft_decode", lambda *a, **kw: done) |
| 145 | + monkeypatch.setattr(decode_tp, "prefill_tp", prefill_tp) |
| 146 | + monkeypatch.setattr(decode_tp, "decode_tp", lambda *a, **kw: done) |
| 147 | + monkeypatch.setattr(decode_tp, "_share", lambda values, rank, device: list(values)) |
| 148 | + for draft in (True, False): |
| 149 | + _engine(1, 0).generate([1, 2, 3], 4, None, lambda tokens: None, draft=draft) |
| 150 | + _engine(2, 0).generate([1, 2, 3], 4, None, lambda tokens: None, draft=draft) |
| 151 | + shared = iter([[1, 4, 0, 1, *decode_tp.pack_sampling(None)], [1, 2, 3]]) |
| 152 | + monkeypatch.setattr(decode_tp, "_share", lambda values, rank, device: next(shared)) |
| 153 | + |
| 154 | + def follow_once(*a, **kw): |
| 155 | + raise _Followed |
| 156 | + |
| 157 | + monkeypatch.setattr(decode_tp, "decode_tp", follow_once) |
| 158 | + with pytest.raises(_Followed): |
| 159 | + _engine(2, 1).follow() |
| 160 | + assert limits == [("one", WINDOW), ("rank 0", WINDOW)] * 2 + [("rank 1", WINDOW)] |
0 commit comments