numr 0.12.0

High-performance numerical computing with multi-backend GPU acceleration (CPU/CUDA/WebGPU)
Documentation
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
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
//! CUDA implementation of GEMM epilogue operations.

#[cfg(feature = "fp8")]
use crate::dtype::DType;
use crate::error::{Error, Result};
#[cfg(feature = "fp8")]
use crate::ops::TypeConversionOps;
use crate::ops::matmul::matmul_mkn;
use crate::ops::{
    GemmActivation, GemmEpilogueOps, ReduceOps, ShapeOps, matmul_bias_output_shape,
    validate_gemm_epilogue_dtypes,
};
use crate::runtime::cuda::kernels::{
    launch_gemm_bias_act_bwd_batched_kernel, launch_gemm_bias_act_bwd_kernel,
};
use crate::runtime::cuda::ops::helpers::{
    gemm_bias_act_batched_native, gemm_bias_act_native, gemm_bias_residual_batched_native,
    gemm_bias_residual_native,
};
use crate::runtime::cuda::ops::matmul_broadcast::expand_batched_operands;
use crate::runtime::cuda::ops::wmma_pad::pad_ab_for_wmma;
use crate::runtime::cuda::{CudaClient, CudaRuntime};
use crate::runtime::{Device, ensure_contiguous};
use crate::tensor::Tensor;

impl GemmEpilogueOps<CudaRuntime> for CudaClient {
    fn matmul_bias_activation(
        &self,
        a: &Tensor<CudaRuntime>,
        b: &Tensor<CudaRuntime>,
        bias: &Tensor<CudaRuntime>,
        activation: GemmActivation,
    ) -> Result<Tensor<CudaRuntime>> {
        let dtype = validate_gemm_epilogue_dtypes(
            a.dtype(),
            b.dtype(),
            bias.dtype(),
            "matmul_bias_activation",
        )?;

        // FP8: compute in F32 (tiled GEMM with shared memory needs native arithmetic)
        #[cfg(feature = "fp8")]
        if dtype == DType::FP8E4M3 || dtype == DType::FP8E5M2 {
            let a_f32 = self.cast(a, DType::F32)?;
            let b_f32 = self.cast(b, DType::F32)?;
            let bias_f32 = self.cast(bias, DType::F32)?;
            let result = self.matmul_bias_activation(&a_f32, &b_f32, &bias_f32, activation)?;
            return self.cast(&result, dtype);
        }

        if bias.shape().len() != 1 {
            return Err(Error::InvalidArgument {
                arg: "bias",
                reason: format!("bias must be 1D tensor, got shape {:?}", bias.shape()),
            });
        }

        let a_shape = a.shape();
        let b_shape = b.shape();
        let (m, k, n) = matmul_mkn(a_shape, b_shape);

        let out_shape = matmul_bias_output_shape(a_shape, b_shape, bias.shape()).ok_or(
            Error::ShapeMismatch {
                expected: a_shape.to_vec(),
                got: b_shape.to_vec(),
            },
        )?;

        // Unclamped: an unbatched matmul takes 0 dims and already products to 1, so
        // a clamp would only fabricate a batch for a genuinely zero batch dim — and
        // then pick the single-matmul branch, writing one m*n tile into an empty
        // allocation.
        let batch_size: usize = out_shape
            .iter()
            .take(out_shape.len().saturating_sub(2))
            .product();

        // A zero-element output has nothing to compute. The launchers derive their
        // grid from `m`, `n` and the batch count without flooring them, and a grid
        // extent of 0 is a launch error, so return before any launch.
        if out_shape.iter().product::<usize>() == 0 {
            return Tensor::<CudaRuntime>::empty(&out_shape, dtype, &self.device);
        }

        // The WMMA kernel handles any M, N, K: it zero-fills past every edge and
        // masks its store. A row stride (K for A, N for B) that is not a multiple
        // of `WMMA_STAGE_HALVES` makes the kernel stage that operand one element
        // at a time, a fixed fraction of the GEMM's work; a pad costs one pass
        // over each copied operand. Padding happens only when the GEMM is heavy
        // enough per copied element for the copy to pay
        // (`WMMA_PAD_MIN_WORK_PER_COPIED_ELEMENT`); every other shape, ragged M
        // included, launches as it is. Same rule as plain matmul and matmul_bias
        // (src/ops/cuda/matmul.rs), and it applies per slice, so the batched form
        // pads the same way: `pad` leaves the leading batch dims as they are.
        // `use_wmma_after_padding` is the complement of the launcher's own
        // `use_wmma`, so the padding decision cannot disagree with the dispatch
        // decision.
        //
        // Zero-padding is exact: the extra K contributes 0 to the accumulator, and
        // the extra N columns, where the bias and the activation still apply, are
        // sliced off before the result is returned.
        //
        // Rank-1 operands never pad: the spec addresses two dims of each.
        // `pad_ab_for_wmma` (runtime/cuda/ops/wmma_pad.rs) carries the decision
        // and the pad itself, shared with matmul/matmul_bias, matmul_bias_residual
        // below, and matmul_wide.
        let caps = self.device.profile().caps;
        if let Some((a_pad, b_pad, n_pad, k_pad)) =
            pad_ab_for_wmma(self, a, b, dtype, caps, m, n, k)?
        {
            // bias is 1-D [n], so it takes a two-element padding spec.
            let bias_pad = self.pad(bias, &[0, n_pad - n], 0.0)?;
            let out_pad_shape =
                matmul_bias_output_shape(a_pad.shape(), b_pad.shape(), bias_pad.shape()).ok_or(
                    Error::ShapeMismatch {
                        expected: a_pad.shape().to_vec(),
                        got: b_pad.shape().to_vec(),
                    },
                )?;
            let out_pad = if batch_size > 1 {
                gemm_bias_act_batched_native(
                    self,
                    &a_pad,
                    &b_pad,
                    &bias_pad,
                    dtype,
                    &out_pad_shape,
                    batch_size,
                    m,
                    n_pad,
                    k_pad,
                    activation,
                )?
            } else {
                gemm_bias_act_native(
                    self,
                    &a_pad,
                    &b_pad,
                    &bias_pad,
                    dtype,
                    &out_pad_shape,
                    m,
                    n_pad,
                    k_pad,
                    activation,
                )?
            };
            // Slice N (last dim) back via negative indexing, NOT dim 1: the output
            // can carry leading batch dims.
            return out_pad.narrow(-1, 0, n)?.contiguous();
        }

        if batch_size > 1 {
            return gemm_bias_act_batched_native(
                self, a, b, bias, dtype, &out_shape, batch_size, m, n, k, activation,
            );
        }
        gemm_bias_act_native(self, a, b, bias, dtype, &out_shape, m, n, k, activation)
    }

    fn matmul_bias_residual(
        &self,
        a: &Tensor<CudaRuntime>,
        b: &Tensor<CudaRuntime>,
        bias: &Tensor<CudaRuntime>,
        residual: &Tensor<CudaRuntime>,
    ) -> Result<Tensor<CudaRuntime>> {
        let dtype = validate_gemm_epilogue_dtypes(
            a.dtype(),
            b.dtype(),
            bias.dtype(),
            "matmul_bias_residual",
        )?;

        // FP8: compute in F32
        #[cfg(feature = "fp8")]
        if dtype == DType::FP8E4M3 || dtype == DType::FP8E5M2 {
            let a_f32 = self.cast(a, DType::F32)?;
            let b_f32 = self.cast(b, DType::F32)?;
            let bias_f32 = self.cast(bias, DType::F32)?;
            let res_f32 = self.cast(residual, DType::F32)?;
            let result = self.matmul_bias_residual(&a_f32, &b_f32, &bias_f32, &res_f32)?;
            return self.cast(&result, dtype);
        }

        if residual.dtype() != dtype {
            return Err(Error::DTypeMismatch {
                lhs: dtype,
                rhs: residual.dtype(),
            });
        }

        let a_shape = a.shape();
        let b_shape = b.shape();

        let out_shape = matmul_bias_output_shape(a_shape, b_shape, bias.shape()).ok_or(
            Error::ShapeMismatch {
                expected: a_shape.to_vec(),
                got: b_shape.to_vec(),
            },
        )?;

        if residual.shape() != out_shape.as_slice() {
            return Err(Error::ShapeMismatch {
                expected: out_shape.clone(),
                got: residual.shape().to_vec(),
            });
        }

        let (m, k, n) = matmul_mkn(a_shape, b_shape);

        // Unclamped: an unbatched matmul takes 0 dims and already products to 1, so
        // a clamp would only fabricate a batch for a genuinely zero batch dim — and
        // then pick the single-matmul branch, writing one m*n tile into an empty
        // allocation.
        let batch_size: usize = out_shape
            .iter()
            .take(out_shape.len().saturating_sub(2))
            .product();

        // A zero-element output has nothing to compute. The launchers derive their
        // grid from `m`, `n` and the batch count without flooring them, and a grid
        // extent of 0 is a launch error, so return before any launch.
        if out_shape.iter().product::<usize>() == 0 {
            return Tensor::<CudaRuntime>::empty(&out_shape, dtype, &self.device);
        }

        // Same WMMA padding rule as matmul_bias_activation above, batched
        // included. The residual is shaped like the output, so it takes the 2-D
        // padding spec A and B take, NOT the 1-D one the bias takes: padding it
        // as a vector would shift every row and corrupt the interior, not just
        // the edge.
        let caps = self.device.profile().caps;
        if let Some((a_pad, b_pad, n_pad, k_pad)) =
            pad_ab_for_wmma(self, a, b, dtype, caps, m, n, k)?
        {
            let bias_pad = self.pad(bias, &[0, n_pad - n], 0.0)?;
            let res_pad = self.pad(residual, &[0, n_pad - n, 0, 0], 0.0)?;
            let out_pad_shape =
                matmul_bias_output_shape(a_pad.shape(), b_pad.shape(), bias_pad.shape()).ok_or(
                    Error::ShapeMismatch {
                        expected: a_pad.shape().to_vec(),
                        got: b_pad.shape().to_vec(),
                    },
                )?;
            let out_pad = if batch_size > 1 {
                gemm_bias_residual_batched_native(
                    self,
                    &a_pad,
                    &b_pad,
                    &bias_pad,
                    &res_pad,
                    dtype,
                    &out_pad_shape,
                    batch_size,
                    m,
                    n_pad,
                    k_pad,
                )?
            } else {
                gemm_bias_residual_native(
                    self,
                    &a_pad,
                    &b_pad,
                    &bias_pad,
                    &res_pad,
                    dtype,
                    &out_pad_shape,
                    m,
                    n_pad,
                    k_pad,
                )?
            };
            return out_pad.narrow(-1, 0, n)?.contiguous();
        }

        if batch_size > 1 {
            return gemm_bias_residual_batched_native(
                self, a, b, bias, residual, dtype, &out_shape, batch_size, m, n, k,
            );
        }
        gemm_bias_residual_native(self, a, b, bias, residual, dtype, &out_shape, m, n, k)
    }

    fn matmul_bias_activation_bwd(
        &self,
        grad: &Tensor<CudaRuntime>,
        a: &Tensor<CudaRuntime>,
        b: &Tensor<CudaRuntime>,
        bias: &Tensor<CudaRuntime>,
        activation: GemmActivation,
    ) -> Result<(
        Tensor<CudaRuntime>,
        Tensor<CudaRuntime>,
        Tensor<CudaRuntime>,
    )> {
        let dtype = validate_gemm_epilogue_dtypes(
            a.dtype(),
            b.dtype(),
            bias.dtype(),
            "matmul_bias_activation_bwd",
        )?;
        if grad.dtype() != dtype {
            return Err(Error::DTypeMismatch {
                lhs: dtype,
                rhs: grad.dtype(),
            });
        }

        let a_shape = a.shape();
        let b_shape = b.shape();
        let out_shape = matmul_bias_output_shape(a_shape, b_shape, bias.shape()).ok_or(
            Error::ShapeMismatch {
                expected: a_shape.to_vec(),
                got: b_shape.to_vec(),
            },
        )?;
        if grad.shape() != out_shape.as_slice() {
            return Err(Error::ShapeMismatch {
                expected: out_shape,
                got: grad.shape().to_vec(),
            });
        }
        let (m, k, n) = matmul_mkn(a_shape, b_shape);

        // Unclamped: an unbatched matmul takes 0 dims and already products to 1, so
        // a clamp would only fabricate a batch for a genuinely zero batch dim — and
        // then pick the single-matmul branch, writing one m*n tile into an empty
        // allocation.
        let batch_size: usize = out_shape
            .iter()
            .take(out_shape.len().saturating_sub(2))
            .product();

        // The batched launcher reads both operands with one shared batch stride
        // and writes one gradient slice per batch, so a broadcast operand is
        // expanded on device first and its gradient summed back afterwards.
        let (a_full, b_full) = expand_batched_operands(a, b, &out_shape)?;
        let bias_contig = ensure_contiguous(bias)?;
        let grad_contig = ensure_contiguous(grad)?;

        let d_a = Tensor::<CudaRuntime>::empty(a_full.shape(), dtype, &self.device)?;
        let d_b = Tensor::<CudaRuntime>::empty(b_full.shape(), dtype, &self.device)?;
        let d_bias = Tensor::<CudaRuntime>::zeros(&[n], dtype, &self.device)?;

        // No batch contributes, so every gradient sums over nothing and stays at the
        // additive identity. A zero `m`, `n` or `k` still reaches the launcher,
        // which skips only the individual kernels whose own output is empty —
        // `d_bias` is a real sum even when `k == 0`.
        if batch_size == 0 {
            return Ok((
                Tensor::<CudaRuntime>::zeros(a_shape, dtype, &self.device)?,
                Tensor::<CudaRuntime>::zeros(b_shape, dtype, &self.device)?,
                d_bias,
            ));
        }

        // Temporary buffer for grad_pre (M * N elements, reused per batch)
        let grad_pre = Tensor::<CudaRuntime>::empty(&[m, n], dtype, &self.device)?;

        unsafe {
            if batch_size > 1 {
                launch_gemm_bias_act_bwd_batched_kernel(
                    &self.context,
                    &self.stream,
                    self.device.index,
                    dtype,
                    grad_contig.ptr(),
                    a_full.ptr(),
                    b_full.ptr(),
                    bias_contig.ptr(),
                    grad_pre.ptr(),
                    d_a.ptr(),
                    d_b.ptr(),
                    d_bias.ptr(),
                    batch_size,
                    m,
                    n,
                    k,
                    activation,
                )?;
            } else {
                launch_gemm_bias_act_bwd_kernel(
                    &self.context,
                    &self.stream,
                    self.device.index,
                    dtype,
                    grad_contig.ptr(),
                    a_full.ptr(),
                    b_full.ptr(),
                    bias_contig.ptr(),
                    grad_pre.ptr(),
                    d_a.ptr(),
                    d_b.ptr(),
                    d_bias.ptr(),
                    m,
                    n,
                    k,
                    activation,
                )?;
            }
        }

        let d_a = reduce_to_operand_shape(self, &d_a, a_shape)?;
        let d_b = reduce_to_operand_shape(self, &d_b, b_shape)?;
        Ok((d_a, d_b, d_bias))
    }
}

/// Sum a per-batch gradient `[..out batch, r, c]` back over the batch dims
/// the operand `[..own batch, r, c]` did not carry, or carried as 1.
///
/// Both shapes hold the same trailing two dims. The operand's batch dims are
/// right-aligned against the gradient's; a gradient dim the operand lacks, or
/// holds as 1 while the gradient's is larger, is summed away, and the result
/// is reshaped to the operand's exact shape.
fn reduce_to_operand_shape(
    client: &CudaClient,
    grad: &Tensor<CudaRuntime>,
    operand_shape: &[usize],
) -> Result<Tensor<CudaRuntime>> {
    let grad_shape = grad.shape();
    if grad_shape == operand_shape {
        return Ok(grad.clone());
    }
    let grad_batch = grad_shape.len().saturating_sub(2);
    let own_batch = operand_shape.len().saturating_sub(2);
    let offset = grad_batch - own_batch;
    let dims: Vec<usize> = (0..grad_batch)
        .filter(|&d| d < offset || operand_shape[d - offset] != grad_shape[d])
        .collect();
    let summed = client.sum(grad, &dims, false)?;
    summed.reshape(operand_shape)
}