numr 0.8.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
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
//! Matrix multiplication helpers
//!
//! This module contains helper types and functions for matrix multiplication.
//! The actual operations are defined in the `TensorOps` trait.

/// Matrix multiplication parameters
#[derive(Copy, Clone, Debug)]
pub struct MatmulParams {
    /// Number of rows in A (M)
    pub m: usize,
    /// Number of columns in A / rows in B (K)
    pub k: usize,
    /// Number of columns in B (N)
    pub n: usize,
    /// Whether A is transposed
    pub trans_a: bool,
    /// Whether B is transposed
    pub trans_b: bool,
    /// Batch size (1 for regular matmul)
    pub batch: usize,
}

impl MatmulParams {
    /// Create params for standard matmul: C`[M,N]` = A`[M,K]` @ B`[K,N]`
    pub fn new(m: usize, k: usize, n: usize) -> Self {
        Self {
            m,
            k,
            n,
            trans_a: false,
            trans_b: false,
            batch: 1,
        }
    }

    /// Create params for batched matmul
    pub fn batched(batch: usize, m: usize, k: usize, n: usize) -> Self {
        Self {
            m,
            k,
            n,
            trans_a: false,
            trans_b: false,
            batch,
        }
    }

    /// Set A transposition
    pub fn with_trans_a(mut self, trans: bool) -> Self {
        self.trans_a = trans;
        self
    }

    /// Set B transposition
    pub fn with_trans_b(mut self, trans: bool) -> Self {
        self.trans_b = trans;
        self
    }

    /// Output shape
    pub fn output_shape(&self) -> Vec<usize> {
        if self.batch > 1 {
            vec![self.batch, self.m, self.n]
        } else {
            vec![self.m, self.n]
        }
    }
}

/// Validate matmul shapes and return dimensions (m, k, n)
///
/// Returns None if shapes are incompatible.
pub fn validate_matmul_shapes(
    a_shape: &[usize],
    b_shape: &[usize],
) -> Option<(usize, usize, usize)> {
    // Handle 1D vectors
    let (a_rows, a_cols) = match a_shape.len() {
        0 => return None,
        1 => (1, a_shape[0]),
        _ => {
            let ndim = a_shape.len();
            (a_shape[ndim - 2], a_shape[ndim - 1])
        }
    };

    let (b_rows, b_cols) = match b_shape.len() {
        0 => return None,
        1 => (b_shape[0], 1),
        _ => {
            let ndim = b_shape.len();
            (b_shape[ndim - 2], b_shape[ndim - 1])
        }
    };

    // Inner dimensions must match
    if a_cols != b_rows {
        return None;
    }

    Some((a_rows, a_cols, b_cols))
}

/// Compute output shape for matmul
pub fn matmul_output_shape(a_shape: &[usize], b_shape: &[usize]) -> Option<Vec<usize>> {
    let (m, _k, n) = validate_matmul_shapes(a_shape, b_shape)?;

    // Handle batched matmul
    let a_batch: Vec<_> = a_shape
        .iter()
        .take(a_shape.len().saturating_sub(2))
        .copied()
        .collect();
    let b_batch: Vec<_> = b_shape
        .iter()
        .take(b_shape.len().saturating_sub(2))
        .copied()
        .collect();

    // Broadcast batch dimensions
    let batch = super::broadcast_shape(&a_batch, &b_batch)?;

    let mut result = batch;
    result.push(m);
    result.push(n);
    Some(result)
}

/// Map each output batch to the batch index each operand should read.
///
/// Batch dims broadcast per dimension, so an operand's batch count is not enough
/// to locate its data: with `A[2, 4, m, k] @ B[2, 1, k, n]` the output has 8
/// batches while `B` has 2, and `B`'s index advances only every 4 outputs.
/// Treating an operand as "broadcast everything" or "same batch as output" reads
/// out of bounds for any case in between.
///
/// Returns `(a_indices, b_indices)`, both of length `prod(out_shape[..-2])`.
pub fn matmul_batch_indices(
    a_shape: &[usize],
    b_shape: &[usize],
    out_shape: &[usize],
) -> (Vec<usize>, Vec<usize>) {
    let out_batch = &out_shape[..out_shape.len().saturating_sub(2)];
    let a_batch = &a_shape[..a_shape.len().saturating_sub(2)];
    let b_batch = &b_shape[..b_shape.len().saturating_sub(2)];

    // No `.max(1)`: an unbatched matmul already products to 1 over the empty slice.
    // Clamping a zero batch dim to 1 entered the loop below and panicked on `rem % 0`.
    let total: usize = out_batch.iter().product();
    let mut a_indices = Vec::with_capacity(total);
    let mut b_indices = Vec::with_capacity(total);
    let mut coord = vec![0usize; out_batch.len()];

    // Operand batch dims are right-aligned against the output's, and a size-1 dim
    // holds index 0 while the output coordinate advances.
    let project = |coord: &[usize], batch: &[usize]| -> usize {
        let offset = coord.len() - batch.len();
        let mut idx = 0;
        for (d, &size) in batch.iter().enumerate() {
            let c = if size == 1 { 0 } else { coord[offset + d] };
            idx = idx * size + c;
        }
        idx
    };

    for flat in 0..total {
        let mut rem = flat;
        for d in (0..out_batch.len()).rev() {
            coord[d] = rem % out_batch[d];
            rem /= out_batch[d];
        }
        a_indices.push(project(&coord, a_batch));
        b_indices.push(project(&coord, b_batch));
    }

    (a_indices, b_indices)
}

/// `(m, k, n)` of a matmul from its operand shapes, under the same rank-1
/// rule as [`validate_matmul_shapes`] and [`matmul_output_shape`]: a rank-1
/// `a` is a `[1, k]` row and a rank-1 `b` is a `[k, 1]` column, so `n == 1`.
///
/// Every backend derives its kernel geometry from this, so an operand rank
/// the output shape treats one way cannot be read another way by a kernel.
/// Assumes the shapes already passed validation; `k` is read from `a`.
pub fn matmul_mkn(a_shape: &[usize], b_shape: &[usize]) -> (usize, usize, usize) {
    let m = if a_shape.len() >= 2 {
        a_shape[a_shape.len() - 2]
    } else {
        1
    };
    let k = a_shape[a_shape.len() - 1];
    let n = if b_shape.len() >= 2 {
        b_shape[b_shape.len() - 1]
    } else {
        1
    };
    (m, k, n)
}

/// `m`, `k`, `n` and the per-operand batch indices shared by `matmul` and
/// `matmul_wide` on every backend: both dispatch the same shape and batch
/// arithmetic before picking a kernel path.
///
/// Returns `(m, k, n, batch_size, a_batch_idx, b_batch_idx)`.
pub fn matmul_dims_and_batches(
    a_shape: &[usize],
    b_shape: &[usize],
    out_shape: &[usize],
) -> (usize, usize, usize, usize, Vec<usize>, Vec<usize>) {
    let (m, k, n) = matmul_mkn(a_shape, b_shape);

    // No `.max(1)`: 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.
    let batch_size: usize = out_shape
        .iter()
        .take(out_shape.len().saturating_sub(2))
        .product();

    let (a_batch_idx, b_batch_idx) = matmul_batch_indices(a_shape, b_shape, out_shape);

    (m, k, n, batch_size, a_batch_idx, b_batch_idx)
}

/// Is `B` a plain transpose of a contiguous `[.., N, K]` buffer?
///
/// A `[K, N]` operand with strides `[1, K]` is the transposed view of a
/// contiguous `[N, K]` weight matrix — the layout every `Linear` weight has.
/// Backends that can read that layout directly skip materializing the view,
/// which otherwise copies the whole weight matrix on every call.
///
/// Returns true only when the underlying buffer is densely packed as
/// `[.., N, K]`, so a batch `i` of the operand starts at element `i * N * K`:
/// - the last two strides are exactly `[1, K]` (this rejects stride 0 and every
///   negative stride, neither of which is a simple transpose)
/// - every batch dim of size > 1 carries the dense stride for that layout
///   (a size-1 dim always projects to index 0, so its stride is irrelevant)
/// - `K` and `N` are both non-zero, so the stride pattern is unambiguous
pub fn is_transposed_b(b_shape: &[usize], b_strides: &[isize], k: usize, n: usize) -> bool {
    let ndim = b_shape.len();
    if ndim < 2 || b_strides.len() != ndim || k == 0 || n == 0 {
        return false;
    }
    if b_strides[ndim - 2] != 1 || b_strides[ndim - 1] != k as isize {
        return false;
    }

    // Batch dims, right to left: dense packing of `[.., N, K]`.
    let mut expected = (n * k) as isize;
    for d in (0..ndim - 2).rev() {
        if b_shape[d] != 1 && b_strides[d] != expected {
            return false;
        }
        expected *= b_shape[d] as isize;
    }
    true
}

/// Validate matmul_bias shapes and return dimensions (m, k, n)
///
/// Checks that:
/// - A and B are compatible for matmul (inner dimensions match)
/// - bias is 1D
/// - bias length matches output columns (N)
///
/// Returns None if shapes are incompatible.
pub fn validate_matmul_bias_shapes(
    a_shape: &[usize],
    b_shape: &[usize],
    bias_shape: &[usize],
) -> Option<(usize, usize, usize)> {
    // First validate matmul shapes
    let (m, k, n) = validate_matmul_shapes(a_shape, b_shape)?;

    // Bias must be 1D
    if bias_shape.len() != 1 {
        return None;
    }

    // Bias length must match output columns (N)
    if bias_shape[0] != n {
        return None;
    }

    Some((m, k, n))
}

/// Compute output shape for matmul_bias
///
/// Same as matmul_output_shape - bias doesn't change output dimensions.
pub fn matmul_bias_output_shape(
    a_shape: &[usize],
    b_shape: &[usize],
    bias_shape: &[usize],
) -> Option<Vec<usize>> {
    // Validate bias shape
    validate_matmul_bias_shapes(a_shape, b_shape, bias_shape)?;

    // Output shape is same as matmul
    matmul_output_shape(a_shape, b_shape)
}

// The matmul_bias dtype rule lives in `ops/matmul_dtype.rs`: it is shared with
// the GEMM epilogue and carries the I8 widening exception.

#[cfg(test)]
mod tests {
    use super::*;

    /// A rank-1 `b` is a column: `n == 1`, matching `matmul_output_shape`.
    #[test]
    fn test_matmul_mkn_rank1_operands() {
        assert_eq!(matmul_mkn(&[5, 7], &[7]), (5, 7, 1));
        assert_eq!(matmul_mkn(&[7], &[7, 3]), (1, 7, 3));
        assert_eq!(matmul_mkn(&[7], &[7]), (1, 7, 1));
        assert_eq!(matmul_output_shape(&[5, 7], &[7]), Some(vec![5, 1]));
        assert_eq!(matmul_output_shape(&[3, 5, 7], &[7]), Some(vec![3, 5, 1]));
        let (m, k, n, batch, a_idx, b_idx) = matmul_dims_and_batches(&[3, 5, 7], &[7], &[3, 5, 1]);
        assert_eq!((m, k, n, batch), (5, 7, 1, 3));
        assert_eq!(a_idx, vec![0, 1, 2]);
        assert_eq!(b_idx, vec![0, 0, 0]);
    }

    /// A middle batch dim broadcasting under a leading batch > 1: B's index must
    /// advance once every 4 outputs, which a batch count alone cannot express.
    #[test]
    fn test_matmul_batch_indices_middle_broadcast() {
        let (a, b) = matmul_batch_indices(&[2, 4, 3, 2], &[2, 1, 2, 1], &[2, 4, 3, 1]);
        assert_eq!(a, vec![0, 1, 2, 3, 4, 5, 6, 7]);
        assert_eq!(b, vec![0, 0, 0, 0, 1, 1, 1, 1]);
    }

    /// A leading broadcast dim does cycle, which is why wrapping by a count
    /// appeared to work.
    #[test]
    fn test_matmul_batch_indices_leading_broadcast() {
        let (a, b) = matmul_batch_indices(&[2, 4, 3, 2], &[1, 4, 2, 3], &[2, 4, 3, 3]);
        assert_eq!(a, vec![0, 1, 2, 3, 4, 5, 6, 7]);
        assert_eq!(b, vec![0, 1, 2, 3, 0, 1, 2, 3]);
    }

    #[test]
    fn test_matmul_batch_indices_fewer_batch_dims() {
        // B's batch dims are right-aligned against the output's.
        let (a, b) = matmul_batch_indices(&[2, 4, 3, 2], &[4, 2, 3], &[2, 4, 3, 3]);
        assert_eq!(a, vec![0, 1, 2, 3, 4, 5, 6, 7]);
        assert_eq!(b, vec![0, 1, 2, 3, 0, 1, 2, 3]);
    }

    #[test]
    fn test_matmul_batch_indices_both_broadcast() {
        let (a, b) = matmul_batch_indices(&[2, 1, 3, 2], &[1, 4, 2, 3], &[2, 4, 3, 3]);
        assert_eq!(a, vec![0, 0, 0, 0, 1, 1, 1, 1]);
        assert_eq!(b, vec![0, 1, 2, 3, 0, 1, 2, 3]);
    }

    #[test]
    fn test_matmul_batch_indices_unbatched() {
        let (a, b) = matmul_batch_indices(&[3, 2], &[2, 4], &[3, 4]);
        assert_eq!(a, vec![0]);
        assert_eq!(b, vec![0]);
    }

    #[test]
    fn test_validate_matmul_shapes() {
        // Valid 2D matmul
        assert_eq!(validate_matmul_shapes(&[2, 3], &[3, 4]), Some((2, 3, 4)));

        // Invalid: inner dimensions don't match
        assert_eq!(validate_matmul_shapes(&[2, 3], &[4, 5]), None);

        // 1D vectors
        assert_eq!(validate_matmul_shapes(&[3], &[3, 4]), Some((1, 3, 4)));
        assert_eq!(validate_matmul_shapes(&[2, 3], &[3]), Some((2, 3, 1)));
    }

    #[test]
    fn test_matmul_output_shape() {
        // Basic 2D matmul
        assert_eq!(matmul_output_shape(&[2, 3], &[3, 4]), Some(vec![2, 4]));

        // Batched matmul
        assert_eq!(
            matmul_output_shape(&[5, 2, 3], &[5, 3, 4]),
            Some(vec![5, 2, 4])
        );

        // Broadcast batches
        assert_eq!(
            matmul_output_shape(&[5, 2, 3], &[3, 4]),
            Some(vec![5, 2, 4])
        );
    }

    #[test]
    fn test_validate_matmul_bias_shapes() {
        // Valid: 2D matmul with 1D bias
        assert_eq!(
            validate_matmul_bias_shapes(&[2, 3], &[3, 4], &[4]),
            Some((2, 3, 4))
        );

        // Invalid: inner dimensions don't match
        assert_eq!(validate_matmul_bias_shapes(&[2, 3], &[4, 5], &[5]), None);

        // Invalid: bias is 2D
        assert_eq!(validate_matmul_bias_shapes(&[2, 3], &[3, 4], &[2, 4]), None);

        // Invalid: bias length doesn't match N
        assert_eq!(validate_matmul_bias_shapes(&[2, 3], &[3, 4], &[3]), None);

        // Valid: batched matmul with 1D bias
        assert_eq!(
            validate_matmul_bias_shapes(&[5, 2, 3], &[5, 3, 4], &[4]),
            Some((2, 3, 4))
        );
    }

    #[test]
    fn test_matmul_bias_output_shape() {
        // Basic 2D matmul_bias
        assert_eq!(
            matmul_bias_output_shape(&[2, 3], &[3, 4], &[4]),
            Some(vec![2, 4])
        );

        // Batched matmul_bias
        assert_eq!(
            matmul_bias_output_shape(&[5, 2, 3], &[5, 3, 4], &[4]),
            Some(vec![5, 2, 4])
        );

        // Invalid bias shape returns None
        assert_eq!(matmul_bias_output_shape(&[2, 3], &[3, 4], &[3]), None);
    }

    #[test]
    fn test_is_transposed_b_simple_transpose() {
        // [4, 3] view of a contiguous [3, 4] buffer.
        assert!(is_transposed_b(&[4, 3], &[1, 4], 4, 3));
    }

    #[test]
    fn test_is_transposed_b_rejects_contiguous() {
        // Row-major [4, 3] is not a transpose (unless K == 1, where both agree).
        assert!(!is_transposed_b(&[4, 3], &[3, 1], 4, 3));
    }

    #[test]
    fn test_is_transposed_b_rejects_zero_and_negative_strides() {
        assert!(!is_transposed_b(&[4, 3], &[0, 4], 4, 3));
        assert!(!is_transposed_b(&[4, 3], &[1, -4], 4, 3));
        assert!(!is_transposed_b(&[4, 3], &[-1, 4], 4, 3));
    }

    #[test]
    fn test_is_transposed_b_rejects_degenerate_dims() {
        assert!(!is_transposed_b(&[0, 3], &[1, 0], 0, 3));
        assert!(!is_transposed_b(&[4, 0], &[1, 4], 4, 0));
        assert!(!is_transposed_b(&[3], &[1], 3, 1));
    }

    #[test]
    fn test_is_transposed_b_batched_dense() {
        // [2, 4, 3] view of a contiguous [2, 3, 4] buffer: batch stride 12.
        assert!(is_transposed_b(&[2, 4, 3], &[12, 1, 4], 4, 3));
        assert!(is_transposed_b(&[5, 2, 4, 3], &[24, 12, 1, 4], 4, 3));
    }

    #[test]
    fn test_is_transposed_b_rejects_sliced_batch() {
        // Batch dim striding over a larger buffer: batch i does NOT start at
        // i * N * K, so the flat batch offset would read the wrong matrix.
        assert!(!is_transposed_b(&[2, 4, 3], &[24, 1, 4], 4, 3));
    }

    #[test]
    fn test_is_transposed_b_ignores_size_one_batch_stride() {
        // A size-1 batch dim always projects to index 0.
        assert!(is_transposed_b(&[1, 4, 3], &[999, 1, 4], 4, 3));
    }
}