Kernels
3v324v23 Claude Opus 4.6 (1M context) commited on
Commit
f61868b
·
1 Parent(s): 3f2678c

feat: MLA RoPE Triton kernels (port from llm-training)

Browse files

Ports Motif3 GDLAttention RoPE optimization kernels from llm-training
to the activation package. Python/Triton-only addition — no CUDA
recompilation needed.

## Kernels added (fused_rope.py)

### _rope_fwd_kernel / _rope_bwd_kernel (Phase 1)
Generic RoPE on [B*S, H, rope_dim] with sin/cos direct multiplication,
interleaved → contiguous layout change inside kernel. Eliminates
view_as_complex + complex_mul + reorder_headdim pattern. Used for k_pe
(1 head, standalone) after Phase 4 landed (Q path uses the in-place
variant below).

### _kv_rope_fwd_kernel (Phase 2)
Fused KV split + k_pe RoPE broadcast + cat. Reads kv_latent (k_nope+v)
and k_pe (1 head, already RoPE'd), outputs key=[k_nope||k_pe_broadcast]
and value. k_pe broadcast across heads happens in register — no
memory copy.

### _q_rope_inplace_fwd_kernel / _q_rope_bwd_kernel (Phase 4)
In-place Q RoPE. Modifies q[..., nope_dim:] from interleaved to
contiguous format without touching the nope section. Eliminates the
subsequent cat(q_nope, q_pe) shuffler. Uses torch.library.custom_op
with mutates_args=("q",) + ctx.mark_dirty(q) for autograd safety.

Distinguishes from the reverted Phase 3 (out-of-place) which copied the
nope section into a new buffer — that cost more than the cat it
replaced. In-place avoids that by never touching nope.

### Autotune (Phase 5)
All kernels autotune over BLOCK_H × num_warps × num_stages = 128
configs via _rope_autotune_configs(). Backward kernels gained ~30%
from this vs BLOCK_H-only search; forward ~5-10%. _kv_rope_fwd_kernel
was already at ~73% HBM BW so showed no improvement.

## Public API

from activation import (
fused_apply_rope, # generic RoPE (Phase 1)
fused_q_rope_inplace, # Q in-place RoPE (Phase 4)
fused_kv_split_rope_cat, # KV split+RoPE+cat (Phase 2)
)

## Measured perf (motif3_seq, B=4, S=4096, n_layers=6, B200)

Attention block per layer (fwd+bwd), vs baseline (PyTorch native MLA):

Phase 0 (baseline) 14,730 µs (reference)
Phase 1 (Triton RoPE) 13,046 (-11.4%)
Phase 2 (KV fused) 12,956 (-12.0%)
Phase 4 (in-place Q) ~12,371 (-16.0%)
Phase 5 (wide autotune) ~12,125 (-17.7%)

(Phase 6 — FA4 dense wrapper — stays in llm-training since it's an
external flash-attn wrapper, not a Motif custom kernel.)

Loss matches baseline to 4 decimal places at step 10 (0.0001). No NaN.

torch.library op namespace 'motif::*' retained (no conflict with
activation's existing TORCH_LIBRARY_EXPAND-registered CUDA ops).

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

torch-ext/activation/__init__.py CHANGED
@@ -2,6 +2,11 @@ import torch
2
 
3
  from . import layers, parallel_style
4
  from ._ops import ops
 
 
 
 
 
5
  from .grouped_poly_norm import fused_mul_grouped_poly_norm
6
  from .poly_norm import FusedMulPolyNormFunction, PolyNormFunction
7
  from .rms_norm import FusedAddRMSNormFunction, RMSNormFunction
@@ -49,6 +54,9 @@ __all__ = [
49
  "fused_mul_grouped_poly_norm",
50
  "rms_norm",
51
  "fused_add_rms_norm",
 
 
 
52
  "layers",
53
  "parallel_style",
54
  "ops",
 
2
 
3
  from . import layers, parallel_style
4
  from ._ops import ops
5
+ from .fused_rope import (
6
+ fused_apply_rope,
7
+ fused_kv_split_rope_cat,
8
+ fused_q_rope_inplace,
9
+ )
10
  from .grouped_poly_norm import fused_mul_grouped_poly_norm
11
  from .poly_norm import FusedMulPolyNormFunction, PolyNormFunction
12
  from .rms_norm import FusedAddRMSNormFunction, RMSNormFunction
 
54
  "fused_mul_grouped_poly_norm",
55
  "rms_norm",
56
  "fused_add_rms_norm",
57
+ "fused_apply_rope",
58
+ "fused_q_rope_inplace",
59
+ "fused_kv_split_rope_cat",
60
  "layers",
61
  "parallel_style",
62
  "ops",
torch-ext/activation/fused_rope.py ADDED
@@ -0,0 +1,723 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Fused MLA RoPE kernels for Motif3 GDLAttention.
2
+
3
+ Applies RoPE to the input tensor and outputs in contiguous format
4
+ [real..., imag...] so no reorder_headdim_elements_rope is needed.
5
+
6
+ Registered as torch custom_op for torch.compile compatibility (no graph break).
7
+
8
+ Reference: Megatron-LM fused_mla_yarn_rope_apply.py
9
+ """
10
+
11
+ import torch
12
+ import triton
13
+ import triton.language as tl
14
+
15
+ # ---------------------------------------------------------------------------
16
+ # Autotune search space (BLOCK_H × num_warps × num_stages = 128 configs/kernel)
17
+ # Triton caches per-(key) best config — one-time compile cost per distinct shape.
18
+ # ---------------------------------------------------------------------------
19
+
20
+ def _rope_autotune_configs():
21
+ configs = []
22
+ for bh in [1, 2, 4, 8, 16, 32, 64, 128]:
23
+ for nw in [1, 2, 4, 8]:
24
+ for ns in [1, 2, 3, 4]:
25
+ configs.append(triton.Config({"BLOCK_H": bh}, num_warps=nw, num_stages=ns))
26
+ return configs
27
+
28
+
29
+ # ---------------------------------------------------------------------------
30
+ # Triton kernels
31
+ # ---------------------------------------------------------------------------
32
+
33
+ @triton.autotune(
34
+ configs=_rope_autotune_configs(),
35
+ key=["rope_dim", "head_num"],
36
+ )
37
+ @triton.jit
38
+ def _rope_fwd_kernel(
39
+ X, # [B*S, H, rope_dim] interleaved
40
+ O, # [B*S, H, rope_dim] contiguous
41
+ COS, # [S, rope_dim // 2]
42
+ SIN, # [S, rope_dim // 2]
43
+ rope_dim: tl.constexpr,
44
+ head_num: tl.constexpr,
45
+ seq_len,
46
+ stride_x_token,
47
+ stride_x_head,
48
+ stride_o_token,
49
+ stride_o_head,
50
+ BLOCK_H: tl.constexpr,
51
+ ):
52
+ HALF: tl.constexpr = rope_dim // 2
53
+
54
+ pid_token = tl.program_id(0)
55
+ pid_hblock = tl.program_id(1)
56
+
57
+ pos = pid_token % seq_len
58
+ cos = tl.load(COS + pos * HALF + tl.arange(0, HALF))
59
+ sin = tl.load(SIN + pos * HALF + tl.arange(0, HALF))
60
+ cos = cos.expand_dims(0).broadcast_to(BLOCK_H, HALF)
61
+ sin = sin.expand_dims(0).broadcast_to(BLOCK_H, HALF)
62
+
63
+ X_ptr = X + pid_token * stride_x_token + pid_hblock * BLOCK_H * stride_x_head
64
+ O_ptr = O + pid_token * stride_o_token + pid_hblock * BLOCK_H * stride_o_head
65
+
66
+ h_off = tl.arange(0, BLOCK_H)[:, None]
67
+ mask = (pid_hblock * BLOCK_H + h_off) < head_num
68
+
69
+ x1_off = h_off * stride_x_head + tl.arange(0, HALF)[None, :] * 2
70
+ x2_off = x1_off + 1
71
+ x1 = tl.load(X_ptr + x1_off, mask=mask).to(tl.float32)
72
+ x2 = tl.load(X_ptr + x2_off, mask=mask).to(tl.float32)
73
+
74
+ out_real = x1 * cos - x2 * sin
75
+ out_imag = x1 * sin + x2 * cos
76
+
77
+ real_off = h_off * stride_o_head + tl.arange(0, HALF)[None, :]
78
+ imag_off = real_off + HALF
79
+ tl.store(O_ptr + real_off, out_real, mask=mask)
80
+ tl.store(O_ptr + imag_off, out_imag, mask=mask)
81
+
82
+
83
+ @triton.autotune(
84
+ configs=_rope_autotune_configs(),
85
+ key=["rope_dim", "head_num"],
86
+ )
87
+ @triton.jit
88
+ def _rope_bwd_kernel(
89
+ DO, # [B*S, H, rope_dim] contiguous
90
+ DX, # [B*S, H, rope_dim] interleaved
91
+ COS, # [S, rope_dim // 2]
92
+ SIN, # [S, rope_dim // 2]
93
+ rope_dim: tl.constexpr,
94
+ head_num: tl.constexpr,
95
+ seq_len,
96
+ stride_do_token,
97
+ stride_do_head,
98
+ stride_dx_token,
99
+ stride_dx_head,
100
+ BLOCK_H: tl.constexpr,
101
+ ):
102
+ HALF: tl.constexpr = rope_dim // 2
103
+
104
+ pid_token = tl.program_id(0)
105
+ pid_hblock = tl.program_id(1)
106
+
107
+ pos = pid_token % seq_len
108
+ cos = tl.load(COS + pos * HALF + tl.arange(0, HALF))
109
+ sin = tl.load(SIN + pos * HALF + tl.arange(0, HALF))
110
+ cos = cos.expand_dims(0).broadcast_to(BLOCK_H, HALF)
111
+ sin = sin.expand_dims(0).broadcast_to(BLOCK_H, HALF)
112
+
113
+ DO_ptr = DO + pid_token * stride_do_token + pid_hblock * BLOCK_H * stride_do_head
114
+ DX_ptr = DX + pid_token * stride_dx_token + pid_hblock * BLOCK_H * stride_dx_head
115
+
116
+ h_off = tl.arange(0, BLOCK_H)[:, None]
117
+ mask = (pid_hblock * BLOCK_H + h_off) < head_num
118
+
119
+ real_off = h_off * stride_do_head + tl.arange(0, HALF)[None, :]
120
+ imag_off = real_off + HALF
121
+ d_real = tl.load(DO_ptr + real_off, mask=mask).to(tl.float32)
122
+ d_imag = tl.load(DO_ptr + imag_off, mask=mask).to(tl.float32)
123
+
124
+ dx1 = d_real * cos + d_imag * sin
125
+ dx2 = -d_real * sin + d_imag * cos
126
+
127
+ x1_off = h_off * stride_dx_head + tl.arange(0, HALF)[None, :] * 2
128
+ x2_off = x1_off + 1
129
+ tl.store(DX_ptr + x1_off, dx1, mask=mask)
130
+ tl.store(DX_ptr + x2_off, dx2, mask=mask)
131
+
132
+
133
+ # ---------------------------------------------------------------------------
134
+ # custom_op registration (no graph break under torch.compile)
135
+ # ---------------------------------------------------------------------------
136
+
137
+ @torch.library.custom_op("motif::rope_fwd", mutates_args=())
138
+ def _rope_fwd(
139
+ x: torch.Tensor,
140
+ cos: torch.Tensor,
141
+ sin: torch.Tensor,
142
+ seq_len: int,
143
+ ) -> torch.Tensor:
144
+ B_S, H, D = x.shape
145
+ out = torch.empty_like(x)
146
+ grid = lambda META: (B_S, triton.cdiv(H, META["BLOCK_H"]))
147
+ _rope_fwd_kernel[grid](
148
+ x, out, cos, sin,
149
+ D, H, seq_len,
150
+ x.stride(0), x.stride(1),
151
+ out.stride(0), out.stride(1),
152
+ )
153
+ return out
154
+
155
+
156
+ @_rope_fwd.register_fake
157
+ def _rope_fwd_fake(x, cos, sin, seq_len):
158
+ return torch.empty_like(x)
159
+
160
+
161
+ @torch.library.custom_op("motif::rope_bwd", mutates_args=())
162
+ def _rope_bwd(
163
+ grad_out: torch.Tensor,
164
+ cos: torch.Tensor,
165
+ sin: torch.Tensor,
166
+ seq_len: int,
167
+ ) -> torch.Tensor:
168
+ B_S, H, D = grad_out.shape
169
+ grad_in = torch.empty_like(grad_out)
170
+ grid = lambda META: (B_S, triton.cdiv(H, META["BLOCK_H"]))
171
+ _rope_bwd_kernel[grid](
172
+ grad_out, grad_in, cos, sin,
173
+ D, H, seq_len,
174
+ grad_out.stride(0), grad_out.stride(1),
175
+ grad_in.stride(0), grad_in.stride(1),
176
+ )
177
+ return grad_in
178
+
179
+
180
+ @_rope_bwd.register_fake
181
+ def _rope_bwd_fake(grad_out, cos, sin, seq_len):
182
+ return torch.empty_like(grad_out)
183
+
184
+
185
+ # ---------------------------------------------------------------------------
186
+ # Autograd wrapper
187
+ # ---------------------------------------------------------------------------
188
+
189
+ class FusedRoPE(torch.autograd.Function):
190
+ @staticmethod
191
+ def forward(ctx, x, cos, sin, seq_len):
192
+ # x: [B, S, H, rope_dim] interleaved
193
+ B, S, H, D = x.shape
194
+ out_3d = _rope_fwd(x.reshape(B * S, H, D), cos, sin, seq_len)
195
+ ctx.save_for_backward(cos, sin)
196
+ ctx.seq_len = seq_len
197
+ ctx.shape = (B, S, H, D)
198
+ return out_3d.view(B, S, H, D)
199
+
200
+ @staticmethod
201
+ def backward(ctx, grad_out):
202
+ cos, sin = ctx.saved_tensors
203
+ B, S, H, D = ctx.shape
204
+ grad_in_3d = _rope_bwd(
205
+ grad_out.contiguous().reshape(B * S, H, D),
206
+ cos, sin, ctx.seq_len,
207
+ )
208
+ return grad_in_3d.view(B, S, H, D), None, None, None
209
+
210
+
211
+ def fused_apply_rope(x, freqs_cis):
212
+ """Apply fused RoPE, outputting contiguous format. No graph break.
213
+
214
+ Args:
215
+ x: [B, S, H, rope_dim] interleaved format
216
+ freqs_cis: [max_seq_len, rope_dim//2] complex64
217
+
218
+ Returns:
219
+ [B, S, H, rope_dim] contiguous format [real..., imag...]
220
+ """
221
+ S = x.shape[1]
222
+ cos = freqs_cis[:S].real.contiguous()
223
+ sin = freqs_cis[:S].imag.contiguous()
224
+ return FusedRoPE.apply(x, cos, sin, S)
225
+
226
+
227
+ # ---------------------------------------------------------------------------
228
+ # Phase 2: Fused KV split + RoPE + expand + cat kernel
229
+ # Fuses: split(kv_latent, [k_dim, v_dim]) + RoPE(k_pe) + expand + cat → key, value
230
+ # Reference: Megatron rotary_fwd_kv_kernel
231
+ # ---------------------------------------------------------------------------
232
+
233
+ @triton.autotune(
234
+ configs=_rope_autotune_configs(),
235
+ key=["rope_dim", "k_nope_dim", "v_dim", "head_num"],
236
+ )
237
+ @triton.jit
238
+ def _kv_rope_fwd_kernel(
239
+ KV, # [B*S, H, k_nope_dim + v_dim]
240
+ K_PE, # [B*S, 1, rope_dim] (already RoPE'd, contiguous format)
241
+ O_KEY, # [B*S, H, k_nope_dim + rope_dim] output
242
+ O_VALUE, # [B*S, H, v_dim] output
243
+ rope_dim: tl.constexpr,
244
+ k_nope_dim: tl.constexpr,
245
+ v_dim: tl.constexpr,
246
+ head_num: tl.constexpr,
247
+ stride_kv_token,
248
+ stride_kv_head,
249
+ stride_pe_token,
250
+ stride_k_token,
251
+ stride_k_head,
252
+ stride_v_token,
253
+ stride_v_head,
254
+ BLOCK_H: tl.constexpr,
255
+ ):
256
+ pid_token = tl.program_id(0)
257
+ pid_hblock = tl.program_id(1)
258
+
259
+ KV_ptr = KV + pid_token * stride_kv_token + pid_hblock * BLOCK_H * stride_kv_head
260
+ K_ptr = O_KEY + pid_token * stride_k_token + pid_hblock * BLOCK_H * stride_k_head
261
+ V_ptr = O_VALUE + pid_token * stride_v_token + pid_hblock * BLOCK_H * stride_v_head
262
+
263
+ h_off = tl.arange(0, BLOCK_H)[:, None]
264
+ mask = (pid_hblock * BLOCK_H + h_off) < head_num
265
+
266
+ # Read k_nope from KV
267
+ k_nope_off = h_off * stride_kv_head + tl.arange(0, k_nope_dim)[None, :]
268
+ k_nope = tl.load(KV_ptr + k_nope_off, mask=mask)
269
+
270
+ # Read v from KV
271
+ v_off = h_off * stride_kv_head + k_nope_dim + tl.arange(0, v_dim)[None, :]
272
+ v = tl.load(KV_ptr + v_off, mask=mask)
273
+
274
+ # Read k_pe (shared across all heads, already RoPE'd)
275
+ # K_PE is [B*S, 1, rope_dim], broadcast to all heads
276
+ pe_ptr = K_PE + pid_token * stride_pe_token
277
+ k_pe = tl.load(pe_ptr + tl.arange(0, rope_dim)[None, :])
278
+ k_pe = k_pe.broadcast_to(BLOCK_H, rope_dim)
279
+
280
+ # Write key = [k_nope | k_pe]
281
+ k_nope_out = h_off * stride_k_head + tl.arange(0, k_nope_dim)[None, :]
282
+ tl.store(K_ptr + k_nope_out, k_nope, mask=mask)
283
+ k_pe_out = h_off * stride_k_head + k_nope_dim + tl.arange(0, rope_dim)[None, :]
284
+ tl.store(K_ptr + k_pe_out, k_pe, mask=mask)
285
+
286
+ # Write value
287
+ v_out = h_off * stride_v_head + tl.arange(0, v_dim)[None, :]
288
+ tl.store(V_ptr + v_out, v, mask=mask)
289
+
290
+
291
+ @torch.library.custom_op("motif::kv_rope_fwd", mutates_args=())
292
+ def _kv_rope_fwd(
293
+ kv_latent: torch.Tensor, # [B*S, H, k_nope_dim + v_dim]
294
+ k_pe: torch.Tensor, # [B*S, 1, rope_dim] (already RoPE'd)
295
+ k_nope_dim: int,
296
+ v_dim: int,
297
+ rope_dim: int,
298
+ ) -> tuple[torch.Tensor, torch.Tensor]:
299
+ B_S, H, _ = kv_latent.shape
300
+ key = kv_latent.new_empty(B_S, H, k_nope_dim + rope_dim)
301
+ value = kv_latent.new_empty(B_S, H, v_dim)
302
+ grid = lambda META: (B_S, triton.cdiv(H, META["BLOCK_H"]))
303
+ _kv_rope_fwd_kernel[grid](
304
+ kv_latent, k_pe, key, value,
305
+ rope_dim, k_nope_dim, v_dim, H,
306
+ kv_latent.stride(0), kv_latent.stride(1),
307
+ k_pe.stride(0),
308
+ key.stride(0), key.stride(1),
309
+ value.stride(0), value.stride(1),
310
+ )
311
+ return key, value
312
+
313
+
314
+ @_kv_rope_fwd.register_fake
315
+ def _kv_rope_fwd_fake(kv_latent, k_pe, k_nope_dim, v_dim, rope_dim):
316
+ B_S, H, _ = kv_latent.shape
317
+ key = kv_latent.new_empty(B_S, H, k_nope_dim + rope_dim)
318
+ value = kv_latent.new_empty(B_S, H, v_dim)
319
+ return key, value
320
+
321
+
322
+ class FusedKVRoPE(torch.autograd.Function):
323
+ @staticmethod
324
+ def forward(ctx, kv_latent, k_pe, k_nope_dim, v_dim, rope_dim):
325
+ # kv_latent: [B, S, H, k_nope_dim + v_dim]
326
+ # k_pe: [B, S, 1, rope_dim] (already RoPE'd)
327
+ B, S, H, D = kv_latent.shape
328
+ key_3d, value_3d = _kv_rope_fwd(
329
+ kv_latent.reshape(B * S, H, D),
330
+ k_pe.reshape(B * S, 1, rope_dim),
331
+ k_nope_dim, v_dim, rope_dim,
332
+ )
333
+ ctx.save_for_backward(k_pe)
334
+ ctx.k_nope_dim = k_nope_dim
335
+ ctx.v_dim = v_dim
336
+ ctx.rope_dim = rope_dim
337
+ ctx.shape = (B, S, H)
338
+ return key_3d.view(B, S, H, k_nope_dim + rope_dim), value_3d.view(B, S, H, v_dim)
339
+
340
+ @staticmethod
341
+ def backward(ctx, grad_key, grad_value):
342
+ k_pe, = ctx.saved_tensors
343
+ B, S, H = ctx.shape
344
+ k_nope_dim = ctx.k_nope_dim
345
+ v_dim = ctx.v_dim
346
+ rope_dim = ctx.rope_dim
347
+
348
+ # grad_key: [B, S, H, k_nope_dim + rope_dim]
349
+ # grad_value: [B, S, H, v_dim]
350
+ # Reconstruct grad_kv_latent = [grad_k_nope | grad_value]
351
+ grad_k_nope = grad_key[..., :k_nope_dim]
352
+ grad_kv_latent = torch.cat([grad_k_nope, grad_value], dim=-1)
353
+
354
+ # grad_k_pe: sum across heads (k_pe was broadcast)
355
+ grad_k_pe = grad_key[..., k_nope_dim:].sum(dim=2, keepdim=True)
356
+
357
+ return grad_kv_latent, grad_k_pe, None, None, None
358
+
359
+
360
+ # ---------------------------------------------------------------------------
361
+ # Phase 3: Fused Q nope passthrough + RoPE kernel (eliminates cat)
362
+ # Q [B*S, H, nope_dim + rope_dim] → Q_out [B*S, H, nope_dim + rope_dim]
363
+ # First nope_dim elements: copy as-is
364
+ # Last rope_dim elements: apply RoPE (interleaved → contiguous)
365
+ # ---------------------------------------------------------------------------
366
+
367
+ @triton.autotune(
368
+ configs=_rope_autotune_configs(),
369
+ key=["nope_dim", "rope_dim", "head_num"],
370
+ )
371
+ @triton.jit
372
+ def _q_rope_fwd_kernel(
373
+ Q, # [B*S, H, nope_dim + rope_dim] input
374
+ O, # [B*S, H, nope_dim + rope_dim] output
375
+ COS, # [S, rope_dim // 2]
376
+ SIN, # [S, rope_dim // 2]
377
+ nope_dim: tl.constexpr,
378
+ rope_dim: tl.constexpr,
379
+ head_num: tl.constexpr,
380
+ seq_len,
381
+ stride_q_token,
382
+ stride_q_head,
383
+ stride_o_token,
384
+ stride_o_head,
385
+ BLOCK_H: tl.constexpr,
386
+ ):
387
+ HALF: tl.constexpr = rope_dim // 2
388
+
389
+ pid_token = tl.program_id(0)
390
+ pid_hblock = tl.program_id(1)
391
+
392
+ pos = pid_token % seq_len
393
+
394
+ Q_ptr = Q + pid_token * stride_q_token + pid_hblock * BLOCK_H * stride_q_head
395
+ O_ptr = O + pid_token * stride_o_token + pid_hblock * BLOCK_H * stride_o_head
396
+
397
+ h_off = tl.arange(0, BLOCK_H)[:, None]
398
+ mask = (pid_hblock * BLOCK_H + h_off) < head_num
399
+
400
+ # Copy nope portion as-is
401
+ nope_off = h_off * stride_q_head + tl.arange(0, nope_dim)[None, :]
402
+ nope_data = tl.load(Q_ptr + nope_off, mask=mask)
403
+ nope_out = h_off * stride_o_head + tl.arange(0, nope_dim)[None, :]
404
+ tl.store(O_ptr + nope_out, nope_data, mask=mask)
405
+
406
+ # RoPE on rope portion: read interleaved, write contiguous
407
+ cos = tl.load(COS + pos * HALF + tl.arange(0, HALF))
408
+ sin = tl.load(SIN + pos * HALF + tl.arange(0, HALF))
409
+ cos = cos.expand_dims(0).broadcast_to(BLOCK_H, HALF)
410
+ sin = sin.expand_dims(0).broadcast_to(BLOCK_H, HALF)
411
+
412
+ x1_off = h_off * stride_q_head + nope_dim + tl.arange(0, HALF)[None, :] * 2
413
+ x2_off = x1_off + 1
414
+ x1 = tl.load(Q_ptr + x1_off, mask=mask).to(tl.float32)
415
+ x2 = tl.load(Q_ptr + x2_off, mask=mask).to(tl.float32)
416
+
417
+ out_real = x1 * cos - x2 * sin
418
+ out_imag = x1 * sin + x2 * cos
419
+
420
+ real_off = h_off * stride_o_head + nope_dim + tl.arange(0, HALF)[None, :]
421
+ imag_off = real_off + HALF
422
+ tl.store(O_ptr + real_off, out_real, mask=mask)
423
+ tl.store(O_ptr + imag_off, out_imag, mask=mask)
424
+
425
+
426
+ @triton.autotune(
427
+ configs=_rope_autotune_configs(),
428
+ key=["nope_dim", "rope_dim", "head_num"],
429
+ )
430
+ @triton.jit
431
+ def _q_rope_bwd_kernel(
432
+ DO, # [B*S, H, nope_dim + rope_dim] grad (contiguous rope fmt)
433
+ DQ, # [B*S, H, nope_dim + rope_dim] grad output (interleaved rope fmt)
434
+ COS, # [S, rope_dim // 2]
435
+ SIN, # [S, rope_dim // 2]
436
+ nope_dim: tl.constexpr,
437
+ rope_dim: tl.constexpr,
438
+ head_num: tl.constexpr,
439
+ seq_len,
440
+ stride_do_token,
441
+ stride_do_head,
442
+ stride_dq_token,
443
+ stride_dq_head,
444
+ BLOCK_H: tl.constexpr,
445
+ ):
446
+ HALF: tl.constexpr = rope_dim // 2
447
+
448
+ pid_token = tl.program_id(0)
449
+ pid_hblock = tl.program_id(1)
450
+
451
+ pos = pid_token % seq_len
452
+
453
+ DO_ptr = DO + pid_token * stride_do_token + pid_hblock * BLOCK_H * stride_do_head
454
+ DQ_ptr = DQ + pid_token * stride_dq_token + pid_hblock * BLOCK_H * stride_dq_head
455
+
456
+ h_off = tl.arange(0, BLOCK_H)[:, None]
457
+ mask = (pid_hblock * BLOCK_H + h_off) < head_num
458
+
459
+ # Copy nope grad as-is
460
+ nope_off_in = h_off * stride_do_head + tl.arange(0, nope_dim)[None, :]
461
+ nope_grad = tl.load(DO_ptr + nope_off_in, mask=mask)
462
+ nope_off_out = h_off * stride_dq_head + tl.arange(0, nope_dim)[None, :]
463
+ tl.store(DQ_ptr + nope_off_out, nope_grad, mask=mask)
464
+
465
+ # Inverse RoPE: contiguous → interleaved
466
+ cos = tl.load(COS + pos * HALF + tl.arange(0, HALF))
467
+ sin = tl.load(SIN + pos * HALF + tl.arange(0, HALF))
468
+ cos = cos.expand_dims(0).broadcast_to(BLOCK_H, HALF)
469
+ sin = sin.expand_dims(0).broadcast_to(BLOCK_H, HALF)
470
+
471
+ real_off = h_off * stride_do_head + nope_dim + tl.arange(0, HALF)[None, :]
472
+ imag_off = real_off + HALF
473
+ d_real = tl.load(DO_ptr + real_off, mask=mask).to(tl.float32)
474
+ d_imag = tl.load(DO_ptr + imag_off, mask=mask).to(tl.float32)
475
+
476
+ dx1 = d_real * cos + d_imag * sin
477
+ dx2 = -d_real * sin + d_imag * cos
478
+
479
+ x1_off = h_off * stride_dq_head + nope_dim + tl.arange(0, HALF)[None, :] * 2
480
+ x2_off = x1_off + 1
481
+ tl.store(DQ_ptr + x1_off, dx1, mask=mask)
482
+ tl.store(DQ_ptr + x2_off, dx2, mask=mask)
483
+
484
+
485
+ @torch.library.custom_op("motif::q_rope_fwd", mutates_args=())
486
+ def _q_rope_fwd(
487
+ q: torch.Tensor,
488
+ cos: torch.Tensor,
489
+ sin: torch.Tensor,
490
+ nope_dim: int,
491
+ rope_dim: int,
492
+ seq_len: int,
493
+ ) -> torch.Tensor:
494
+ B_S, H, D = q.shape
495
+ out = torch.empty_like(q)
496
+ grid = lambda META: (B_S, triton.cdiv(H, META["BLOCK_H"]))
497
+ _q_rope_fwd_kernel[grid](
498
+ q, out, cos, sin,
499
+ nope_dim, rope_dim, H, seq_len,
500
+ q.stride(0), q.stride(1),
501
+ out.stride(0), out.stride(1),
502
+ )
503
+ return out
504
+
505
+
506
+ @_q_rope_fwd.register_fake
507
+ def _q_rope_fwd_fake(q, cos, sin, nope_dim, rope_dim, seq_len):
508
+ return torch.empty_like(q)
509
+
510
+
511
+ @torch.library.custom_op("motif::q_rope_bwd", mutates_args=())
512
+ def _q_rope_bwd(
513
+ grad_out: torch.Tensor,
514
+ cos: torch.Tensor,
515
+ sin: torch.Tensor,
516
+ nope_dim: int,
517
+ rope_dim: int,
518
+ seq_len: int,
519
+ ) -> torch.Tensor:
520
+ B_S, H, D = grad_out.shape
521
+ grad_in = torch.empty_like(grad_out)
522
+ grid = lambda META: (B_S, triton.cdiv(H, META["BLOCK_H"]))
523
+ _q_rope_bwd_kernel[grid](
524
+ grad_out, grad_in, cos, sin,
525
+ nope_dim, rope_dim, H, seq_len,
526
+ grad_out.stride(0), grad_out.stride(1),
527
+ grad_in.stride(0), grad_in.stride(1),
528
+ )
529
+ return grad_in
530
+
531
+
532
+ @_q_rope_bwd.register_fake
533
+ def _q_rope_bwd_fake(grad_out, cos, sin, nope_dim, rope_dim, seq_len):
534
+ return torch.empty_like(grad_out)
535
+
536
+
537
+ class FusedQRoPE(torch.autograd.Function):
538
+ @staticmethod
539
+ def forward(ctx, q, cos, sin, nope_dim, rope_dim, seq_len):
540
+ B, S, H, D = q.shape
541
+ out_3d = _q_rope_fwd(q.reshape(B * S, H, D), cos, sin, nope_dim, rope_dim, seq_len)
542
+ ctx.save_for_backward(cos, sin)
543
+ ctx.nope_dim = nope_dim
544
+ ctx.rope_dim = rope_dim
545
+ ctx.seq_len = seq_len
546
+ ctx.shape = (B, S, H, D)
547
+ return out_3d.view(B, S, H, D)
548
+
549
+ @staticmethod
550
+ def backward(ctx, grad_out):
551
+ cos, sin = ctx.saved_tensors
552
+ B, S, H, D = ctx.shape
553
+ grad_in_3d = _q_rope_bwd(
554
+ grad_out.contiguous().reshape(B * S, H, D),
555
+ cos, sin, ctx.nope_dim, ctx.rope_dim, ctx.seq_len,
556
+ )
557
+ return grad_in_3d.view(B, S, H, D), None, None, None, None, None
558
+
559
+
560
+ def fused_q_rope(q, freqs_cis, nope_dim, rope_dim):
561
+ """Fused Q nope passthrough + RoPE. Eliminates split + cat.
562
+
563
+ Replaces:
564
+ q_nope, q_pe = split(q, [nope_dim, rope_dim])
565
+ q_pe = fused_apply_rope(q_pe, freqs_cis)
566
+ q_total = cat([q_nope, q_pe])
567
+
568
+ Args:
569
+ q: [B, S, H, nope_dim + rope_dim] from wq_b output
570
+ freqs_cis: [max_seq_len, rope_dim//2] complex64
571
+
572
+ Returns:
573
+ [B, S, H, nope_dim + rope_dim] with nope unchanged, rope in contiguous format
574
+ """
575
+ S = q.shape[1]
576
+ cos = freqs_cis[:S].real.contiguous()
577
+ sin = freqs_cis[:S].imag.contiguous()
578
+ return FusedQRoPE.apply(q, cos, sin, nope_dim, rope_dim, S)
579
+
580
+
581
+ # ---------------------------------------------------------------------------
582
+ # Phase 4: In-place Q RoPE kernel (eliminates cat + nope copy)
583
+ # Modifies q[..., nope_dim:] from interleaved → contiguous format IN-PLACE.
584
+ # nope section [..., :nope_dim] is untouched.
585
+ # Forward: in-place on Q (mutates)
586
+ # Backward: out-of-place via existing _q_rope_bwd_kernel (nope grad copy + inverse rope)
587
+ # ---------------------------------------------------------------------------
588
+
589
+ @triton.autotune(
590
+ configs=_rope_autotune_configs(),
591
+ key=["nope_dim", "rope_dim", "head_num"],
592
+ )
593
+ @triton.jit
594
+ def _q_rope_inplace_fwd_kernel(
595
+ Q, # [B*S, H, nope_dim + rope_dim] modified in-place on [..., nope_dim:]
596
+ COS, # [S, rope_dim // 2]
597
+ SIN, # [S, rope_dim // 2]
598
+ nope_dim: tl.constexpr,
599
+ rope_dim: tl.constexpr,
600
+ head_num: tl.constexpr,
601
+ seq_len,
602
+ stride_q_token,
603
+ stride_q_head,
604
+ BLOCK_H: tl.constexpr,
605
+ ):
606
+ HALF: tl.constexpr = rope_dim // 2
607
+
608
+ pid_token = tl.program_id(0)
609
+ pid_hblock = tl.program_id(1)
610
+
611
+ pos = pid_token % seq_len
612
+ cos = tl.load(COS + pos * HALF + tl.arange(0, HALF))
613
+ sin = tl.load(SIN + pos * HALF + tl.arange(0, HALF))
614
+ cos = cos.expand_dims(0).broadcast_to(BLOCK_H, HALF)
615
+ sin = sin.expand_dims(0).broadcast_to(BLOCK_H, HALF)
616
+
617
+ Q_ptr = Q + pid_token * stride_q_token + pid_hblock * BLOCK_H * stride_q_head
618
+
619
+ h_off = tl.arange(0, BLOCK_H)[:, None]
620
+ mask = (pid_hblock * BLOCK_H + h_off) < head_num
621
+
622
+ # Read rope section interleaved: [r0,i0,r1,i1,...]
623
+ x1_off = h_off * stride_q_head + nope_dim + tl.arange(0, HALF)[None, :] * 2
624
+ x2_off = x1_off + 1
625
+ x1 = tl.load(Q_ptr + x1_off, mask=mask).to(tl.float32)
626
+ x2 = tl.load(Q_ptr + x2_off, mask=mask).to(tl.float32)
627
+
628
+ out_real = x1 * cos - x2 * sin
629
+ out_imag = x1 * sin + x2 * cos
630
+
631
+ # Write back to SAME rope section in contiguous format: [r0..r31, i0..i31]
632
+ real_off = h_off * stride_q_head + nope_dim + tl.arange(0, HALF)[None, :]
633
+ imag_off = real_off + HALF
634
+ tl.store(Q_ptr + real_off, out_real, mask=mask)
635
+ tl.store(Q_ptr + imag_off, out_imag, mask=mask)
636
+
637
+
638
+ @torch.library.custom_op("motif::q_rope_inplace_fwd", mutates_args=("q",))
639
+ def _q_rope_inplace_fwd(
640
+ q: torch.Tensor,
641
+ cos: torch.Tensor,
642
+ sin: torch.Tensor,
643
+ nope_dim: int,
644
+ rope_dim: int,
645
+ seq_len: int,
646
+ ) -> None:
647
+ B_S, H, _ = q.shape
648
+ grid = lambda META: (B_S, triton.cdiv(H, META["BLOCK_H"]))
649
+ _q_rope_inplace_fwd_kernel[grid](
650
+ q, cos, sin,
651
+ nope_dim, rope_dim, H, seq_len,
652
+ q.stride(0), q.stride(1),
653
+ )
654
+
655
+
656
+ class FusedQRoPEInplace(torch.autograd.Function):
657
+ @staticmethod
658
+ def forward(ctx, q, cos, sin, nope_dim, rope_dim, seq_len):
659
+ # q: [B, S, H, nope_dim + rope_dim] mutated in-place on [..., nope_dim:]
660
+ B, S, H, D = q.shape
661
+ assert D == nope_dim + rope_dim
662
+ _q_rope_inplace_fwd(q.reshape(B * S, H, D), cos, sin, nope_dim, rope_dim, seq_len)
663
+ ctx.mark_dirty(q)
664
+ ctx.save_for_backward(cos, sin)
665
+ ctx.nope_dim = nope_dim
666
+ ctx.rope_dim = rope_dim
667
+ ctx.seq_len = seq_len
668
+ ctx.shape = (B, S, H, D)
669
+ return q
670
+
671
+ @staticmethod
672
+ def backward(ctx, grad_out):
673
+ # grad_out: [B, S, H, nope_dim + rope_dim] rope section in contiguous grad fmt
674
+ # Produce grad_in: same shape, rope section in interleaved grad fmt (matches Q input layout)
675
+ cos, sin = ctx.saved_tensors
676
+ B, S, H, D = ctx.shape
677
+ # Reuse existing Q backward kernel (copies nope grad + inverse-ropes pe section)
678
+ grad_in_3d = _q_rope_bwd(
679
+ grad_out.contiguous().reshape(B * S, H, D),
680
+ cos, sin, ctx.nope_dim, ctx.rope_dim, ctx.seq_len,
681
+ )
682
+ return grad_in_3d.view(B, S, H, D), None, None, None, None, None
683
+
684
+
685
+ def fused_q_rope_inplace(q, freqs_cis, nope_dim, rope_dim):
686
+ """In-place fused Q RoPE. Modifies q[..., nope_dim:] from interleaved → contiguous format.
687
+
688
+ Replaces:
689
+ q_nope, q_pe = split(q, [nope_dim, rope_dim])
690
+ q_pe = fused_apply_rope(q_pe, freqs_cis)
691
+ q_total = cat([q_nope, q_pe])
692
+
693
+ Saves the cat copy (~415 µs/layer for Motif3) compared to out-of-place variants.
694
+
695
+ Args:
696
+ q: [B, S, H, nope_dim + rope_dim] from wq_b output. Will be mutated.
697
+ freqs_cis: [max_seq_len, rope_dim//2] complex64
698
+
699
+ Returns:
700
+ Same tensor `q`, now with rope section in contiguous format.
701
+ """
702
+ S = q.shape[1]
703
+ cos = freqs_cis[:S].real.contiguous()
704
+ sin = freqs_cis[:S].imag.contiguous()
705
+ return FusedQRoPEInplace.apply(q, cos, sin, nope_dim, rope_dim, S)
706
+
707
+
708
+ def fused_kv_split_rope_cat(kv_latent, k_pe, k_nope_dim, v_dim, rope_dim):
709
+ """Fused KV split + k_pe expand + cat. No graph break.
710
+
711
+ Replaces:
712
+ k_nope, v = split(kv_latent, [k_nope_dim, v_dim])
713
+ k_full = cat([k_nope, k_pe.expand(-1,-1,H,-1)])
714
+
715
+ Args:
716
+ kv_latent: [B, S, H, k_nope_dim + v_dim]
717
+ k_pe: [B, S, 1, rope_dim] (already RoPE'd, contiguous format)
718
+
719
+ Returns:
720
+ key: [B, S, H, k_nope_dim + rope_dim]
721
+ value: [B, S, H, v_dim]
722
+ """
723
+ return FusedKVRoPE.apply(kv_latent, k_pe, k_nope_dim, v_dim, rope_dim)