"""Contracts, independent mathematical references, and fixed integration glue.""" import math import torch import torch.nn.functional as F from . import extended, sparse, expansion TASKS = { "gqa_attention": {"rtol": 0.02, "atol": 0.02, "nrmse": 0.01, "min_sm": 80}, "fp8_gemm": {"rtol": 0.02, "atol": 0.02, "nrmse": 0.01, "min_sm": 89}, "fused_mlp": {"rtol": 0.02, "atol": 0.001, "rms_atol": 0.05, "nrmse": 0.01, "min_sm": 80}, } TASKS.update(extended.CONTRACTS) TASKS.update(sparse.CONTRACTS) TASKS.update(expansion.CONTRACTS) PATTERNS = ("normal", "uniform", "zeros", "outliers") def make_inputs(case, seed, pattern="normal"): gen = torch.Generator(device="cuda").manual_seed(seed) def rand(shape, scale=1.0): if pattern == "zeros": x = torch.zeros(shape, device="cuda") elif pattern == "uniform": x = torch.rand(shape, device="cuda", generator=gen).mul_(2).sub_(1) else: x = torch.randn(shape, device="cuda", generator=gen) if pattern == "outliers": x.flatten()[::97].mul_(8) return (x * scale).to(torch.float16 if case["task"] == "dense_gemm" else torch.bfloat16) task = case["task"] if task in expansion.CONTRACTS: return expansion.make_inputs(case, rand, gen) if task in sparse.CONTRACTS: return sparse.make_inputs(case, rand, gen) if task == "gqa_attention": b, h, hk, q, k, d = (case[x] for x in ("batch", "heads", "kv_heads", "q_len", "kv_len", "head_dim")) if h % hk or (case["causal"] and q != k): raise ValueError("GQA requires divisible heads; causal cases require q_len == kv_len") return (rand((b, h, q, d)), rand((b, hk, k, d)), rand((b, hk, k, d)), case["causal"]) if task == "fp8_gemm": m, k, n = (case[x] for x in ("m", "k", "n")) if k % 16 or n % 16: raise ValueError("FP8 contract requires K and N divisible by 16") # B is column-major, including for the reference and candidate. a = rand((m, k)).to(torch.float8_e4m3fn) b = rand((n, k)).to(torch.float8_e4m3fn).t() sa = torch.tensor(1 / math.sqrt(k), device="cuda", dtype=torch.float32) sb = torch.tensor(0.5 if pattern == "uniform" else 1.25, device="cuda", dtype=torch.float32) return a, b, sa, sb if task == "fused_mlp": m, h, i = (case[x] for x in ("m", "hidden", "intermediate")) return rand((m, h)), rand((h, 2 * i), 1 / math.sqrt(h)), rand((i, h), 1 / math.sqrt(i)) return extended.make_inputs(case, rand, gen) def reference(task, *args): if task in expansion.CONTRACTS: return expansion.reference(task, *args) if task in sparse.CONTRACTS: return sparse.reference(task, *args) if task in extended.CONTRACTS: return extended.reference(task, *args) if task == "gqa_attention": q, k, v, causal = args b, h, qn, d = q.shape hk, kn = k.shape[1:3] # Explicit grouped attention, FP32 accumulation, bounded score workspace. q = q.float().reshape(b, hk, h // hk, qn, d) k, v = k.float().unsqueeze(2), v.float().unsqueeze(2) chunks = [] for start in range(0, qn, 64): stop = min(start + 64, qn) scores = (q[..., start:stop, :] @ k.transpose(-1, -2)) / math.sqrt(d) if causal: mask = torch.arange(kn, device=q.device)[None, :] > torch.arange(start, stop, device=q.device)[:, None] scores.masked_fill_(mask, -torch.inf) chunks.append(torch.softmax(scores, dim=-1) @ v) return torch.cat(chunks, dim=-2).reshape(b, h, qn, d).to(torch.bfloat16) if task == "fp8_gemm": a, b, sa, sb = args return ((a.float() * sa) @ (b.float() * sb)).to(torch.bfloat16) x, w_up, w_down = args # The up-projection is BF16 at the operator boundary; activation may fuse. gate, up = (x.float() @ w_up.float()).to(torch.bfloat16).float().chunk(2, dim=-1) hidden = (F.silu(gate) * up).to(torch.bfloat16).float() return (hidden @ w_down.float()).to(torch.bfloat16) def make_integration(case, inputs, seed): """Frozen projection/residual/RMS block. This is NOT full-model E2E.""" gen = torch.Generator(device="cuda").manual_seed(seed) task = case["task"] if task in expansion.CONTRACTS: sample = expansion.output_view(task, reference(task, *inputs)) shape, width = sample.shape, sample.shape[-1] del sample elif task in sparse.CONTRACTS: sample = sparse.output_view(task, reference(task, *inputs)) shape, width = sample.shape, sample.shape[-1] del sample elif task in extended.CONTRACTS: sample = extended.output_view(task, reference(task, *inputs)) shape, width = sample.shape, sample.shape[-1] del sample elif task == "gqa_attention": b, h, q, d = inputs[0].shape shape, width = (b * q, h * d), h * d else: shape = (case["m"], case["n"] if task == "fp8_gemm" else case["hidden"]) width = shape[-1] # A fixed 512-dimensional projection bounds glue cost while exposing dilution. out_width = min(width, 512) weight = torch.randn((width, out_width), device="cuda", generator=gen, dtype=torch.bfloat16) / math.sqrt(width) residual = torch.randn((shape[0], out_width), device="cuda", generator=gen, dtype=torch.bfloat16) def glue(out): if task in expansion.CONTRACTS: out = expansion.output_view(task, out) elif task in sparse.CONTRACTS: out = sparse.output_view(task, out) elif task in extended.CONTRACTS: out = extended.output_view(task, out) elif task == "gqa_attention": out = out.transpose(1, 2).contiguous().view(shape) y = (out @ weight + residual).float() return (y * torch.rsqrt(y.square().mean(dim=-1, keepdim=True) + 1e-6)).to(torch.bfloat16) return glue def tensor_bytes(args): return sum(x.numel() * x.element_size() for x in args if isinstance(x, torch.Tensor))