1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
//! Rotary Position Embedding (RoPE) backward plan.
//!
//! Rotation matrices are orthogonal, so BW is rotation by `-θ`:
//!
//! ```text
//! dx[2i] = dy[2i] · cos(θ) + dy[2i+1] · sin(θ)
//! dx[2i+1] = dy[2i+1] · cos(θ) - dy[2i] · sin(θ)
//! ```
//!
//! Shape, dtype scope, and `positions` semantics match [`super::rope`].
use core::ffi::c_void;
use core::marker::PhantomData;
use baracuda_cutlass::{Error, Result};
use baracuda_driver::Stream;
use baracuda_kernels_types::{
ArchSku, AttentionKind, BackendKind, Element, ElementKind, KernelSku, MathPrecision,
OpCategory, PlanPreference, PrecisionGuarantee, TensorMut, TensorRef, Workspace,
};
use super::map_status;
/// Descriptor for a RoPE backward op.
#[derive(Copy, Clone, Debug)]
pub struct RopeBackwardDescriptor {
/// Batch size (`B`).
pub batch_size: i32,
/// Number of attention heads (`H`).
pub num_heads: i32,
/// Sequence length (`S`).
pub seq_len: i32,
/// Head dimension (`D`). Must be even.
pub head_dim: i32,
/// Rotary base; must match the FW base.
pub base: f32,
/// Element type.
pub element: ElementKind,
}
/// Args bundle for a RoPE backward launch.
pub struct RopeBackwardArgs<'a, T: Element> {
/// Upstream gradient `dy` — shape `[B, H, S, D]`, contiguous.
pub dy: TensorRef<'a, T, 4>,
/// Optional `[S]` `i64` position indices — must match the FW call.
pub positions: Option<TensorRef<'a, i64, 1>>,
/// Output gradient `dx` — same shape as `dy`.
pub dx: TensorMut<'a, T, 4>,
}
/// Rotary Position Embedding backward plan.
///
/// Rotation matrices are orthogonal — BW is rotation by `-θ`. No saved
/// FW state is needed; the kernel re-derives `θ` from `positions` (or
/// from `s` when `positions` is omitted) on the fly.
///
/// **When to use**: autograd partner for [`super::RopePlan`]. `base`,
/// `head_dim`, and the optional `positions` arg must match the FW
/// call.
///
/// **Dtypes / shape limits / workspace / precision**: identical to
/// [`super::RopePlan`].
pub struct RopeBackwardPlan<T: Element> {
desc: RopeBackwardDescriptor,
sku: KernelSku,
_marker: PhantomData<T>,
}
impl<T: Element> RopeBackwardPlan<T> {
/// Pick a kernel.
pub fn select(
_stream: &Stream,
desc: &RopeBackwardDescriptor,
_pref: PlanPreference,
) -> Result<Self> {
if desc.element != T::KIND {
return Err(Error::Unsupported(
"baracuda-kernels::RopeBackwardPlan: descriptor element != T",
));
}
if desc.batch_size < 0
|| desc.num_heads < 0
|| desc.seq_len < 0
|| desc.head_dim < 0
{
return Err(Error::InvalidProblem(
"baracuda-kernels::RopeBackwardPlan: extents must be non-negative",
));
}
if desc.head_dim % 2 != 0 {
return Err(Error::InvalidProblem(
"baracuda-kernels::RopeBackwardPlan: head_dim must be even",
));
}
if !desc.base.is_finite() || desc.base <= 0.0 {
return Err(Error::InvalidProblem(
"baracuda-kernels::RopeBackwardPlan: base must be finite and positive",
));
}
let dtype_in_scope = matches!(
T::KIND,
ElementKind::F32 | ElementKind::F16 | ElementKind::Bf16 | ElementKind::F64
);
if !dtype_in_scope {
return Err(Error::Unsupported(
"baracuda-kernels::RopeBackwardPlan: wired today: `{f32, f16, bf16, f64}`",
));
}
let precision_guarantee = PrecisionGuarantee {
math_precision: MathPrecision::F32,
accumulator: ElementKind::F32,
bit_stable_on_same_hardware: true,
deterministic: true,
};
let sku = KernelSku {
category: OpCategory::Attention,
op: AttentionKind::Rope as u16,
element: T::KIND,
aux_element: None,
layout: None,
epilogue: None,
arch: ArchSku::Sm80,
backend: BackendKind::Bespoke,
precision_guarantee,
};
Ok(Self {
desc: *desc,
sku,
_marker: PhantomData,
})
}
/// Validate args.
pub fn can_implement(&self, args: &RopeBackwardArgs<'_, T>) -> Result<()> {
let want_shape = [
self.desc.batch_size,
self.desc.num_heads,
self.desc.seq_len,
self.desc.head_dim,
];
if args.dy.shape != want_shape {
return Err(Error::InvalidProblem(
"baracuda-kernels::RopeBackwardPlan: dy shape mismatch",
));
}
if args.dx.shape != want_shape {
return Err(Error::InvalidProblem(
"baracuda-kernels::RopeBackwardPlan: dx shape mismatch",
));
}
// Phase 14.4: strided variant supports arbitrary outer strides
// but the innermost head_dim axis MUST remain stride=1 because
// RoPE rotates adjacent pairs (2i, 2i+1).
if args.dy.stride[3] != 1 || args.dx.stride[3] != 1 {
return Err(Error::InvalidProblem(
"baracuda-kernels::RopeBackwardPlan: head_dim axis must have stride=1 \
(RoPE rotates adjacent pairs)",
));
}
if let Some(ref p) = args.positions {
if p.shape != [self.desc.seq_len] {
return Err(Error::InvalidProblem(
"baracuda-kernels::RopeBackwardPlan: positions shape must be [seq_len]",
));
}
}
// Buffer-size check only for contig — strided views are caller-owned.
if args.dy.is_contiguous() && args.dx.is_contiguous() {
let numel = args.dy.numel();
if (args.dy.data.len() as i64) < numel || (args.dx.data.len() as i64) < numel {
return Err(Error::BufferTooSmall {
needed: numel as usize,
got: args.dy.data.len().min(args.dx.data.len()),
});
}
}
Ok(())
}
/// Workspace size in bytes.
#[inline]
pub fn workspace_size(&self) -> usize {
0
}
/// SKU identity.
#[inline]
pub fn sku(&self) -> KernelSku {
self.sku
}
/// Numerical guarantees.
#[inline]
pub fn precision_guarantee(&self) -> PrecisionGuarantee {
self.sku.precision_guarantee
}
/// Launch.
///
/// Phase 14.4: dispatches between the contig fast path and the
/// strided sibling FFI based on whether `dy` / `dx` are canonical
/// row-major contiguous.
pub fn run(
&self,
stream: &Stream,
_workspace: Workspace<'_>,
args: RopeBackwardArgs<'_, T>,
) -> Result<()> {
self.can_implement(&args)?;
let numel = args.dy.numel();
if numel == 0 {
return Ok(());
}
let stream_ptr = stream.as_raw() as *mut c_void;
let dy_ptr = args.dy.data.as_raw().0 as *const c_void;
let dx_ptr = args.dx.data.as_raw().0 as *mut c_void;
let (pos_ptr, pos_default_flag) = match &args.positions {
Some(p) => (p.data.as_raw().0 as *const c_void, 0i32),
None => (core::ptr::null::<c_void>(), 1i32),
};
let contig = args.dy.is_contiguous() && args.dx.is_contiguous();
let status = unsafe {
if contig {
match T::KIND {
ElementKind::F32 => baracuda_kernels_sys::baracuda_kernels_rope_backward_f32_run(
self.desc.batch_size,
self.desc.num_heads,
self.desc.seq_len,
self.desc.head_dim,
self.desc.base,
pos_default_flag,
dy_ptr,
pos_ptr,
dx_ptr,
core::ptr::null_mut(),
0,
stream_ptr,
),
ElementKind::F16 => baracuda_kernels_sys::baracuda_kernels_rope_backward_f16_run(
self.desc.batch_size,
self.desc.num_heads,
self.desc.seq_len,
self.desc.head_dim,
self.desc.base,
pos_default_flag,
dy_ptr,
pos_ptr,
dx_ptr,
core::ptr::null_mut(),
0,
stream_ptr,
),
ElementKind::Bf16 => baracuda_kernels_sys::baracuda_kernels_rope_backward_bf16_run(
self.desc.batch_size,
self.desc.num_heads,
self.desc.seq_len,
self.desc.head_dim,
self.desc.base,
pos_default_flag,
dy_ptr,
pos_ptr,
dx_ptr,
core::ptr::null_mut(),
0,
stream_ptr,
),
ElementKind::F64 => baracuda_kernels_sys::baracuda_kernels_rope_backward_f64_run(
self.desc.batch_size,
self.desc.num_heads,
self.desc.seq_len,
self.desc.head_dim,
self.desc.base,
pos_default_flag,
dy_ptr,
pos_ptr,
dx_ptr,
core::ptr::null_mut(),
0,
stream_ptr,
),
_ => {
return Err(Error::Unsupported(
"baracuda-kernels::RopeBackwardPlan::run reached an unimplemented dtype",
));
}
}
} else {
// Strided sibling.
let sdyb = args.dy.stride[0];
let sdyh = args.dy.stride[1];
let sdys = args.dy.stride[2];
let sdxb = args.dx.stride[0];
let sdxh = args.dx.stride[1];
let sdxs = args.dx.stride[2];
match T::KIND {
ElementKind::F32 => baracuda_kernels_sys::baracuda_kernels_rope_backward_f32_strided_run(
self.desc.batch_size,
self.desc.num_heads,
self.desc.seq_len,
self.desc.head_dim,
sdyb, sdyh, sdys, sdxb, sdxh, sdxs,
self.desc.base,
pos_default_flag,
dy_ptr,
pos_ptr,
dx_ptr,
core::ptr::null_mut(),
0,
stream_ptr,
),
ElementKind::F16 => baracuda_kernels_sys::baracuda_kernels_rope_backward_f16_strided_run(
self.desc.batch_size,
self.desc.num_heads,
self.desc.seq_len,
self.desc.head_dim,
sdyb, sdyh, sdys, sdxb, sdxh, sdxs,
self.desc.base,
pos_default_flag,
dy_ptr,
pos_ptr,
dx_ptr,
core::ptr::null_mut(),
0,
stream_ptr,
),
ElementKind::Bf16 => baracuda_kernels_sys::baracuda_kernels_rope_backward_bf16_strided_run(
self.desc.batch_size,
self.desc.num_heads,
self.desc.seq_len,
self.desc.head_dim,
sdyb, sdyh, sdys, sdxb, sdxh, sdxs,
self.desc.base,
pos_default_flag,
dy_ptr,
pos_ptr,
dx_ptr,
core::ptr::null_mut(),
0,
stream_ptr,
),
ElementKind::F64 => baracuda_kernels_sys::baracuda_kernels_rope_backward_f64_strided_run(
self.desc.batch_size,
self.desc.num_heads,
self.desc.seq_len,
self.desc.head_dim,
sdyb, sdyh, sdys, sdxb, sdxh, sdxs,
self.desc.base,
pos_default_flag,
dy_ptr,
pos_ptr,
dx_ptr,
core::ptr::null_mut(),
0,
stream_ptr,
),
_ => {
return Err(Error::Unsupported(
"baracuda-kernels::RopeBackwardPlan::run reached an unimplemented dtype",
));
}
}
}
};
map_status(status)
}
}