Skip to content

Fuse QK RMSNorm into Triton learnable 2D RoPE kernels - #1289

Open
zsqdx wants to merge 1 commit into
lightvector:masterfrom
zsqdx:train-fused-rope-qkn
Open

zsqdx wants to merge 1 commit into
lightvector:masterfrom
zsqdx:train-fused-rope-qkn

Conversation

@zsqdx

@zsqdx zsqdx commented Nov 28, 2026

Copy link
Copy Markdown
Contributor

Summary

When attention_qk_norm is enabled alongside KATAGO_FUSED_ROPE_BACKWARD, applying Q/K RMSNorm as separate ops adds extra memory-bound read/write passes over Q and K in both forward and backward and saves an extra copy of rotated Q and K. Since 2D RoPE rotation preserves vector norm, we can apply the per-head RMSNorm in registers inside the existing RoPE Triton kernel structure.

  • Adds katago::rope_qkn_forward / katago::rope_qkn_backward and learnable_rope_qkn in python/katago/train/fused_rope.py, mirroring learnable_rope_qkv without modifying the non-QK-norm kernels.
  • Wires it in TransformerAttentionBlock behind KATAGO_FUSED_QK_NORM (default 1), automatically falling back whenever KATAGO_FUSED_ROPE_BACKWARD=0, use_qk_norm=False, or single-graph compile disables fused RoPE. Compatible with torch.compile per-block trunk and -attn-logit-penalty-cap.
  • Adds test_fused_rope_qkn_matches_autograd in python/tests/test_fused_kernels.py covering fp32, fp16 (including odd batch size), and bf16 (v_head_dim != head_dim, small board).

Numerics & Measurements

Everything inside the kernel is computed in fp32 from the packed QKV projection and rounded once on store (the separate-op path rounds rotated Q/K before normalizing, so the two differ only at fp16/bf16 rounding level).

Measured on RTX PRO 6000 Blackwell (b13c768h12f896nbt3tflrsqkn-fson-silu, batch 128, FP16 AMP + Aurora + per-block compile):

  • Throughput: 790.5 → 830.4 samples/s (+5.0%)
  • Peak VRAM: 27.4 → 24.7 GB (-2.7 GB) (enabling batch 128 → 144 under a 30 GB cap)
  • Parity: standalone fp16/bf16 unit check matched fp64 reference (~2e-4 rel L2 error in fp16, matching the separate-op path); 800-batch paired seeded training run had max relative loss diff 8.4e-6 (vs 6.3e-6 baseline run-to-run noise).

(Note: ported cleanly onto current master and syntax-checked locally on macOS; the newly added pytest case in test_fused_kernels.py mirrors the GPU unit check above and has not yet been re-run via pytest on a CUDA box after porting.)

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant