Download code/autoslm/engine/rope.py from DavidBShan/rope-kernel-v2: direct link, hf CLI and curl.
- Browser
- Download file 14.3 kB
-
https://huggingface.co/datasets/DavidBShan/rope-kernel-v2/resolve/main/code/autoslm/engine/rope.py
- Command line
-
hf download hf://datasets/DavidBShan/rope-kernel-v2/code/autoslm/engine/rope.py
-
curl -L -o rope.py https://huggingface.co/datasets/DavidBShan/rope-kernel-v2/resolve/main/code/autoslm/engine/rope.py
14.3 kB
| """Custom fused Triton RoPE kernel for Qwen3.5/3.6 full-attention layers. | |
| Liger ships a RoPE kernel but its qwen3_5 patcher *refuses* to apply it | |
| (``raise NotImplementedError`` "due to hybrid attention: Gated DeltaNet + Gated | |
| Attention") — the GDN layers don't call ``apply_rotary_pos_emb`` at all, only the | |
| full-attention layers do, and Liger's blanket patch couldn't target just those. | |
| This module sidesteps that by monkeypatching the module-level | |
| ``transformers.models.qwen3_5.modeling_qwen3_5.apply_rotary_pos_emb`` function | |
| itself — which ONLY the ``Qwen3_5Attention`` layers call — so the GDN path is | |
| untouched. The HF eager version is heavily unfused: ``rotate_half`` allocates a | |
| full ``cat([-x2, x1])`` tensor and the rotation is ~8 separate elementwise | |
| kernels + intermediates per attention layer. We fuse the whole rotation into one | |
| Triton kernel (forward + backward), eliminating those launches/allocations. | |
| Correctness is gated by a live-GPU numeric self-test (loss + grad vs the eager | |
| reference within tolerance); ANY import/compile/self-test failure leaves the | |
| eager path untouched — correctness over speed. Opt-in via AUTOSLM_ROPE_KERNEL=1. | |
| Semantics matched exactly to modeling_qwen3_5.apply_rotary_pos_emb: | |
| rotate_half(x) = cat(-x[d/2:], x[:d/2]) # GPT-NeoX / non-interleaved | |
| q_embed = (q_rot * cos) + (rotate_half(q_rot) * sin); q_pass kept as-is | |
| with rotary_dim = cos.shape[-1] possibly < head_dim (the tail is passed through), | |
| cos/sin of shape [batch, seq, rotary_dim] (broadcast over heads). | |
| """ | |
| from __future__ import annotations | |
| import os | |
| # Populated by install_qwen35_rope/benchmark so the worker can fold the measured speedup | |
| # into metrics.json's `notes` (RunPod doesn't persist worker stdout, but metrics.json is | |
| # always uploaded). Empty {} means the kernel was not engaged this run. | |
| RESULT: dict = {} | |
| def _enabled() -> bool: | |
| return os.environ.get("AUTOSLM_ROPE_KERNEL", "0").strip().lower() not in ( | |
| "0", | |
| "false", | |
| "no", | |
| "off", | |
| "none", | |
| "", | |
| ) | |
| def _build_kernels(): | |
| """Import torch/triton and define the fused RoPE forward+backward kernels + the | |
| autograd Function. Returns ``apply_fn`` (HF-signature drop-in) or raises on any | |
| import/compile problem (the caller treats a raise as "keep eager").""" | |
| import torch | |
| import triton | |
| import triton.language as tl | |
| def _rope_fwd_kernel( | |
| x_ptr, cos_ptr, sin_ptr, out_ptr, | |
| H_T, T, head_dim, rotary_dim, half, | |
| x_row_stride, cs_row_stride, | |
| BLOCK: tl.constexpr, | |
| ): | |
| # one program == one [head_dim] vector for a single (batch, head, token) | |
| pid = tl.program_id(0) | |
| b = pid // H_T | |
| t = pid % T | |
| cs_row = b * T + t | |
| offs = tl.arange(0, BLOCK) | |
| mask_half = offs < half | |
| # the two rotary halves of this row | |
| x1 = tl.load(x_ptr + pid * x_row_stride + offs, mask=mask_half, other=0.0) | |
| x2 = tl.load(x_ptr + pid * x_row_stride + half + offs, mask=mask_half, other=0.0) | |
| cos1 = tl.load(cos_ptr + cs_row * cs_row_stride + offs, mask=mask_half, other=0.0) | |
| sin1 = tl.load(sin_ptr + cs_row * cs_row_stride + offs, mask=mask_half, other=0.0) | |
| cos2 = tl.load(cos_ptr + cs_row * cs_row_stride + half + offs, mask=mask_half, other=0.0) | |
| sin2 = tl.load(sin_ptr + cs_row * cs_row_stride + half + offs, mask=mask_half, other=0.0) | |
| # rotate_half: out1 = x1*cos1 - x2*sin1 ; out2 = x2*cos2 + x1*sin2 | |
| out1 = x1 * cos1 - x2 * sin1 | |
| out2 = x2 * cos2 + x1 * sin2 | |
| tl.store(out_ptr + pid * x_row_stride + offs, out1, mask=mask_half) | |
| tl.store(out_ptr + pid * x_row_stride + half + offs, out2, mask=mask_half) | |
| # pass-through tail [rotary_dim : head_dim] | |
| if head_dim > rotary_dim: | |
| poffs = tl.arange(0, BLOCK) | |
| pmask = poffs < (head_dim - rotary_dim) | |
| xp = tl.load(x_ptr + pid * x_row_stride + rotary_dim + poffs, mask=pmask, other=0.0) | |
| tl.store(out_ptr + pid * x_row_stride + rotary_dim + poffs, xp, mask=pmask) | |
| def _rope_bwd_kernel( | |
| g_ptr, cos_ptr, sin_ptr, dx_ptr, | |
| H_T, T, head_dim, rotary_dim, half, | |
| g_row_stride, cs_row_stride, | |
| BLOCK: tl.constexpr, | |
| ): | |
| pid = tl.program_id(0) | |
| b = pid // H_T | |
| t = pid % T | |
| cs_row = b * T + t | |
| offs = tl.arange(0, BLOCK) | |
| mask_half = offs < half | |
| g1 = tl.load(g_ptr + pid * g_row_stride + offs, mask=mask_half, other=0.0) | |
| g2 = tl.load(g_ptr + pid * g_row_stride + half + offs, mask=mask_half, other=0.0) | |
| cos1 = tl.load(cos_ptr + cs_row * cs_row_stride + offs, mask=mask_half, other=0.0) | |
| sin1 = tl.load(sin_ptr + cs_row * cs_row_stride + offs, mask=mask_half, other=0.0) | |
| cos2 = tl.load(cos_ptr + cs_row * cs_row_stride + half + offs, mask=mask_half, other=0.0) | |
| sin2 = tl.load(sin_ptr + cs_row * cs_row_stride + half + offs, mask=mask_half, other=0.0) | |
| # transpose of the forward (orthogonal rotation): | |
| # dx1 = g1*cos1 + g2*sin2 ; dx2 = -g1*sin1 + g2*cos2 | |
| dx1 = g1 * cos1 + g2 * sin2 | |
| dx2 = -g1 * sin1 + g2 * cos2 | |
| tl.store(dx_ptr + pid * g_row_stride + offs, dx1, mask=mask_half) | |
| tl.store(dx_ptr + pid * g_row_stride + half + offs, dx2, mask=mask_half) | |
| if head_dim > rotary_dim: | |
| poffs = tl.arange(0, BLOCK) | |
| pmask = poffs < (head_dim - rotary_dim) | |
| gp = tl.load(g_ptr + pid * g_row_stride + rotary_dim + poffs, mask=pmask, other=0.0) | |
| tl.store(dx_ptr + pid * g_row_stride + rotary_dim + poffs, gp, mask=pmask) | |
| def _next_pow2(n: int) -> int: | |
| p = 1 | |
| while p < n: | |
| p <<= 1 | |
| return max(p, 1) | |
| def _rope_one(x, cos, sin, forward: bool): | |
| # x: [B, H, T, D] (contiguous), cos/sin: [B, T, rotary_dim] | |
| B, H, T, D = x.shape | |
| rotary_dim = cos.shape[-1] | |
| half = rotary_dim // 2 | |
| x = x.contiguous() | |
| out = torch.empty_like(x) | |
| xf = x.view(B * H * T, D) | |
| of = out.view(B * H * T, D) | |
| cosf = cos.contiguous().view(B * T, rotary_dim) | |
| sinf = sin.contiguous().view(B * T, rotary_dim) | |
| BLOCK = _next_pow2(max(half, D - rotary_dim, 1)) | |
| grid = (B * H * T,) | |
| kern = _rope_fwd_kernel if forward else _rope_bwd_kernel | |
| kern[grid]( | |
| xf, cosf, sinf, of, | |
| H * T, T, D, rotary_dim, half, | |
| xf.stride(0), cosf.stride(0), | |
| BLOCK=BLOCK, | |
| ) | |
| return out | |
| class _RoPEFunction(torch.autograd.Function): | |
| def forward(ctx, q, k, cos, sin): | |
| ctx.save_for_backward(cos, sin) | |
| q_embed = _rope_one(q, cos, sin, forward=True) | |
| k_embed = _rope_one(k, cos, sin, forward=True) | |
| return q_embed, k_embed | |
| def backward(ctx, gq, gk): | |
| cos, sin = ctx.saved_tensors | |
| dq = _rope_one(gq.contiguous(), cos, sin, forward=False) | |
| dk = _rope_one(gk.contiguous(), cos, sin, forward=False) | |
| return dq, dk, None, None | |
| def apply_fn(q, k, cos, sin, unsqueeze_dim=1): | |
| # cos/sin arrive as [B, T, rotary_dim]; HF unsqueezes to broadcast over heads. | |
| # Our kernel broadcasts over heads internally, so use cos/sin as-is ([B,T,rd]). | |
| # Fall back to eager for any shape we don't handle (interleaved/odd ranks). | |
| if q.dim() != 4 or cos.dim() != 3 or (cos.shape[-1] % 2) != 0: | |
| return _eager_apply(q, k, cos, sin, unsqueeze_dim) | |
| return _RoPEFunction.apply(q, k, cos, sin) | |
| return apply_fn | |
| def _eager_apply(q, k, cos, sin, unsqueeze_dim=1): | |
| """The exact HF reference (used as the self-test oracle and the shape fallback).""" | |
| import torch | |
| cos_u = cos.unsqueeze(unsqueeze_dim) | |
| sin_u = sin.unsqueeze(unsqueeze_dim) | |
| rd = cos_u.shape[-1] | |
| q_rot, q_pass = q[..., :rd], q[..., rd:] | |
| k_rot, k_pass = k[..., :rd], k[..., rd:] | |
| def rh(x): | |
| x1 = x[..., : x.shape[-1] // 2] | |
| x2 = x[..., x.shape[-1] // 2 :] | |
| return torch.cat((-x2, x1), dim=-1) | |
| q_embed = torch.cat([(q_rot * cos_u) + (rh(q_rot) * sin_u), q_pass], dim=-1) | |
| k_embed = torch.cat([(k_rot * cos_u) + (rh(k_rot) * sin_u), k_pass], dim=-1) | |
| return q_embed, k_embed | |
| def self_test(apply_fn, *, head_dim=128, rotary_dim=128, dtype=None) -> bool: | |
| """Numeric parity of the fused kernel vs eager HF apply_rotary_pos_emb, on the | |
| live GPU: forward q/k AND backward dq/dk. Returns True iff within tolerance.""" | |
| import torch | |
| if not torch.cuda.is_available(): | |
| return False | |
| dtype = dtype or torch.bfloat16 | |
| B, Hh, T = 2, 4, 64 | |
| dev = "cuda" | |
| torch.manual_seed(0) | |
| q = torch.randn(B, Hh, T, head_dim, device=dev, dtype=dtype, requires_grad=True) | |
| k = torch.randn(B, Hh, T, head_dim, device=dev, dtype=dtype, requires_grad=True) | |
| pos = torch.arange(T, device=dev) | |
| inv = 1.0 / (10000 ** (torch.arange(0, rotary_dim // 2, device=dev).float() / (rotary_dim // 2))) | |
| ang = pos[:, None].float() * inv[None, :] | |
| emb = torch.cat([ang, ang], dim=-1) # [T, rotary_dim], duplicated halves (standard RoPE) | |
| cos = emb.cos()[None].expand(B, T, rotary_dim).to(dtype).contiguous() | |
| sin = emb.sin()[None].expand(B, T, rotary_dim).to(dtype).contiguous() | |
| qe_ref, ke_ref = _eager_apply(q, k, cos, sin) | |
| (qe_ref.float().square().mean() + ke_ref.float().square().mean()).backward() | |
| dq_ref, dk_ref = q.grad.clone(), k.grad.clone() | |
| q.grad = None | |
| k.grad = None | |
| qe, ke = apply_fn(q, k, cos, sin) | |
| (qe.float().square().mean() + ke.float().square().mean()).backward() | |
| dq, dk = q.grad.clone(), k.grad.clone() | |
| def close(a, b, atol=2e-2, rtol=2e-2): | |
| return torch.allclose(a.float(), b.float(), atol=atol, rtol=rtol) | |
| ok = ( | |
| close(qe, qe_ref) and close(ke, ke_ref) and close(dq, dq_ref) and close(dk, dk_ref) | |
| ) | |
| if not ok: | |
| print( | |
| "[rope] self-test FAILED " | |
| f"(fwd_q={close(qe, qe_ref)} fwd_k={close(ke, ke_ref)} " | |
| f"bwd_q={close(dq, dq_ref)} bwd_k={close(dk, dk_ref)}) -> keeping eager", | |
| flush=True, | |
| ) | |
| return ok | |
| def benchmark(apply_fn, *, head_dim=128, rotary_dim=128, n_heads=16, seq=4096, iters=50) -> None: | |
| """Time eager HF vs the fused kernel (forward+backward) at Qwen-attention shapes, | |
| on the live GPU; prints the speedup. Diagnostic only — never raises.""" | |
| import torch | |
| try: | |
| if not torch.cuda.is_available(): | |
| return | |
| dev = "cuda" | |
| dt = torch.bfloat16 | |
| B = 1 | |
| pos = torch.arange(seq, device=dev) | |
| inv = 1.0 / (10000 ** (torch.arange(0, rotary_dim // 2, device=dev).float() / (rotary_dim // 2))) | |
| ang = pos[:, None].float() * inv[None, :] | |
| emb = torch.cat([ang, ang], dim=-1) | |
| cos = emb.cos()[None].expand(B, seq, rotary_dim).to(dt).contiguous() | |
| sin = emb.sin()[None].expand(B, seq, rotary_dim).to(dt).contiguous() | |
| def run(fn): | |
| q = torch.randn(B, n_heads, seq, head_dim, device=dev, dtype=dt, requires_grad=True) | |
| k = torch.randn(B, n_heads, seq, head_dim, device=dev, dtype=dt, requires_grad=True) | |
| qe, ke = fn(q, k, cos, sin) | |
| (qe.float().square().mean() + ke.float().square().mean()).backward() | |
| for _ in range(5): # warmup (Triton JIT + autotune) | |
| run(_eager_apply) | |
| run(apply_fn) | |
| torch.cuda.synchronize() | |
| def timed(fn): | |
| s = torch.cuda.Event(enable_timing=True) | |
| e = torch.cuda.Event(enable_timing=True) | |
| torch.cuda.synchronize() | |
| s.record() | |
| for _ in range(iters): | |
| run(fn) | |
| e.record() | |
| torch.cuda.synchronize() | |
| return s.elapsed_time(e) / iters # ms/iter | |
| t_eager = timed(_eager_apply) | |
| t_kernel = timed(apply_fn) | |
| speedup = t_eager / t_kernel if t_kernel > 0 else 0.0 | |
| RESULT.update( | |
| { | |
| "head_dim": head_dim, | |
| "heads": n_heads, | |
| "seq": seq, | |
| "eager_ms": round(t_eager, 4), | |
| "kernel_ms": round(t_kernel, 4), | |
| "speedup": round(speedup, 3), | |
| } | |
| ) | |
| print( | |
| f"[rope][bench] head_dim={head_dim} heads={n_heads} seq={seq} fwd+bwd: " | |
| f"eager={t_eager:.3f}ms kernel={t_kernel:.3f}ms -> {speedup:.2f}x", | |
| flush=True, | |
| ) | |
| except Exception as e: | |
| RESULT["bench_error"] = f"{type(e).__name__}: {e}" | |
| print(f"[rope][bench] skipped: {e}", flush=True) | |
| def install_qwen35_rope(run_benchmark: bool = True) -> bool: | |
| """Patch ``apply_rotary_pos_emb`` in the qwen3_5/qwen3_6 modeling modules with the | |
| fused Triton kernel — IFF AUTOSLM_ROPE_KERNEL=1 and the live-GPU self-test passes. | |
| Patches the module-level function only the full-attention layers call, so the GDN | |
| layers are untouched. Never raises: any failure leaves the eager path in place. | |
| Returns True iff the kernel was installed.""" | |
| if not _enabled(): | |
| return False | |
| try: | |
| apply_fn = _build_kernels() | |
| except Exception as e: | |
| print(f"[rope] kernel build failed ({type(e).__name__}: {e}); keeping eager", flush=True) | |
| return False | |
| if not self_test(apply_fn): | |
| return False | |
| patched = [] | |
| for mod_name in ("qwen3_5", "qwen3_6"): | |
| try: | |
| import importlib | |
| mod = importlib.import_module(f"transformers.models.{mod_name}.modeling_{mod_name}") | |
| except Exception: | |
| continue | |
| if hasattr(mod, "apply_rotary_pos_emb"): | |
| mod.apply_rotary_pos_emb = apply_fn | |
| patched.append(mod_name) | |
| if not patched: | |
| print("[rope] no qwen3_5/3_6 modeling module to patch; keeping eager", flush=True) | |
| return False | |
| RESULT.update({"installed": True, "self_test": "passed", "patched": patched}) | |
| print(f"[rope] fused Triton RoPE installed on {patched} (self-test passed)", flush=True) | |
| if run_benchmark: | |
| benchmark(apply_fn) | |
| return True | |