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
//! CPU implementation of fused matrix multiplication with bias.
//!
//! Same tiled kernel as plain matmul, with the bias added in the epilogue so
//! the result is not read back for a separate broadcast add.
//!
//! `#[path]`-included into `runtime::cpu::ops`, so `super` here is that module.
use crate::dtype::DType;
use crate::error::{Error, Result};
use crate::runtime::cpu::{
CpuClient, CpuRuntime,
helpers::{dispatch_dtype, ensure_contiguous},
};
use crate::tensor::Tensor;
impl CpuClient {
/// Fused matmul+bias: `C = A @ B + bias`, broadcast over the batch.
///
/// Carries the body of [`crate::ops::MatmulOps::matmul_bias`] for the CPU
/// runtime; the trait method delegates here.
pub(super) fn matmul_bias_impl(
&self,
a: &Tensor<CpuRuntime>,
b: &Tensor<CpuRuntime>,
bias: &Tensor<CpuRuntime>,
) -> Result<Tensor<CpuRuntime>> {
use crate::ops::matmul::matmul_mkn;
use crate::ops::{matmul_bias_output_shape, validate_matmul_bias_dtypes};
use crate::runtime::cpu::kernels::matmul_bias_kernel;
// Validate dtypes using unified helper (ensures consistent error handling across backends)
let dtype = validate_matmul_bias_dtypes(a.dtype(), b.dtype(), bias.dtype())?;
// Compute output shape (also validates bias 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(),
},
)?;
// Get matrix dimensions (last two dims)
let a_shape = a.shape();
let b_shape = b.shape();
let (m, k, n) = matmul_mkn(a_shape, b_shape);
// Require row-major contiguous tensors for SIMD-optimized packing
let a_contig = ensure_contiguous(a)?;
let b_contig = ensure_contiguous(b)?;
let bias_contig = ensure_contiguous(bias)?;
// Calculate batch size from output shape, and per-operand batch sizes for broadcasting
let batch_size: usize = out_shape
.iter()
.take(out_shape.len().saturating_sub(2))
.product();
// 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.
// Batch dims broadcast per dimension, so each output batch needs its own
// source index per operand rather than a single batch count.
let (a_batch_idx, b_batch_idx) =
crate::ops::matmul::matmul_batch_indices(a_shape, b_shape, &out_shape);
// I8 widens to I32 exactly as the plain form does, and the validator
// above has already required the I32 bias that seeds the accumulator.
if dtype == DType::I8 {
return super::matmul_i8::matmul_i8_i32(
self,
&a_contig,
&b_contig,
Some(&bias_contig),
&out_shape,
&a_batch_idx,
&b_batch_idx,
m,
n,
k,
);
}
// Create output tensor
let out = Tensor::<CpuRuntime>::empty(&out_shape, dtype, &self.device)?;
let a_ptr = a_contig.ptr();
let b_ptr = b_contig.ptr();
let bias_ptr = bias_contig.ptr();
let out_ptr = out.ptr();
// Leading dimensions for contiguous row-major matrices
let lda = k;
let ldb = n;
let ldc = n;
// Dispatch based on dtype
dispatch_dtype!(dtype, T => {
#[cfg(feature = "rayon")]
{
if batch_size > 1 {
self.par_for_each(batch_size, batch_size * m * n * k, |batch| unsafe {
let a_offset = a_batch_idx[batch] * m * k;
let b_offset = b_batch_idx[batch] * k * n;
let out_offset = batch * m * n;
matmul_bias_kernel::<T>(
(a_ptr as *const T).add(a_offset),
(b_ptr as *const T).add(b_offset),
bias_ptr as *const T, // bias is 1D, same for all batches
(out_ptr as *mut T).add(out_offset),
m,
n,
k,
lda,
ldb,
ldc,
);
});
} else {
unsafe {
let a_offset = 0;
let b_offset = 0;
let out_offset = 0;
matmul_bias_kernel::<T>(
(a_ptr as *const T).add(a_offset),
(b_ptr as *const T).add(b_offset),
bias_ptr as *const T,
(out_ptr as *mut T).add(out_offset),
m,
n,
k,
lda,
ldb,
ldc,
);
}
}
}
#[cfg(not(feature = "rayon"))]
unsafe {
for batch in 0..batch_size {
let a_offset = a_batch_idx[batch] * m * k;
let b_offset = b_batch_idx[batch] * k * n;
let out_offset = batch * m * n;
matmul_bias_kernel::<T>(
(a_ptr as *const T).add(a_offset),
(b_ptr as *const T).add(b_offset),
bias_ptr as *const T, // bias is 1D, same for all batches
(out_ptr as *mut T).add(out_offset),
m,
n,
k,
lda,
ldb,
ldc,
);
}
}
}, "matmul_bias");
Ok(out)
}
}