Skip to main content

oa/ml/nn/
linear.gen.rs

1// @generated by tool/gen/nn/generate.py; DO NOT EDIT.
2// Source: tool/gen/nn/schema/ml/ml_nn_linear.json
3// generator_version=8; schema_sha256=b35cbe29f9a0f111f56227ab6c9de23115312b1c6ad334da3abc6405ae27c3d1
4
5use crate::{Error, Matrix, Result, Runtime};
6
7use super::super::{Module, ModuleRegistry, Parameter, autograd, matrix, random};
8
9// OA donor: oacpp/source/cpp/lib/oa/ml/nn/linear/linear.cpp
10// Adaptation: Preserve existing Rust initialization, parameter versions and autograd; adapt donor structure to ModuleRegistry ownership
11/// Trainable FP32 affine projection using `[output, input]` weight layout.
12pub 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	/// Construct a deterministically initialized linear layer.
48	///
49	/// `seed` controls an independent SplitMix64 Xavier-uniform initializer.
50	///
51	/// # Errors
52	///
53	/// Returns an error when either feature count is zero, shape arithmetic
54	/// overflows, or parameter allocation/upload fails.
55	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	/// Construct a deterministically initialized linear layer with optional bias.
81	///
82	/// A bias-free layer retains a private zero vector required by the current
83	/// physical GEMM ABI, but exposes and registers no fake trainable parameter.
84	///
85	/// # Errors
86	///
87	/// Returns an error when either feature count is zero, shape arithmetic
88	/// overflows, or parameter allocation/upload fails.
89	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	/// Construct a linear layer from exact FP32 weight and bias matrices.
115	///
116	/// # Errors
117	///
118	/// Returns an error unless weight has shape `[O, I]`, bias has shape `[O]`,
119	/// both are nonempty FP32 matrices, and both belong to the same runtime.
120	pub fn new_from_matrices(weight: Matrix, bias: Matrix) -> Result<Self> {
121		Self::new_from_parts(weight, bias, true)
122	}
123
124	/// Construct a bias-free linear layer from an exact FP32 weight matrix.
125	///
126	/// # Errors
127	///
128	/// Returns an error unless weight is a nonempty FP32 `[O, I]` matrix or the
129	/// private physical zero vector cannot be allocated.
130	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	/// Apply this layer to an FP32 Matrix with rank at least two.
187	///
188	/// Leading dimensions are preserved and the final input-feature dimension
189	/// is replaced by the configured output-feature dimension.
190	///
191	/// # Errors
192	///
193	/// Returns an error when the input contract or runtime recording fails.
194	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	/// Return this layer's input feature count.
212	pub const fn input_features(&self) -> usize {
213		self.input_features
214	}
215
216	/// Return this layer's output feature count.
217	pub const fn output_features(&self) -> usize {
218		self.output_features
219	}
220
221	/// Return the stable trainable weight handle.
222	pub fn weight(&self) -> Parameter {
223		self.weight.clone()
224	}
225
226	/// Return the stable trainable bias handle.
227	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	/// Return whether this layer owns a trainable bias.
235	pub fn has_bias(&self) -> bool {
236		matches!(self.bias, LinearBias::Parameter(_))
237	}
238
239	/// Return this layer's parameters in deterministic weight, optional-bias order.
240	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}