1use crate::{Error, Matrix, Result, Runtime};
6
7use super::super::{Module, ModuleRegistry, Parameter, autograd, matrix, random};
8
9pub struct Linear {
13 input_features: usize,
14 output_features: usize,
15 weight: Parameter,
16 bias: LinearBias,
17 registry: ModuleRegistry,
18}
19
20enum LinearBias {
21 Parameter(Parameter),
22 Zero(Matrix),
23}
24
25impl LinearBias {
26 fn snapshot(&self) -> (Matrix, Option<(Parameter, u64)>, bool) {
27 match self {
28 Self::Parameter(parameter) => {
29 let (value, version, requires_grad) = parameter.snapshot();
30 (
31 value,
32 requires_grad.then(|| (parameter.clone(), version)),
33 requires_grad,
34 )
35 }
36 Self::Zero(value) => (value.clone(), None, false),
37 }
38 }
39}
40
41impl Linear {
42 #[allow(clippy::too_many_arguments)]
43 pub fn new_with_seed(input_features: usize, output_features: usize, seed: u64) -> Result<Self> {
44 Self::new_with_seed_on(&Runtime::current()?, input_features, output_features, seed)
45 }
46
47 pub fn new_with_seed_on(
56 runtime: &Runtime,
57 input_features: usize,
58 output_features: usize,
59 seed: u64,
60 ) -> Result<Self> {
61 Self::new_with_seed_and_bias_on(runtime, input_features, output_features, true, seed)
62 }
63
64 #[allow(clippy::too_many_arguments)]
65 pub fn new_with_seed_and_bias(
66 input_features: usize,
67 output_features: usize,
68 trainable_bias: bool,
69 seed: u64,
70 ) -> Result<Self> {
71 Self::new_with_seed_and_bias_on(
72 &Runtime::current()?,
73 input_features,
74 output_features,
75 trainable_bias,
76 seed,
77 )
78 }
79
80 pub fn new_with_seed_and_bias_on(
90 runtime: &Runtime,
91 input_features: usize,
92 output_features: usize,
93 trainable_bias: bool,
94 seed: u64,
95 ) -> Result<Self> {
96 if input_features == 0 || output_features == 0 {
97 return Err(Error::invalid_argument(
98 "linear feature counts must be nonzero",
99 ));
100 }
101 let weight_count = input_features
102 .checked_mul(output_features)
103 .ok_or_else(|| Error::invalid_argument("linear weight size overflows usize"))?;
104 let denominator = input_features
105 .checked_add(output_features)
106 .ok_or_else(|| Error::invalid_argument("linear Xavier extent overflows usize"))?;
107 let limit = (6.0_f32 / denominator as f32).sqrt();
108 let weights = random::symmetric_uniform(weight_count, limit, seed);
109 let weight = Matrix::new_from_f32_on(runtime, [output_features, input_features], &weights)?;
110 let bias = Matrix::new_from_f32_on(runtime, [output_features], &vec![0.0; output_features])?;
111 Self::new_from_parts(weight, bias, trainable_bias)
112 }
113
114 pub fn new_from_matrices(weight: Matrix, bias: Matrix) -> Result<Self> {
121 Self::new_from_parts(weight, bias, true)
122 }
123
124 pub fn new_from_weight(weight: Matrix) -> Result<Self> {
131 let [output_features, input_features] = weight.shape() else {
132 return Err(Error::invalid_argument("linear weight must have rank two"));
133 };
134 if *input_features == 0 || *output_features == 0 || weight.dtype() != crate::DType::F32 {
135 return Err(Error::invalid_argument(
136 "bias-free linear requires nonempty FP32 weight [O, I]",
137 ));
138 }
139 let output_features = *output_features;
140 let zero = Matrix::allocate(
141 weight.runtime(),
142 vec![output_features],
143 output_features,
144 crate::DType::F32,
145 )?;
146 Self::new_from_parts(weight, zero, false)
147 }
148
149 fn new_from_parts(weight: Matrix, bias: Matrix, trainable_bias: bool) -> Result<Self> {
150 let [output_features, input_features] = weight.shape() else {
151 return Err(Error::invalid_argument("linear weight must have rank two"));
152 };
153 if *input_features == 0
154 || *output_features == 0
155 || bias.shape() != [*output_features]
156 || weight.dtype() != crate::DType::F32
157 || bias.dtype() != crate::DType::F32
158 || !weight.runtime().same_as(bias.runtime())
159 {
160 return Err(Error::invalid_argument(
161 "linear requires nonempty same-runtime FP32 weight [O, I] and bias [O]",
162 ));
163 }
164 let input_features = *input_features;
165 let output_features = *output_features;
166 let weight = Parameter::new("weight", weight)?;
167 let bias = if trainable_bias {
168 LinearBias::Parameter(Parameter::new("bias", bias)?)
169 } else {
170 LinearBias::Zero(bias)
171 };
172 let mut registry = ModuleRegistry::new();
173 registry.register_parameter("weight", weight.clone())?;
174 if let LinearBias::Parameter(parameter) = &bias {
175 registry.register_parameter("bias", parameter.clone())?;
176 }
177 Ok(Self {
178 input_features,
179 output_features,
180 weight,
181 bias,
182 registry,
183 })
184 }
185
186 pub fn forward(&self, input: &Matrix) -> Result<Matrix> {
195 let (weight, weight_version, weight_requires_grad) = self.weight.snapshot();
196 let (bias, bias_parameter, bias_requires_grad) = self.bias.snapshot();
197 let output = matrix::linear(input, &weight, &bias)?;
198 if weight_requires_grad || bias_requires_grad {
199 autograd::record_linear(
200 input,
201 &output,
202 self.weight.clone(),
203 weight,
204 weight_version,
205 bias_parameter,
206 )?;
207 }
208 Ok(output)
209 }
210
211 pub const fn input_features(&self) -> usize {
213 self.input_features
214 }
215
216 pub const fn output_features(&self) -> usize {
218 self.output_features
219 }
220
221 pub fn weight(&self) -> Parameter {
223 self.weight.clone()
224 }
225
226 pub fn bias(&self) -> Option<Parameter> {
228 match &self.bias {
229 LinearBias::Parameter(parameter) => Some(parameter.clone()),
230 LinearBias::Zero(_) => None,
231 }
232 }
233
234 pub fn has_bias(&self) -> bool {
236 matches!(self.bias, LinearBias::Parameter(_))
237 }
238
239 pub fn parameters(&self) -> Vec<Parameter> {
241 let mut parameters = vec![self.weight.clone()];
242 if let Some(bias) = self.bias() {
243 parameters.push(bias);
244 }
245 parameters
246 }
247}
248
249impl Module for Linear {
250 fn forward(&self, input: &Matrix) -> Result<Matrix> {
251 Linear::forward(self, input)
252 }
253
254 fn registry(&self) -> &ModuleRegistry {
255 &self.registry
256 }
257}