"""Isolated test of width-7 causal conv1d on XPU. Compares against an independent per-sequence F.conv1d reference in fp32: * vLLM's stock Triton causal_conv1d_fn / causal_conv1d_update (expected to be wrong at width 7) * vllm_lfm3.conv_ops torch and triton paths, for both conv-state layouts (SD, DS), for prefill (fresh + continued chunks, sequences shorter than the state) and decode. Run inside the container: python /work/tests/test_conv_kernel.py """ import sys import time import torch import torch.nn.functional as F sys.path.insert(0, "/work") from vllm_lfm3 import conv_ops # noqa: E402 torch.manual_seed(0) DEV = "xpu" if torch.xpu.is_available() else "cpu" DT = torch.bfloat16 D, K = 2048, 7 L = K - 1 NUM_BLOCKS = 16 def ref_conv(x_seq, state, w, bias): """x_seq (T, D) fp32, state (L, D) fp32 -> out (T, D), new_state (L, D).""" full = torch.cat([state, x_seq], 0) # (L+T, D) out = F.conv1d(full.T[None], w[:, None, :], bias, groups=D)[0].T # (T, D) return out, full[-L:] def make_case(lens, has_init, layout): w = torch.randn(D, K, device=DEV, dtype=DT) * 0.3 x = torch.randn(sum(lens), D, device=DEV, dtype=DT) if layout == "SD": state = torch.randn(NUM_BLOCKS, L, D, device=DEV, dtype=DT) state_view = state else: # DS storage, viewed token-major state = torch.randn(NUM_BLOCKS, D, L, device=DEV, dtype=DT) state_view = state.transpose(1, 2) slots = torch.tensor([3, 7, 1, 12, 5][: len(lens)], device=DEV, dtype=torch.int32) qsl = torch.zeros(len(lens) + 1, dtype=torch.int32, device=DEV) qsl[1:] = torch.cumsum(torch.tensor(lens, device=DEV), 0) hi = torch.tensor(has_init, device=DEV, dtype=torch.bool) return w, x, state, state_view, slots, qsl, hi def reference_prefill(w, x, state_view, slots, qsl, hi): outs, states = [], state_view.float().clone() for i in range(len(slots)): a, b = int(qsl[i]), int(qsl[i + 1]) init = states[int(slots[i])] if bool(hi[i]) else torch.zeros(L, D, device=DEV) o, ns = ref_conv(x[a:b].float(), init, w.float(), None) outs.append(o) states[int(slots[i])] = ns return torch.cat(outs), states def check(name, got, want, tol=2e-2): err = (got.float() - want.float()).abs().max().item() ok = err < tol print(f" {'PASS' if ok else 'FAIL'} {name:<44} max_abs_err={err:.3e}") return ok def test_ours(impl): ok = True prefill = getattr(conv_ops, f"causal_conv1d_prefill_{impl}") decode = getattr(conv_ops, f"causal_conv1d_decode_{impl}") for layout in ("SD", "DS"): lens, has_init = [37, 3, 1, 300, 6], [False, True, True, False, True] w, x, state, sv, slots, qsl, hi = make_case(lens, has_init, layout) want_out, want_state = reference_prefill(w, x, sv, slots, qsl, hi) out = prefill(x, w, None, sv, qsl, slots, hi) ok &= check(f"{impl}/{layout} prefill out", out, want_out) ok &= check(f"{impl}/{layout} prefill state", sv.float(), want_state) # 5 decode steps, with one padded row (-1) that must not corrupt anything for step in range(5): xd = torch.randn(len(lens), D, device=DEV, dtype=DT) want_rows, st = [], sv.float().clone() for i in range(len(lens)): o, ns = ref_conv(xd[i : i + 1].float(), st[int(slots[i])], w.float(), None) want_rows.append(o) st[int(slots[i])] = ns pad_idx = torch.cat([slots, torch.tensor([-1], device=DEV, dtype=torch.int32)]) xpad = torch.cat([xd, torch.zeros(1, D, device=DEV, dtype=DT)]) out = decode(xpad, w, None, sv, pad_idx)[: len(lens)] ok &= check(f"{impl}/{layout} decode step {step} out", out, torch.cat(want_rows)) # block 0 is the null block (written by the pad row); compare all others ok &= check(f"{impl}/{layout} decode step {step} state", sv[1:].float(), st[1:]) return ok def test_stock_vllm(): from vllm.model_executor.layers.mamba.ops.causal_conv1d import ( causal_conv1d_fn, causal_conv1d_update, ) lens, has_init = [37, 3, 300], [False, True, False] w, x, state, sv, slots, qsl, hi = make_case(lens, has_init, "DS") want_out, want_state = reference_prefill(w, x, sv, slots, qsl, hi) try: out = causal_conv1d_fn( x.T, w, None, state, qsl, cache_indices=slots, has_initial_state=hi, activation=None, ).T check("stock causal_conv1d_fn out (width 7)", out, want_out) check("stock causal_conv1d_fn state (width 7)", sv.float(), want_state) except Exception as e: # noqa: BLE001 print(f" ERROR stock causal_conv1d_fn: {type(e).__name__}: {str(e)[:200]}") try: xd = torch.randn(len(lens), D, device=DEV, dtype=DT) st = sv.float().clone() want = [] for i in range(len(lens)): o, ns = ref_conv(xd[i : i + 1].float(), st[int(slots[i])], w.float(), None) want.append(o) out = causal_conv1d_update(xd, state, w, None, activation=None, conv_state_indices=slots) check("stock causal_conv1d_update out (width 7)", out, torch.cat(want)) except Exception as e: # noqa: BLE001 print(f" ERROR stock causal_conv1d_update: {type(e).__name__}: {str(e)[:200]}") def bench(): print("\nTiming (bf16, D=2048):") for impl in ("torch", "triton"): prefill = getattr(conv_ops, f"causal_conv1d_prefill_{impl}") decode = getattr(conv_ops, f"causal_conv1d_decode_{impl}") for lens in ([2048], [512] * 16): w, x, state, sv, slots, qsl, hi = make_case(lens[:5] if len(lens) > 5 else lens, [False] * min(5, len(lens)), "SD") if len(lens) > 5: x = torch.randn(sum(lens), D, device=DEV, dtype=DT) slots = torch.arange(len(lens), device=DEV, dtype=torch.int32) % NUM_BLOCKS qsl = torch.arange(len(lens) + 1, device=DEV, dtype=torch.int32) * lens[0] hi = torch.zeros(len(lens), dtype=torch.bool, device=DEV) for _ in range(3): prefill(x, w, None, sv, qsl, slots, hi) torch.xpu.synchronize() t0 = time.perf_counter() for _ in range(20): prefill(x, w, None, sv, qsl, slots, hi) torch.xpu.synchronize() print(f" {impl:<6} prefill {len(lens)}x{lens[0]:<5} {1e3 * (time.perf_counter() - t0) / 20:.3f} ms") for n in (1, 16): xd = torch.randn(n, D, device=DEV, dtype=DT) idx = torch.arange(n, device=DEV, dtype=torch.int32) % NUM_BLOCKS for _ in range(3): decode(xd, w, None, sv, idx) torch.xpu.synchronize() t0 = time.perf_counter() for _ in range(100): decode(xd, w, None, sv, idx) torch.xpu.synchronize() print(f" {impl:<6} decode batch {n:<9} {1e3 * (time.perf_counter() - t0) / 100:.3f} ms") if __name__ == "__main__": print(f"device={DEV} torch={torch.__version__}") print("\n[stock vLLM Triton causal_conv1d at width 7]") test_stock_vllm() all_ok = True for impl in ("torch", "triton"): print(f"\n[vllm_lfm3.conv_ops {impl}]") all_ok &= test_ours(impl) if DEV == "xpu": bench() print("\nRESULT:", "ALL PASS" if all_ok else "FAILURES") sys.exit(0 if all_ok else 1)