E2K-cd82-rl-internalization / numeric /gdn_numeric_test.py
ziyan98's picture
Add files using upload-large-folder tool
bbd7f1f verified
Raw History Blame Contribute Delete
6.74 kB
"""1-GPU numeric check of the pieces the 27B backward uses on this image:
fla chunk_gated_delta_rule (triton) fwd/bwd vs fla's naive reference, model dims (GQA: 16 k-heads,
48 v-heads), bf16, varlen; then TransformerEngine DotProductAttention fwd/bwd (cuDNN fused, thd,
head_dim 256). fla #640 was WRONG gradients (not NaN), so gradients are compared, not just NaN-checked."""
import os, sys, math, time, torch
print("torch", torch.__version__, "| cuda", torch.version.cuda, "| device", torch.cuda.get_device_name(0), flush=True)
import triton; print("triton", triton.__version__, triton.__file__, flush=True)
import fla; from fla.ops.gated_delta_rule import chunk_gated_delta_rule
from fla.ops.gated_delta_rule.naive import naive_chunk_gated_delta_rule
print("fla", getattr(fla, "__version__", "?"), flush=True)
torch.manual_seed(0)
dev = "cuda"
Hk, Hv, K, V = 16, 48, 128, 128 # Qwen3.8-27B linear attention dims (GQA ratio 3)
NG = Hv // Hk
def bad(t):
return bool(torch.isnan(t).any() or torch.isinf(t).any())
def rel(a, b):
return ((a.float() - b.float()).abs().max() / b.float().abs().max().clamp_min(1e-6)).item()
def reference(q, k, v, g, beta, T_list, cu):
"""fp32 naive per sequence (naive has no varlen / GQA): l2-normalised q/k, k-heads repeated per v-head."""
outs = []
for i in range(len(T_list)):
s, e = int(cu[i]), int(cu[i + 1])
qi = torch.nn.functional.normalize(q[:, s:e].float(), p=2, dim=-1).repeat_interleave(NG, dim=2)
ki = torch.nn.functional.normalize(k[:, s:e].float(), p=2, dim=-1).repeat_interleave(NG, dim=2)
oi = naive_chunk_gated_delta_rule(qi, ki, v[:, s:e].float(), g[:, s:e].float(), beta[:, s:e].float(), chunk_size=64)
outs.append(oi[0] if isinstance(oi, tuple) else oi)
return torch.cat(outs, dim=1)
def run_case(T_list, dtype, label, compare_grads=True):
B = 1; T = sum(T_list)
cu = torch.tensor([0] + list(torch.cumsum(torch.tensor(T_list), 0)), dtype=torch.long, device=dev)
q = torch.randn(B, T, Hk, K, device=dev, dtype=dtype, requires_grad=True)
k = torch.randn(B, T, Hk, K, device=dev, dtype=dtype, requires_grad=True)
v = torch.randn(B, T, Hv, V, device=dev, dtype=dtype, requires_grad=True)
g = (torch.rand(B, T, Hv, device=dev, dtype=torch.float32) * -0.5).to(dtype).requires_grad_(True) # log-gates in (-0.5, 0]
beta = torch.rand(B, T, Hv, device=dev, dtype=dtype).requires_grad_(True)
do = torch.randn(B, T, Hv, V, device=dev, dtype=dtype)
params = (("q", q), ("k", k), ("v", v), ("g", g), ("beta", beta))
torch.cuda.synchronize(); t0 = time.time()
o, _ = chunk_gated_delta_rule(q, k, v, g=g, beta=beta, initial_state=None, output_final_state=False,
use_qk_l2norm_in_kernel=True, cu_seqlens=cu)
(o * do).sum().backward()
torch.cuda.synchronize(); t1 = time.time()
kgrads = {n: t.grad.detach().clone() for n, t in params}
nan = {n: bad(gr) for n, gr in kgrads.items()}
print(f"[{label}] T={T} seqs={len(T_list)} dtype={dtype}: fwd+bwd {t1-t0:.2f}s | out nan/inf={bad(o)} | grad nan/inf={nan}", flush=True)
for _, t in params:
t.grad = None
result = {"nan": nan, "out_nan": bad(o)}
try:
oref = reference(q, k, v, g, beta, T_list, cu)
result["fwd_rel_err"] = rel(o, oref)
print(f" fwd max-rel-err vs naive fp32: {result['fwd_rel_err']:.3e}", flush=True)
if compare_grads:
(oref * do.float()).sum().backward()
errs = {n: rel(kgrads[n], t.grad) for n, t in params}
result["grad_rel_err"] = errs
print(f" grad max-rel-err vs naive fp32 autograd: " + ", ".join(f"{n}={e:.3e}" for n, e in errs.items()), flush=True)
except Exception as exc: # noqa: BLE001
print(f" reference failed: {type(exc).__name__}: {str(exc)[:200]}", flush=True)
del q, k, v, g, beta, do, o, kgrads
torch.cuda.empty_cache()
return result
results = {}
results["short_fp32"] = run_case([64, 200, 37], torch.float32, "short fp32")
results["short_bf16"] = run_case([64, 200, 37], torch.bfloat16, "short bf16")
results["mid_bf16"] = run_case([1500, 900], torch.bfloat16, "mid bf16")
results["model_bf16"] = run_case([8700, 9100, 400], torch.bfloat16, "model-shape bf16 (2 decisions + sft row)")
print("GDN RESULT:", results, flush=True)
# --- TransformerEngine fused attention, thd, head_dim 256, bf16, training ---
try:
import transformer_engine.pytorch as te
from transformer_engine.pytorch.attention import DotProductAttention
H, Hkv, D = 24 // 4, 4 // 4 or 1, 256 # per TP rank of 4: 6 heads, 1 kv head
for Tl in ([400, 300], [4000, 3500], [8700, 9100, 400]):
T = sum(Tl)
cu = torch.tensor([0] + list(torch.cumsum(torch.tensor(Tl), 0)), dtype=torch.int32, device=dev)
dpa = DotProductAttention(num_attention_heads=H, kv_channels=D, num_gqa_groups=Hkv, attention_dropout=0.0,
qkv_format="thd", attn_mask_type="padding_causal").to(dev)
q = torch.randn(T, H, D, device=dev, dtype=torch.bfloat16, requires_grad=True)
k = torch.randn(T, Hkv, D, device=dev, dtype=torch.bfloat16, requires_grad=True)
v = torch.randn(T, Hkv, D, device=dev, dtype=torch.bfloat16, requires_grad=True)
out = dpa(q, k, v, cu_seqlens_q=cu, cu_seqlens_kv=cu, max_seqlen_q=max(Tl), max_seqlen_kv=max(Tl))
do = torch.randn_like(out)
(out * do).sum().backward()
fused = {n: t.grad.detach().clone() for n, t in (("q", q), ("k", k), ("v", v))}
print(f"TE fused attention thd hd256 T={T}: out nan {bad(out)} | grad nan", {n: bad(t) for n, t in fused.items()}, flush=True)
# unfused reference per sequence (fp32 sdpa, causal)
for t in (q, k, v):
t.grad = None
ref_out = []
for i in range(len(Tl)):
s, e = int(cu[i]), int(cu[i + 1])
qi = q[s:e].float().transpose(0, 1) # [H, L, D]
ki = k[s:e].float().transpose(0, 1).expand(H, -1, -1)
vi = v[s:e].float().transpose(0, 1).expand(H, -1, -1)
oi = torch.nn.functional.scaled_dot_product_attention(qi, ki, vi, is_causal=True)
ref_out.append(oi.transpose(0, 1))
ref = torch.cat(ref_out, dim=0)
(ref * do.float()).sum().backward()
print(f" fwd rel err {rel(out, ref):.3e} | grad rel err " + ", ".join(f"{n}={rel(fused[n], t.grad):.3e}" for n, t in (("q", q), ("k", k), ("v", v))), flush=True)
del q, k, v, out, do, fused, ref, dpa
torch.cuda.empty_cache()
except Exception as exc:
print("TE attention check failed to run:", type(exc).__name__, str(exc)[:300], flush=True)
print("DONE", flush=True)