E2K-cd82-rl-internalization / numeric /gdn_plugin_path_test.py
ziyan98's picture
Add files using upload-large-folder tool
bbd7f1f verified
Raw History Blame Contribute Delete
6.37 kB
"""The exact kernel paths slime's qwen3_5 plugin uses in the Megatron forward, vs torch references:
(1) fla chunk_gated_delta_rule with H=HV=48 (q/k repeat_interleaved) + packed cu_seqlens vs HF torch_chunk_gated_delta_rule;
(2) fla ShortConvolution(silu) vs F.conv1d+silu; (3) fla FusedRMSNormGated vs HF Qwen3_5RMSNormGated;
(4) TE fused partial RoPE on thd (rotary_percent 0.25) vs Megatron's unfused reference."""
import os, sys, torch, torch.nn.functional as F
import triton; print("triton", triton.__version__, triton.__file__, flush=True)
dev = "cuda"; torch.manual_seed(0)
def rel(a, b): return ((a.float() - b.float()).abs().max() / b.float().abs().max().clamp_min(1e-6)).item()
def bad(t): return bool(torch.isnan(t).any() or torch.isinf(t).any())
# ---------- (1) GDN, plugin path ----------
from fla.ops.gated_delta_rule import chunk_gated_delta_rule
from transformers.models.qwen3_5.modeling_qwen3_5 import torch_chunk_gated_delta_rule
Hk, Hv, K, V = 16, 48, 128, 128
for Tl in ([300, 200], [9000, 400], [10275, 512]):
T = sum(Tl); cu = torch.tensor([0] + list(torch.cumsum(torch.tensor(Tl), 0)), dtype=torch.long, device=dev)
q = torch.randn(1, T, Hk, K, device=dev, dtype=torch.bfloat16); k = torch.randn(1, T, Hk, K, device=dev, dtype=torch.bfloat16)
v = torch.randn(1, T, Hv, V, device=dev, dtype=torch.bfloat16)
g = (-torch.rand(1, T, Hv, device=dev) * 0.5).float(); beta = torch.rand(1, T, Hv, device=dev, dtype=torch.bfloat16)
qr, kr = q.repeat_interleave(Hv // Hk, dim=2), k.repeat_interleave(Hv // Hk, dim=2) # plugin: H = HV = 48
with torch.no_grad():
o_plugin, _ = chunk_gated_delta_rule(qr, kr, v, g=g.to(v.dtype), beta=beta, initial_state=None, output_final_state=False, use_qk_l2norm_in_kernel=True, cu_seqlens=cu)
o_gva, _ = chunk_gated_delta_rule(q, k, v, g=g.to(v.dtype), beta=beta, initial_state=None, output_final_state=False, use_qk_l2norm_in_kernel=True, cu_seqlens=cu) # sglang-like GVA path
refs = []
for i in range(len(Tl)):
s, e = int(cu[i]), int(cu[i + 1])
qi = F.normalize(qr[:, s:e].float(), p=2, dim=-1); ki = F.normalize(kr[:, s:e].float(), p=2, dim=-1)
r = torch_chunk_gated_delta_rule(qi, ki, v[:, s:e].float(), g[:, s:e], beta[:, s:e].float(), chunk_size=64, use_qk_l2norm_in_kernel=False)
refs.append(r[0] if isinstance(r, tuple) else r)
ref = torch.cat(refs, dim=1)
print(f"GDN {Tl}: plugin(H=HV=48) rel err {rel(o_plugin, ref):.2e} bad={bad(o_plugin)} | GVA(H=16,HV=48) rel err {rel(o_gva, ref):.2e} | plugin-vs-GVA {rel(o_plugin, o_gva):.2e}", flush=True)
# per-sequence error (does the 2nd packed segment go wrong?)
per = [f"seq{i}:{rel(o_plugin[:, int(cu[i]):int(cu[i+1])], ref[:, int(cu[i]):int(cu[i+1])]):.1e}" for i in range(len(Tl))]
print(" per-seq:", " ".join(per), flush=True)
# ---------- (2) ShortConvolution ----------
from fla.modules import ShortConvolution
D = Hk * K * 2 + Hv * V # conv over [q|k|v] = 4096+6144 = 10240
conv = ShortConvolution(hidden_size=D, kernel_size=4, activation="silu").to(dev, torch.bfloat16)
for Tl in ([300, 200], [9000, 400]):
T = sum(Tl); cu = torch.tensor([0] + list(torch.cumsum(torch.tensor(Tl), 0)), dtype=torch.int32, device=dev)
x = torch.randn(1, T, D, device=dev, dtype=torch.bfloat16)
with torch.no_grad():
try:
y = conv(x, cu_seqlens=cu); y = y[0] if isinstance(y, tuple) else y
except TypeError:
y = conv(x); y = y[0] if isinstance(y, tuple) else y
w = conv.weight.float() # [D,1,4]
refs = []
for i in range(len(Tl)):
s, e = int(cu[i]), int(cu[i + 1])
xi = x[:, s:e].float().transpose(1, 2) # [1,D,L]
yi = F.conv1d(F.pad(xi, (3, 0)), w, groups=D)
if conv.bias is not None: yi = yi + conv.bias.float()[None, :, None]
refs.append(F.silu(yi).transpose(1, 2))
ref = torch.cat(refs, dim=1)
print(f"ShortConv {Tl}: rel err {rel(y, ref):.2e} bad={bad(y)}", flush=True)
# ---------- (3) gated RMSNorm ----------
from fla.modules import FusedRMSNormGated
from transformers.models.qwen3_5.modeling_qwen3_5 import Qwen3_5RMSNormGated
n_fla = FusedRMSNormGated(V, eps=1e-6, activation="silu").to(dev, torch.bfloat16); n_hf = Qwen3_5RMSNormGated(V, eps=1e-6).to(dev, torch.bfloat16)
with torch.no_grad():
wgt = torch.rand(V, device=dev) + 0.5; n_fla.weight.copy_(wgt); n_hf.weight.copy_(wgt)
x = torch.randn(1, 2000, Hv, V, device=dev, dtype=torch.bfloat16); z = torch.randn_like(x)
yf = n_fla(x, z); yh = n_hf(x, z)
print(f"RMSNormGated: fla vs HF rel err {rel(yf, yh):.2e} | HF uses (1+w)? {rel(yh, (F.rms_norm(x.float(), (V,), eps=1e-6) * (1 + wgt)) * F.silu(z.float())):.2e} plain w? {rel(yh, (F.rms_norm(x.float(), (V,), eps=1e-6) * wgt) * F.silu(z.float())):.2e}", flush=True)
# ---------- (4) TE fused partial RoPE on thd ----------
try:
from megatron.core.models.common.embeddings.rotary_pos_embedding import RotaryEmbedding
from megatron.core.models.common.embeddings import rope_utils
rot = RotaryEmbedding(kv_channels=256, rotary_percent=0.25, rotary_base=10000000, rotary_interleaved=False)
for Tl in ([300, 200], [9000, 400], [10275, 512]):
T = sum(Tl); cu = torch.tensor([0] + list(torch.cumsum(torch.tensor(Tl), 0)), dtype=torch.int32, device=dev)
freqs = rot(max(Tl)).to(dev) # [max_seqlen,1,1,64]
t = torch.randn(T, 1, 24, 256, device=dev, dtype=torch.bfloat16)
fused = rope_utils.fused_apply_rotary_pos_emb_thd(t, cu, freqs)
# unfused reference: per-sequence bshd rope on the first 64 dims, positions restart per sequence
refs = []
for i in range(len(Tl)):
s, e = int(cu[i]), int(cu[i + 1])
refs.append(rope_utils._apply_rotary_pos_emb_bshd(t[s:e], freqs[: e - s], rotary_interleaved=False, multi_latent_attention=False, mscale=1.0))
ref = torch.cat(refs, dim=0)
print(f"RoPE thd {Tl}: fused vs unfused rel err {rel(fused, ref):.2e} bad={bad(fused)} | rot dims err {rel(fused[..., :64], ref[..., :64]):.2e} pass-through dims err {rel(fused[..., 64:], ref[..., 64:]):.2e}", flush=True)
except Exception as exc:
import traceback; traceback.print_exc(); print("RoPE test failed:", exc, flush=True)
print("DONE", flush=True)