"""Numerical check of loop_cot's decode channel against a fp64 reference. Separates three questions: 1. Is the ALGORITHM exact? (chunked top-k merge + renormalized weighted sum) -> run the whole thing in fp32 and compare to fp64: must be ~1e-6. 2. How much does bf16 perturb the arithmetic, holding the selected token set fixed? -> compare against a fp64 reference restricted to the same indices. 3. How much of the bf16 error is just tie-breaking at the top-k boundary (semantically harmless: it swaps the lowest-probability members)? """ import sys from pathlib import Path import torch sys.path.insert(0, str(Path(__file__).resolve().parent.parent)) from models.baselines.loop_cot import LoopedCoTTransformer # noqa: E402 torch.manual_seed(0) V, H, N, K = 4096, 256, 64, 17 CHUNK = 700 # deliberately not a divisor of V, and < V, to exercise merging cfg = dict(max_seq_len=64, n_layers=1, hidden_size=H, num_heads=2, expansion=4, init_type="lecun_normal", norm_type="pre", norm_eps=1e-6, pos_emb_type="rope", rope_theta=10000.0, cycles=4, cot_decode_topk=K, cot_decode_topk_chunk_size=CHUNK, cot_decode_readout="lm_head") m = LoopedCoTTransformer(cfg).cuda() scale = 3.7 def reference(hidden, W_out, W_in, indices=None): """fp64 decode; if `indices` given, restrict the softmax to that token set.""" h64, o64, i64 = hidden.double(), W_out.double(), W_in.double() logits = h64.reshape(-1, H) @ o64.T if indices is None: tv, ti = torch.topk(logits, k=K, dim=-1) else: ti = indices tv = torch.gather(logits, -1, ti) probs = torch.softmax(tv, dim=-1) return torch.einsum("nk,nkh->nh", probs, i64[ti]).reshape(hidden.shape) * scale, ti def impl_indices(hidden, W_out): """Top-k token set actually selected by the implementation's dtype path.""" md = hidden.dtype if hidden.dtype in (torch.float16, torch.bfloat16) else torch.float32 flat = hidden.to(md).reshape(-1, H) return torch.topk(flat @ W_out.to(md).T, k=K, dim=-1).indices print("=" * 62) CASES = [(torch.float32, 1.0, "fp32 (algorithm check)"), (torch.bfloat16, 1.0, "bf16, logits ~N(0,1) (adversarial: many near-ties)"), (torch.bfloat16, 8.0, "bf16, logits spread x8 (trained-LM-like separation)")] for dtype, spread, tag in CASES: W_out = (torch.randn(V, H, device="cuda", generator=torch.Generator("cuda").manual_seed(1)) / H**0.5).to(dtype) W_in = (torch.randn(V, H, device="cuda", generator=torch.Generator("cuda").manual_seed(2)) / H**0.5).to(dtype) hidden = (torch.randn(2, N, H, device="cuda", generator=torch.Generator("cuda").manual_seed(3)) * spread).to(dtype) got = m._decode(hidden, W_out, 1.0, W_in, scale) ref_free, ti_ref = reference(hidden, W_out, W_in) ti_impl = impl_indices(hidden, W_out) ref_same, _ = reference(hidden, W_out, W_in, indices=ti_impl) e_free = ((got.double() - ref_free).norm() / ref_free.norm()).item() e_same = ((got.double() - ref_same).norm() / ref_same.norm()).item() overlap = (ti_impl.sort(-1).values == ti_ref.sort(-1).values).float().mean().item() print(f"{tag}") print(f" rel err vs fp64 (free top-k) : {e_free:.2e}") print(f" rel err vs fp64 (same token set) : {e_same:.2e} <- pure arithmetic") print(f" top-k token-set agreement : {overlap*100:.2f}%") print("=" * 62) if dtype == torch.float32: algo_ok = e_free < 1e-5 elif spread > 1.0: # Separated logits: no boundary ties, so this is pure arithmetic. arith_ok = e_free < 2e-2 # Structural checks (dtype-independent) W_out = torch.randn(V, H, device="cuda", dtype=torch.bfloat16) / H**0.5 W_in = torch.randn(V, H, device="cuda", dtype=torch.bfloat16) / H**0.5 hidden = torch.randn(2, N, H, device="cuda", dtype=torch.bfloat16) got = m._decode(hidden, W_out, 1.0, W_in, scale) ti = impl_indices(hidden, W_out) eff = W_in.double()[ti] * scale lo, hi = eff.min(dim=1).values, eff.max(dim=1).values tol = 1e-2 * eff.abs().max() inside = (((got.double().reshape(-1, H) >= lo - tol) & (got.double().reshape(-1, H) <= hi + tol)).float().mean()).item() readout_matters = (m._decode(hidden, W_in, 1.0, W_in, scale) - got).norm().item() > 1e-3 writeback_matters = (m._decode(hidden, W_out, 1.0, W_out, scale) - got).norm().item() > 1e-3 print(f"decoded inside top-k convex hull : {inside*100:.2f}%") print(f"readout matrix is used : {readout_matters}") print(f"write-back matrix is separate : {writeback_matters}") ok = algo_ok and arith_ok and inside > 0.999 and readout_matters and writeback_matters print("DECODE_TEST_PASS" if ok else "DECODE_TEST_FAIL")