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
//! Matmul against a transposed B operand: `matmul_bt_kernel`.
//!
//! Split out of the general matmul kernel: B arrives as the contiguous `[N, K]`
//! buffer a transposed weight matrix already owns, so the index arithmetic and
//! the dispatch differ from [`super::matmul_kernel`] even though the
//! result is the same.
use crate;
/// Does [`matmul_bt_kernel`] agree bit for bit with [`super::matmul_kernel`] on
/// a materialized B, for this dtype and shape?
///
/// True only where both run the tiled kernel over identical packed panels: f32
/// and f64, at a shape the tiled path takes. Every other case reaches the
/// transposed layout through a different kernel — half floats convert B
/// wholesale, integers and narrow floats dot-product with a wide accumulator —
/// which agrees within tolerance but accumulates in its own order. A caller
/// that must not change results materializes B for those.
/// Matrix multiplication with a transposed B operand: C = A @ B
///
/// `b_nk` holds the logical `[K, N]` operand as a contiguous `[N, K]` buffer,
/// which is what a `[K, N]` view with strides `[1, K]` points at. The matrix is
/// never materialized: the tiled kernel packs its B panels directly out of that
/// buffer, producing panels byte-identical to the ones a materialized operand
/// would give. Shapes and dtypes the tiled path does not cover fall back to the
/// dot-product kernel, which agrees within tolerance but not bit for bit — see
/// [`matmul_bt_matches_contiguous`].
///
/// # Why this exists
///
/// Every `Linear::forward` multiplies against a transposed weight view. Making
/// that view contiguous copied the whole weight matrix per call: a profiled
/// VoxCPM2 decode moved ~50 GB through `copy_strided` over four generated
/// patches, and 41% of all program instructions landed under
/// `Tensor::contiguous` on that path.
///
/// # Arguments
/// * `a` - Pointer to matrix A (m × k), contiguous row-major (row stride `k`)
/// * `b_nk` - Pointer to B in `[N, K]` layout, contiguous (row stride `k`)
/// * `out` - Pointer to output C (m × n), row-major with leading dimension `ldc`
/// * `m`, `n`, `k` - Matrix dimensions of the logical product
/// * `ldc` - Leading dimension of the output
///
/// # Safety
/// - `a` must be valid for `m * k` contiguous reads
/// - `b_nk` must be valid for `n * k` contiguous reads
/// - `out` must be valid for `m * ldc` writes
/// - `out` must not alias `a` or `b_nk`
pub unsafe