Skip to main content

oa/ml/nn/
quantized_linear.rs

1//! Inference-only linear layer over a block-quantized weight.
2
3use crate::ml::matrix::{self as ml_matrix, QuantMatrix, Quantization};
4use crate::{Error, Matrix, Result, matrix};
5
6use super::super::module::{Module, ModuleRegistry};
7
8/// Affine map `x @ W^T + b` whose weight stays packed in a [`QuantMatrix`].
9///
10/// `QuantizedLinear` is the model-level quantized-inference contract: the
11/// weight is frozen at quantization time, exposes no trainable parameters,
12/// and the forward pass dequantizes inside the dispatch rather than
13/// materializing an F32 weight on the device. State-dict round-trips run the
14/// standard quantize-on-export flow — checkpoints carry the F32 module and
15/// `from_linear` re-derives the packed planes.
16pub struct QuantizedLinear {
17	input_features: usize,
18	output_features: usize,
19	weight: QuantMatrix,
20	bias: Option<Matrix>,
21	registry: ModuleRegistry,
22}
23
24impl QuantizedLinear {
25	/// Quantize an existing [`super::Linear`]'s weight into `quantization`.
26	///
27	/// The bias, when the source module carries one, moves into this module
28	/// unchanged as a persistent buffer.
29	///
30	/// # Errors
31	///
32	/// Returns an error when the weight fails the [`crate::ml::matrix::quantize`]
33	/// contract or buffer registration fails.
34	pub fn from_linear(linear: &super::Linear, quantization: Quantization) -> Result<Self> {
35		let weight = ml_matrix::quantize(&linear.weight().data(), quantization)?;
36		let bias = linear.bias().map(|bias| bias.data());
37		Self::from_quantized(weight, bias)
38	}
39
40	/// Wrap an already-quantized `[N, K]` weight and optional `[N]` bias.
41	///
42	/// # Errors
43	///
44	/// Returns an error when the weight is not rank 2, the bias is not `[N]`,
45	/// or buffer registration fails.
46	pub fn from_quantized(weight: QuantMatrix, bias: Option<Matrix>) -> Result<Self> {
47		if weight.shape().len() != 2 {
48			return Err(Error::invalid_argument(
49				"QuantizedLinear weight must have rank 2 [N,K]",
50			));
51		}
52		let output_features = weight.shape()[0];
53		let input_features = weight.shape()[1];
54		if let Some(bias) = &bias
55			&& bias.shape() != [output_features]
56		{
57			return Err(Error::invalid_argument(format!(
58				"QuantizedLinear bias must have shape [{output_features}]; found {:?}",
59				bias.shape(),
60			)));
61		}
62		let mut registry = ModuleRegistry::new();
63		if let Some(bias) = &bias {
64			registry.register_buffer("bias", bias.clone(), true)?;
65		}
66		Ok(Self {
67			input_features,
68			output_features,
69			weight,
70			bias,
71			registry,
72		})
73	}
74
75	/// Return the accepted input feature count `K`.
76	pub const fn input_features(&self) -> usize {
77		self.input_features
78	}
79
80	/// Return the produced output feature count `N`.
81	pub const fn output_features(&self) -> usize {
82		self.output_features
83	}
84
85	/// Return the packed weight format.
86	pub const fn quantization(&self) -> Quantization {
87		self.weight.quantization()
88	}
89
90	/// Return the packed weight value.
91	pub const fn weight(&self) -> &QuantMatrix {
92		&self.weight
93	}
94
95	/// Return the optional additive bias, when present.
96	pub const fn bias(&self) -> Option<&Matrix> {
97		self.bias.as_ref()
98	}
99}
100
101impl Module for QuantizedLinear {
102	fn forward(&self, input: &Matrix) -> Result<Matrix> {
103		if input.shape().last() != Some(&self.input_features) {
104			return Err(Error::invalid_argument(format!(
105				"QuantizedLinear requires input last dimension {}; found {:?}",
106				self.input_features,
107				input.shape(),
108			)));
109		}
110		let output = ml_matrix::matmul(input, &self.weight)?;
111		if let Some(bias) = &self.bias {
112			return matrix::add(&output, bias);
113		}
114		Ok(output)
115	}
116
117	fn registry(&self) -> &ModuleRegistry {
118		&self.registry
119	}
120}