# SPDX-License-Identifier: Apache-2.0 """Host tests of the plain-SDPA key-chunk guard (tt/sdpa_chunks.py; no device, no ttnn): - every reachable plain (non-causal, non-windowed) SDPA shape of the three variants gets an even key-chunk count (or a single query chunk per head), for any tile batch up to 16 and every prefill bucket; - no plain SDPA call in the package bypasses the wrapper (static scan of the sources); - DSOCR_PREFILL_BUCKETS values without an even split are refused when the server starts (Unlimited-OCR-2). tt-metal 44d6650's plain SDPA returns wrong (batch, head) slots for an odd key-chunk count when a head's query chunks are split over several cores (tenstorrent/tt-metal PR #60493); causal, windowed and decode SDPA are not affected. """ from __future__ import annotations import os import re import sys import types import pytest HERE = os.path.dirname(os.path.abspath(__file__)) PKG = os.path.dirname(HERE) sys.path.insert(0, os.path.dirname(PKG)) from tt_dsocr import config as C # noqa: E402 from tt_dsocr.tt import sdpa_chunks as SC # noqa: E402 @pytest.mark.parametrize("sk,k,want", [ (288, 32, 160), # Qwen2 encoder on a 768 tile / CLIP on a 1024 view: 9 chunks -> 2 (96, 32, 64), # CLIP on a 512 view: 3 -> 2 (416, 32, 128), # CLIP on a 1280 view: 13 -> 4 (128, 32, 32), # already even (4096, 128, 128), # SAM global on a 1024 view: 32 chunks (384, 128, 96), # DASH prefill buckets (Unlimited-OCR-2 defaults) (640, 128, 160), (2176, 128, 160), (2304, 128, 128), (32, 32, 32), # one chunk whatever the size: safe only with one query chunk (see chain_safe) ]) def test_even_k_chunk(sk, k, want): got = SC.even_k_chunk(sk, k) assert got == want and got % 32 == 0 and got <= SC.K_CHUNK_MAX assert sk <= 32 or SC.n_chunks(sk, got) % 2 == 0 def test_check_refuses_odd_counts(): SC.check("x", 288, 288, 32, 160) SC.check("x", 32, 32, 32, 32) # one query chunk per head: no KV chain with pytest.raises(AssertionError, match="odd key-chunk count"): SC.check("x", 288, 288, 32, 32) with pytest.raises(ValueError): SC.even_k_chunk(288, 48) def _vision_views(variant: str, max_tiles: int = 16): """(view size, images) of every traced vision view the device model can build (tt/model.py DsocrDevice), with tile batches up to ``max_tiles`` (the default tile_chunk is 4).""" from tt_dsocr import frontend as FE v = FE.VARIANTS[variant] out = set() for m in [m[0] for m in C.VARIANTS[variant].modes]: b, s, crop = FE.mode_params(v, m) if crop: out.add((b, 1)) out.update((v.tile, n) for n in range(1, max_tiles + 1)) else: out.add((s, 1)) return sorted(out) @pytest.mark.parametrize("variant", ["deepseek-ocr", "deepseek-ocr-2", "unlimited-ocr-2"]) def test_every_vision_shape_is_safe(variant): pytest.importorskip("torch") from tt_dsocr.tt.vision_consts import view_geom seen = [] for S, B in _vision_views(variant): g = view_geom(S, B) rows = {"SAM global attention": (g.g * g.G32, 128)} if variant == "deepseek-ocr-2": rows["Qwen2 encoder attention"] = (2 * g.n, 32) else: rows["CLIP attention"] = (g.Sc, 32) for site, (s, ch) in rows.items(): qc, kc = SC.chunks(site, s, s, ch, ch) assert SC.chain_safe(s, s, qc, kc) and SC.n_chunks(s, kc) % 2 == 0, (site, S, B, s, kc) seen.append((site, S, s, kc)) if variant == "deepseek-ocr-2": # the audited case: 768 tiles, 288 rows -> 160-row key chunks assert ("Qwen2 encoder attention", 768, 288, 160) in seen def test_every_dash_bucket(): ok = bad = 0 for b in range(32, 16384 + 1, 32): ch = SC.dash_chunk(b) try: qc, kc = SC.chunks("DASH prefill attention", b, b, ch, ch) except (AssertionError, ValueError): assert b % 128, b # every multiple of 128 has an even split bad += 1 continue assert SC.chain_safe(b, b, qc, kc) and kc <= SC.K_CHUNK_MAX ok += 1 assert ok > 500 and bad < 10 for b in C.resolve_config({"DSOCR_VARIANT": "unlimited-ocr-2"}).pre_buckets: SC.chunks("DASH prefill attention", b, b, SC.dash_chunk(b), SC.dash_chunk(b)) def test_bucket_without_even_split_refuses_to_start(): bad = next(b for b in range(32, 16384 + 1, 32) if b >= 4096 and not _splits(b)) with pytest.raises(ValueError, match="even number of key chunks"): C.resolve_config({"DSOCR_VARIANT": "unlimited-ocr-2", "DSOCR_PREFILL_BUCKETS": f"4096,{bad}"}) C.resolve_config({"DSOCR_VARIANT": "unlimited-ocr-2", "DSOCR_PREFILL_BUCKETS": "4096,4224"}) # the other variants' prefill is causal: any bucket is fine C.resolve_config({"DSOCR_PREFILL_BUCKETS": f"1792,{bad}"}) def _splits(b: int) -> bool: try: SC.chunks("x", b, b, SC.dash_chunk(b), SC.dash_chunk(b)) return True except (AssertionError, ValueError): return False def test_wrapper_picks_and_passes_the_even_chunk(): calls = [] def op(q, k, v, **kw): calls.append(kw) return "out" cfg = lambda **kw: types.SimpleNamespace(**kw) # noqa: E731 ttnn = types.SimpleNamespace(SDPAProgramConfig=cfg, transformer=types.SimpleNamespace(scaled_dot_product_attention=op, flash_mla_prefill=op)) t = lambda *s: types.SimpleNamespace(shape=s) # noqa: E731 grid = types.SimpleNamespace(x=12, y=10) assert SC.plain_sdpa(ttnn, t(6, 14, 288, 64), t(6, 2, 288, 64), t(6, 2, 288, 64), grid=grid, site="qwen", q_chunk=32, k_chunk=32, attn_mask="m", scale=0.125) == "out" kw = calls[-1] assert kw["is_causal"] is False and kw["attn_mask"] == "m" and kw["scale"] == 0.125 pc = kw["program_config"] assert (pc.q_chunk_size, pc.k_chunk_size, pc.compute_with_storage_grid_size) == (32, 160, (12, 10)) SC.plain_sdpa(ttnn, t(1, 12, 4096, 192), t(1, 12, 4096, 192), t(1, 12, 4096, 64), grid=grid, site="sam", q_chunk=128, k_chunk=128, mla=True) assert calls[-1]["program_config"].k_chunk_size == 128 for bad in ({"is_causal": True}, {"cu_window_seqlens": [0, 288]}, {"program_config": None}): with pytest.raises(TypeError): SC.plain_sdpa(ttnn, t(1, 1, 288, 64), t(1, 1, 288, 64), t(1, 1, 288, 64), grid=grid, site="x", q_chunk=32, k_chunk=32, **bad) _CALL = re.compile(r"\btransformer\s*\.\s*(scaled_dot_product_attention|flash_mla_prefill)\s*\(") def _call_text(src: str, start: int) -> str: depth, i = 0, src.index("(", start) for j in range(i, len(src)): depth += {"(": 1, ")": -1}.get(src[j], 0) if depth == 0: return src[i:j + 1] raise AssertionError("unbalanced call") def test_no_plain_sdpa_bypasses_the_wrapper(): """Every SDPA call in the package outside tt/sdpa_chunks.py is causal, windowed or a decode op; the vendored ttaw's generic attention helper (ttaw/ops/attention.py) is not used by the package.""" checked = 0 for root, dirs, files in os.walk(PKG): rel = os.path.relpath(root, PKG) dirs[:] = [d for d in dirs if d not in ("__pycache__", "ttaw")] for f in files: if not f.endswith(".py") or f.startswith("test_host_sdpa_chunks") or (rel, f) == ("tt", "sdpa_chunks.py"): continue path = os.path.join(root, f) src = open(path, encoding="utf-8").read() assert "ttaw.ops.attention" not in src and "ttaw.ops import attention" not in src, path if rel == "reference" or f == "fake_ttnn_torch.py": continue # torch's F.scaled_dot_product_attention (CPU) / the fake ttnn op for m in _CALL.finditer(src): call = _call_text(src, m.start()) assert "is_causal=True" in call or "cu_window_seqlens=" in call, \ f"{path}: a plain SDPA call outside tt/sdpa_chunks.plain_sdpa: {call[:120]}" checked += 1 assert checked >= 2 # the decoder's causal prefill and SAM's windowed attention