Files
kernbench2/tests/test_kernel_runner.py
T
mukesh d282144339 gqa: ADR-0060/0062/0063/0064 unified GQA kernels + CPU cost model
Land the new GQA fused-attention kernels (ADR-0060) for prefill/decode
across long and short context, the TL discipline primitives they depend
on (ADR-0062 lazy load, ADR-0063 scratch_scope + copy_to), and the
per-op-type CPU issue cost model (ADR-0064). Remove the pre-ADR-0060
mesh-attention baseline now that the unified kernels supersede it.

ADR-0060 (long context)
- _gqa_decode.py: M-fold + 2-level chain reduce-to-root (Level-2
  intra-CUBE row-then-col + Level-1 inter-CUBE) — root-only output.
- _gqa_prefill.py: head-parallel + Ring KV rotation around C CUBEs,
  online-softmax merge per ring step, per-CUBE distributed output.
- Each merge stage wraps in scratch_scope() and persists running
  (m, l, O) via copy_to() to lift the 1 MiB scratch ceiling.

ADR-0060 §B.split.2 (short context, kv_per_cube in {1,2,4,8})
- _gqa_decode_short.py / _gqa_prefill_short.py: no cube-SP; each CUBE
  owns whole KV heads; PE-parallel heads with intra-group chain
  reduce. Prefill has no Ring KV (each head fully resident).

ADR-0062 (lazy tl.load): future-bearing TensorHandle, auto-wait at
first consuming op (dot/MATH/store/send/copy_to/composite).

ADR-0063 (tl.scratch_scope + tl.copy_to): scoped per-tile arena with
copy_to writeback primitive for persistent running state.

ADR-0064 (CPU issue cost model)
- common/cpu_issue_cost.py: per-op-type table (composite=40 ns,
  primitives=5 ns); ratios are load-bearing per D1.
- TLContext: issue_cost_table param; _emit_dispatch_overhead(kind)
  consults table with dispatch_cycles fallback (ADR-0046 §D6
  back-compat).
- Live PE_CPU paths (greenlet + legacy) construct TLContext with
  DEFAULT_CPU_ISSUE_COST so saturation lever (ADR-0060 §1) is
  measurable end-to-end.

P7 headline bench: milestone-gqa-headline writes per-panel
op_log_summary to 1H_milestone_output/gqa_headline/sweep.json. No
figure renderers yet (deferred).

Removals (pre-ADR-0060 baseline now superseded):
- benches: _attention_mesh_kv.py, _attention_mesh_mlo.py,
  _attention_mesh_mlo_2d.py, milestone_gqa_llama70b.py
- tests: test_attention_*, test_mesh_*, test_milestone_gqa_llama70b
- topology: llama70b_4sip.yaml (only consumer was the deleted diag)
- artifacts: 1H_milestone_output/gqa/ (sweep.json + 5 PNGs)
- tests/gqa/ plot helper + test (broken on Windows Tcl/Tkinter)
- ADR-0060/0061 references to deleted file paths cleaned up
  (EN + KO kept in sync).

Tests: 124/124 focused regression green (attention + Phase E + TL
discipline + triton_emu + pe_components). Full regression: 764 pass,
2 pre-existing test_bench_registry failures (stale EXPECTED_NAMES
across multiple benches, not introduced here).

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
2026-06-09 18:15:59 -07:00

159 lines
4.8 KiB
Python

"""Tests for KernelRunner greenlet-based execution (ADR-0020 D3)."""
import numpy as np
import simpy
from kernbench.sim_engine.memory_store import MemoryStore
from kernbench.triton_emu.kernel_runner import KernelRunner
def _make_runner(env, store=None):
"""Create a minimal KernelRunner with mock scheduler port."""
scheduler_id = "sip0.cube0.pe0.pe_scheduler"
out_ports = {scheduler_id: simpy.Store(env)}
runner = KernelRunner(
pe_prefix="sip0.cube0.pe0",
pe_idx=0, sip_idx=0, cube_idx=0,
scheduler_id=scheduler_id,
out_ports=out_ports,
store=store,
)
return runner, out_ports[scheduler_id]
def _mock_scheduler(env, inbox):
"""Consume PeInternalTxn from inbox and immediately succeed."""
while True:
pe_txn = yield inbox.get()
pe_txn.done.succeed()
def test_kernel_runner_basic_load():
"""Kernel with tl.load runs through greenlet without hanging.
Under ADR-0062 (lazy ``tl.load``) the handle's ``data`` is None
until a consumer op triggers auto-wait at first use. A no-op math
op (``tl.exp``) consumes ``a`` and forces resolution before we
inspect ``a.data``.
"""
env = simpy.Environment()
store = MemoryStore()
data = np.ones((4, 4), dtype=np.float16)
store.write("hbm", 0x1000, data)
runner, sched_port = _make_runner(env, store)
env.process(_mock_scheduler(env, sched_port))
def kernel(a_ptr, tl):
a = tl.load(a_ptr, (4, 4), "f16")
tl.exp(a) # consumer op → auto-wait at first use (ADR-0062 §D2)
assert a.data is not None
assert a.data.shape == (4, 4)
def run():
yield from runner.run(env, kernel, [0x1000], num_programs=1)
env.process(run())
env.run()
def test_kernel_runner_load_returns_data():
"""tl.load returns actual numpy data from MemoryStore.
Under ADR-0062 lazy semantics the data is attached at auto-wait
time (first consumer op), so we read ``a.data`` after a consumer
op fires the wait.
"""
env = simpy.Environment()
store = MemoryStore()
data = np.array([[1.0, 2.0], [3.0, 4.0]], dtype=np.float16)
store.write("hbm", 0x2000, data)
runner, sched_port = _make_runner(env, store)
env.process(_mock_scheduler(env, sched_port))
results = {}
def kernel(ptr, tl):
a = tl.load(ptr, (2, 2), "f16")
tl.exp(a) # consumer op → auto-wait at first use (ADR-0062 §D2)
results["data"] = a.data
def run():
yield from runner.run(env, kernel, [0x2000], num_programs=1)
env.process(run())
env.run()
assert results["data"] is data # reference equality
def test_kernel_runner_composite():
"""Composite commands pass through without blocking kernel."""
env = simpy.Environment()
runner, sched_port = _make_runner(env)
env.process(_mock_scheduler(env, sched_port))
def kernel(a_ptr, b_ptr, out_ptr, tl):
a = tl.ref(a_ptr, (4, 8), "f16")
b = tl.ref(b_ptr, (8, 4), "f16")
h = tl.composite(op="gemm", a=a, b=b, out_ptr=out_ptr)
tl.wait(h)
def run():
yield from runner.run(env, kernel, [0, 64, 128], num_programs=1)
env.process(run())
env.run()
def test_kernel_runner_dynamic_branch():
"""Kernel can branch based on loaded data (ADR-0020 D3)."""
env = simpy.Environment()
store = MemoryStore()
store.write("hbm", 0x100, np.array([1.0], dtype=np.float32))
store.write("hbm", 0x200, np.array([0.0], dtype=np.float32))
runner, sched_port = _make_runner(env, store)
env.process(_mock_scheduler(env, sched_port))
results = {"branch": None}
def kernel(flag_ptr, tl):
flag = tl.load(flag_ptr, (1,), "f32")
# ADR-0062: under lazy tl.load, dynamic-branching kernels must
# force resolution by consuming the handle (any tl.* op works).
# Without this, flag.data is None at branch time and control
# always takes the not-taken path.
tl.exp(flag)
if flag.data is not None and flag.data[0] > 0.5:
results["branch"] = "taken"
else:
results["branch"] = "not_taken"
# Test with flag=1.0 → branch taken
def run():
yield from runner.run(env, kernel, [0x100], num_programs=1)
env.process(run())
env.run()
assert results["branch"] == "taken"
def test_kernel_runner_no_store():
"""Without MemoryStore, tl.load returns handle with data=None."""
env = simpy.Environment()
runner, sched_port = _make_runner(env, store=None)
env.process(_mock_scheduler(env, sched_port))
results = {}
def kernel(ptr, tl):
a = tl.load(ptr, (4,), "f16")
results["data"] = a.data
def run():
yield from runner.run(env, kernel, [0], num_programs=1)
env.process(run())
env.run()
assert results["data"] is None