Skip to main content

oa/ml/nn/
bilinear.rs

1//! Bilinear layer (`nn.Bilinear`): `y = x1^T W_o x2 + b` per output feature.
2
3use crate::{Error, Matrix, Result, Runtime, matrix};
4
5use super::super::{Module, ModuleRegistry, Parameter, autograd, random};
6
7/// Trainable bilinear interaction `out[n, o] = sum_i,j x1[n,i] W[o,i,j] x2[n,j] + b[o]`.
8///
9/// The weight uses the donor `[O, I1, I2]` layout and Xavier-uniform
10/// initialization matching `nn.Linear`.
11pub struct Bilinear {
12	in1_features: usize,
13	in2_features: usize,
14	out_features: usize,
15	weight: Parameter,
16	bias: Option<Parameter>,
17	registry: ModuleRegistry,
18}
19
20impl Bilinear {
21	/// Construct on the current runtime with the thread-local seed source.
22	///
23	/// # Errors
24	///
25	/// Returns an error when a feature count is zero or initialization fails.
26	pub fn new(in1_features: usize, in2_features: usize, out_features: usize) -> Result<Self> {
27		Self::new_with_seed(in1_features, in2_features, out_features, true, 0)
28	}
29
30	/// Construct on the current runtime with an explicit seed.
31	///
32	/// # Errors
33	///
34	/// Returns an error when a feature count is zero or initialization fails.
35	pub fn new_with_seed(
36		in1_features: usize,
37		in2_features: usize,
38		out_features: usize,
39		trainable_bias: bool,
40		seed: u64,
41	) -> Result<Self> {
42		Self::new_with_seed_on(
43			&Runtime::current()?,
44			in1_features,
45			in2_features,
46			out_features,
47			trainable_bias,
48			seed,
49		)
50	}
51
52	/// Construct on `runtime` with an explicit seed.
53	///
54	/// # Errors
55	///
56	/// Returns an error when a feature count is zero or initialization fails.
57	pub fn new_with_seed_on(
58		runtime: &Runtime,
59		in1_features: usize,
60		in2_features: usize,
61		out_features: usize,
62		trainable_bias: bool,
63		seed: u64,
64	) -> Result<Self> {
65		if in1_features == 0 || in2_features == 0 || out_features == 0 {
66			return Err(Error::invalid_argument(
67				"bilinear feature counts must be nonzero",
68			));
69		}
70		let weight_count = in1_features
71			.checked_mul(in2_features)
72			.and_then(|count| count.checked_mul(out_features))
73			.ok_or_else(|| Error::invalid_argument("bilinear weight size overflows usize"))?;
74		let denominator = in1_features
75			.checked_add(in2_features)
76			.ok_or_else(|| Error::invalid_argument("bilinear Xavier extent overflows usize"))?;
77		let limit = (6.0_f32 / denominator as f32).sqrt();
78		let weights = random::symmetric_uniform(weight_count, limit, seed);
79		let weight = Matrix::new_from_f32_on(
80			runtime,
81			[out_features, in1_features, in2_features],
82			&weights,
83		)?;
84		let bias = Matrix::new_from_f32_on(runtime, [out_features], &vec![0.0; out_features])?;
85		Self::new_from_parts(weight, bias, trainable_bias)
86	}
87
88	/// Construct from exact FP32 weight and bias matrices.
89	///
90	/// # Errors
91	///
92	/// Returns an error unless weight is `[O, I1, I2]` and bias is `[O]` on the
93	/// same runtime.
94	pub fn new_from_matrices(weight: Matrix, bias: Matrix) -> Result<Self> {
95		let [out_features, in1_features, in2_features] = weight.shape().to_vec()[..] else {
96			return Err(Error::invalid_argument(format!(
97				"bilinear weight must be [O, I1, I2]; found {:?}",
98				weight.shape()
99			)));
100		};
101		if bias.shape() != [out_features] || !bias.runtime().same_as(weight.runtime()) {
102			return Err(Error::invalid_argument(format!(
103				"bilinear bias must be [O] on the weight runtime; found {:?}",
104				bias.shape()
105			)));
106		}
107		Self::new_from_parts_unchecked(weight, bias, true, in1_features, in2_features, out_features)
108	}
109
110	fn new_from_parts(weight: Matrix, bias: Matrix, trainable_bias: bool) -> Result<Self> {
111		let [out_features, in1_features, in2_features] = weight.shape().to_vec()[..] else {
112			return Err(Error::invalid_argument(format!(
113				"bilinear weight must be [O, I1, I2]; found {:?}",
114				weight.shape()
115			)));
116		};
117		Self::new_from_parts_unchecked(
118			weight,
119			bias,
120			trainable_bias,
121			in1_features,
122			in2_features,
123			out_features,
124		)
125	}
126
127	fn new_from_parts_unchecked(
128		weight: Matrix,
129		bias: Matrix,
130		trainable_bias: bool,
131		in1_features: usize,
132		in2_features: usize,
133		out_features: usize,
134	) -> Result<Self> {
135		let weight = Parameter::new("weight", weight)?;
136		let bias = if trainable_bias {
137			Some(Parameter::new("bias", bias)?)
138		} else {
139			None
140		};
141		let mut registry = ModuleRegistry::new();
142		registry.register_parameter("weight", weight.clone())?;
143		if let Some(parameter) = &bias {
144			registry.register_parameter("bias", parameter.clone())?;
145		}
146		Ok(Self {
147			in1_features,
148			in2_features,
149			out_features,
150			weight,
151			bias,
152			registry,
153		})
154	}
155
156	/// Return the `[O, I1, I2]` trainable weight.
157	pub fn weight(&self) -> Parameter {
158		self.weight.clone()
159	}
160
161	/// Return the `[O]` trainable bias when present.
162	pub fn bias(&self) -> Option<Parameter> {
163		self.bias.clone()
164	}
165
166	/// Apply the bilinear map to `[N, I1]` and `[N, I2]` inputs.
167	///
168	/// # Errors
169	///
170	/// Returns an error for mismatched ranks, feature extents, batch counts, or
171	/// runtimes, or when the composed dispatch fails.
172	pub fn forward2(&self, input1: &Matrix, input2: &Matrix) -> Result<Matrix> {
173		let operation = "Bilinear";
174		for (input, features) in [(input1, self.in1_features), (input2, self.in2_features)] {
175			if input.shape().len() != 2
176				|| input.shape()[1] != features
177				|| !input.runtime().same_as(self.weight.data().runtime())
178			{
179				return Err(Error::invalid_argument(format!(
180					"{operation} requires same-runtime [N, {features}] inputs; found {:?}",
181					input.shape()
182				)));
183			}
184		}
185		if input1.shape()[0] != input2.shape()[0] {
186			return Err(Error::invalid_argument(format!(
187				"{operation} batch extents must match; found {:?} and {:?}",
188				input1.shape(),
189				input2.shape()
190			)));
191		}
192		let batch = input1.shape()[0];
193		let outer = matrix::mul(
194			&input1.reshape([batch, self.in1_features, 1])?,
195			&input2.reshape([batch, 1, self.in2_features])?,
196		)?
197		.reshape([batch, self.in1_features * self.in2_features])?;
198		autograd::record_parameter_leaf(&self.weight)?;
199		let flat = self
200			.weight
201			.data()
202			.reshape([self.out_features, self.in1_features * self.in2_features])?;
203		let mut output = matrix::matmul(&outer, &flat)?;
204		if let Some(bias) = &self.bias {
205			autograd::record_parameter_leaf(bias)?;
206			output = matrix::add(&output, &bias.data())?;
207		}
208		Ok(output)
209	}
210}
211
212impl Module for Bilinear {
213	fn forward(&self, input: &Matrix) -> Result<Matrix> {
214		let _ = input;
215		Err(Error::invalid_argument(
216			"Bilinear requires two inputs; call forward2(input1, input2)",
217		))
218	}
219
220	fn registry(&self) -> &ModuleRegistry {
221		&self.registry
222	}
223}