oa/ml/nn/
quantized_linear.rs1use crate::ml::matrix::{self as ml_matrix, QuantMatrix, Quantization};
4use crate::{Error, Matrix, Result, matrix};
5
6use super::super::module::{Module, ModuleRegistry};
7
8pub 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 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 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 pub const fn input_features(&self) -> usize {
77 self.input_features
78 }
79
80 pub const fn output_features(&self) -> usize {
82 self.output_features
83 }
84
85 pub const fn quantization(&self) -> Quantization {
87 self.weight.quantization()
88 }
89
90 pub const fn weight(&self) -> &QuantMatrix {
92 &self.weight
93 }
94
95 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}