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
// RLX — versatile ML compiler + runtime.
// Copyright (C) 2026 Eugene Hauptmann, Nataliya Kosmyna.
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, version 3.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <https://www.gnu.org/licenses/>.
//! Linear-algebra builders: matmul, LoRA, dequant, fused
//! matmul+bias+activation (plan #53).
use crate::op::Activation;
use crate::quant::{QuantScheme, ScaleLayout, ScaledFormat};
use crate::{DType, Graph, NodeId, Op, Shape};
impl Graph {
/// Matrix multiply.
pub fn matmul(&mut self, lhs: NodeId, rhs: NodeId, out_shape: Shape) -> NodeId {
self.push(Op::MatMul, vec![lhs, rhs], out_shape, None)
}
/// Dynamically quantize `x` (logical `[rows, cols]`, blocks along the last
/// axis) to low-precision `fmt` codes plus a scale tensor, per `layout`.
/// Returns `(codes, scale)`: `codes` is `DType::U8` with `x`'s shape;
/// `scale`'s shape/dtype follow the layout (`[1]` f32 for per-tensor,
/// `[rows, cols/block]` u8 for block layouts). The building block of
/// [`scaled_matmul`](Self::scaled_matmul); `fmt` may be any
/// [`ScaledFormat`], including a parameterized [`ScaledFormat::Custom`].
pub fn scaled_quantize(
&mut self,
x: NodeId,
fmt: ScaledFormat,
layout: ScaleLayout,
) -> (NodeId, NodeId) {
let xs = self.node(x).shape.clone();
let cols = xs.dim(xs.rank() - 1).unwrap_static();
let rows = xs.num_elements().unwrap() / cols.max(1);
let scale_shape = match layout {
ScaleLayout::PerTensor => Shape::new(&[1], layout.scale_dtype()),
_ => Shape::new(
&[rows, cols.div_ceil(layout.block() as usize)],
layout.scale_dtype(),
),
};
let scale = self.push(
Op::ScaledQuantScale {
format: fmt,
scale_layout: layout,
},
vec![x],
scale_shape,
None,
);
let codes = self.push(
Op::ScaledQuantize {
format: fmt,
scale_layout: layout,
},
vec![x, scale],
xs.with_dtype(DType::U8),
None,
);
(codes, scale)
}
/// Reconstruct f32 from packed `codes` + `scale` — the inverse of
/// [`scaled_quantize`](Self::scaled_quantize).
pub fn scaled_dequantize(
&mut self,
codes: NodeId,
scale: NodeId,
fmt: ScaledFormat,
layout: ScaleLayout,
) -> NodeId {
let shape = self.node(codes).shape.clone().with_dtype(DType::F32);
self.push(
Op::ScaledDequantize {
format: fmt,
scale_layout: layout,
},
vec![codes, scale],
shape,
None,
)
}
/// Native low-precision GEMM (TN: `lhs [m,k] · rhs [n,k]ᵀ → [m,n]` f32).
/// Both operands are dynamically quantized to `fmt`/`layout` and fed
/// straight into the scaled matmul with f32 accumulation — no hand-wiring of
/// [`Op::ScaledQuantScale`]/[`Op::ScaledQuantize`]. `rhs` must already be
/// K-last (`[n, k]`); transpose a `[k, n]` weight first. `fmt` may be any
/// [`ScaledFormat`], including a parameterized [`ScaledFormat::Custom`]
/// (e.g. `ScaledFormat::custom(3, 0)` for `f4e3m0`).
pub fn scaled_matmul(
&mut self,
lhs: NodeId,
rhs: NodeId,
fmt: ScaledFormat,
layout: ScaleLayout,
) -> NodeId {
self.scaled_matmul_bias(lhs, rhs, None, fmt, layout)
}
/// [`scaled_matmul`](Self::scaled_matmul) with an optional f32 bias `[n]`
/// added to each output row.
pub fn scaled_matmul_bias(
&mut self,
lhs: NodeId,
rhs: NodeId,
bias: Option<NodeId>,
fmt: ScaledFormat,
layout: ScaleLayout,
) -> NodeId {
let m = self.node(lhs).shape.dim(0).unwrap_static();
let n = self.node(rhs).shape.dim(0).unwrap_static();
let (lq, ls) = self.scaled_quantize(lhs, fmt, layout);
let (rq, rs) = self.scaled_quantize(rhs, fmt, layout);
let mut inputs = vec![lq, rq, ls, rs];
if let Some(b) = bias {
inputs.push(b);
}
self.push(
Op::ScaledMatMul {
lhs_format: fmt,
rhs_format: fmt,
scale_layout: layout,
has_bias: bias.is_some(),
},
inputs,
Shape::new(&[m, n], DType::F32),
None,
)
}
/// Dense linear solve `x = A⁻¹·b`. `A` must be `[N, N]`; `b` is
/// `[N]` for a single right-hand side or `[N, K]` for multiple.
/// `out_shape` matches `b`'s shape.
pub fn dense_solve(&mut self, a: NodeId, b: NodeId, out_shape: Shape) -> NodeId {
self.push(Op::DenseSolve, vec![a, b], out_shape, None)
}
/// Batched dense linear solve. `A` is `[B, N, N]`; `b` is
/// `[B, N]` (single-RHS) or `[B, N, K]` (multi-RHS). Per-batch
/// independent — each slice solved as a separate `dense_solve`.
/// Typically constructed by `vmap` of `dense_solve`.
pub fn batched_dense_solve(&mut self, a: NodeId, b: NodeId, out_shape: Shape) -> NodeId {
self.push(Op::BatchedDenseSolve, vec![a, b], out_shape, None)
}
/// Fused LoRA matmul: out = x·W + scale * (x·A)·B.
/// Inputs: x [m, k], w [k, n], a [k, r], b [r, n]. r is the
/// LoRA rank; scale is the alpha/rank coefficient.
pub fn lora_matmul(
&mut self,
x: NodeId,
w: NodeId,
a: NodeId,
b: NodeId,
scale: f32,
shape: Shape,
) -> NodeId {
self.push(Op::LoraMatMul { scale }, vec![x, w, a, b], shape, None)
}
/// Fused dequant + matmul. See [`Op::DequantMatMul`] for per-scheme
/// input layout (4 inputs for legacy/NVFP4, 2 for GGUF).
pub fn dequant_matmul(
&mut self,
x: NodeId,
w_q: NodeId,
scale: NodeId,
zp: NodeId,
scheme: QuantScheme,
shape: Shape,
) -> NodeId {
self.push(
Op::DequantMatMul { scheme },
vec![x, w_q, scale, zp],
shape,
None,
)
}
/// GGUF / K-quant packed weights — `[x, packed_w_bytes]` only.
pub fn dequant_matmul_packed(
&mut self,
x: NodeId,
packed_w: NodeId,
scheme: QuantScheme,
shape: Shape,
) -> NodeId {
debug_assert!(
scheme.is_gguf(),
"dequant_matmul_packed requires a GGUF QuantScheme"
);
self.push(Op::DequantMatMul { scheme }, vec![x, packed_w], shape, None)
}
/// NVFP4 (E2M1) block matmul — group size 16, FP8 block scales,
/// optional f32 global scale (defaults to 1.0 when unset at runtime).
pub fn dequant_matmul_nvfp4(
&mut self,
x: NodeId,
w_q: NodeId,
block_scales: NodeId,
global_scale: NodeId,
shape: Shape,
) -> NodeId {
self.dequant_matmul(
x,
w_q,
block_scales,
global_scale,
QuantScheme::Nvfp4Block,
shape,
)
}
/// Fused matmul + bias + activation (created by optimization passes).
pub fn fused_matmul_bias_act(
&mut self,
input: NodeId,
weight: NodeId,
bias: NodeId,
activation: Option<Activation>,
shape: Shape,
) -> NodeId {
self.push(
Op::FusedMatMulBiasAct { activation },
vec![input, weight, bias],
shape,
None,
)
}
/// Real INT8-arithmetic matmul: i8 inputs, i32 bias, i8 output.
/// `mult = x_scale · w_scale / out_scale`. Caller's responsible
/// for asserting the input dtypes — the builder just plumbs the
/// shape with `dtype = I8` since that's what the kernel writes.
pub fn q_matmul(
&mut self,
x: NodeId,
w: NodeId,
bias: NodeId,
x_zp: i32,
w_zp: i32,
out_zp: i32,
mult: f32,
out_shape: Shape,
) -> NodeId {
debug_assert_eq!(
out_shape.dtype(),
crate::DType::I8,
"q_matmul output dtype must be I8"
);
self.push(
Op::QMatMul {
x_zp,
w_zp,
out_zp,
mult,
},
vec![x, w, bias],
out_shape,
None,
)
}
/// Real INT8-arithmetic 2-D convolution. NCHW layout matching
/// `Op::Conv`. `mult = x_scale · w_scale / out_scale`.
#[allow(clippy::too_many_arguments)]
pub fn q_conv2d(
&mut self,
x: NodeId,
w: NodeId,
bias: NodeId,
kernel_size: Vec<usize>,
stride: Vec<usize>,
padding: Vec<usize>,
dilation: Vec<usize>,
groups: usize,
x_zp: i32,
w_zp: i32,
out_zp: i32,
mult: f32,
out_shape: Shape,
) -> NodeId {
debug_assert_eq!(
out_shape.dtype(),
crate::DType::I8,
"q_conv2d output dtype must be I8"
);
self.push(
Op::QConv2d {
kernel_size,
stride,
padding,
dilation,
groups,
x_zp,
w_zp,
out_zp,
mult,
},
vec![x, w, bias],
out_shape,
None,
)
}
}