Skip to main content

oa/ml/nn/
lstm.gen.rs

1// @generated by tool/gen/nn/generate.py; DO NOT EDIT.
2// Source: tool/gen/nn/schema/ml/ml_nn_lstm.json
3// generator_version=8; schema_sha256=46e3df4061086d8402e0497ce6e9df24b14e907a51b22e47af95d78e48ad876c
4
5use std::rc::Rc;
6
7use crate::{DType, Error, Matrix, Result, Runtime};
8
9use super::super::{Module, ModuleRegistry, Parameter, autograd, matrix, random};
10
11// OA donor: oacpp/source/cpp/lib/oa/ml/nn/lstm/lstm.cpp
12// Adaptation: No fused C++ donor kernel exists for LSTM. Rust composes each timestep from recorded linear and elementwise dispatches in input/forget/candidate/output gate order, retaining checked FP32 geometry, deterministic seeded host initialization, versioned parameter adjoints and optional unregistered zero biases; a fused scan kernel remains planned performance work
13enum LstmBias {
14	Parameter(Parameter),
15	Zero(Matrix),
16}
17
18impl LstmBias {
19	fn snapshot(&self) -> (Matrix, Option<(Parameter, u64)>, bool) {
20		match self {
21			Self::Parameter(parameter) => {
22				let (value, version, requires_grad) = parameter.snapshot();
23				(
24					value,
25					requires_grad.then(|| (parameter.clone(), version)),
26					requires_grad,
27				)
28			}
29			Self::Zero(value) => (value.clone(), None, false),
30		}
31	}
32}
33
34struct LstmLayer {
35	input_size: usize,
36	hidden_size: usize,
37	weight_ih: Parameter,
38	weight_hh: Parameter,
39	bias_ih: LstmBias,
40	bias_hh: LstmBias,
41	registry: ModuleRegistry,
42}
43
44impl LstmLayer {
45	fn new_with_seed(
46		runtime: &Runtime,
47		input_size: usize,
48		hidden_size: usize,
49		bias: bool,
50		seed: u64,
51	) -> Result<Self> {
52		let gate_size = hidden_size
53			.checked_mul(4)
54			.ok_or_else(|| Error::invalid_argument("LSTM gate size overflows usize"))?;
55		let weight_ih = xavier_matrix(runtime, gate_size, input_size, seed)?;
56		let weight_hh = xavier_matrix(
57			runtime,
58			gate_size,
59			hidden_size,
60			seed.wrapping_add(0x9e37_79b9_7f4a_7c15),
61		)?;
62		let bias_ih = bias
63			.then(|| Matrix::new_from_f32_on(runtime, [gate_size], &vec![0.0; gate_size]))
64			.transpose()?;
65		let bias_hh = bias
66			.then(|| Matrix::new_from_f32_on(runtime, [gate_size], &vec![0.0; gate_size]))
67			.transpose()?;
68		Self::from_values(weight_ih, weight_hh, bias_ih, bias_hh)
69	}
70
71	fn from_values(
72		weight_ih: Matrix,
73		weight_hh: Matrix,
74		bias_ih: Option<Matrix>,
75		bias_hh: Option<Matrix>,
76	) -> Result<Self> {
77		let [gate_size, input_size] = weight_ih.shape() else {
78			return Err(Error::invalid_argument(
79				"LSTM input weight must have shape [4H, I]",
80			));
81		};
82		if *gate_size == 0 || gate_size % 4 != 0 || *input_size == 0 {
83			return Err(Error::invalid_argument(
84				"LSTM input weight requires nonzero shape [4H, I]",
85			));
86		}
87		let hidden_size = gate_size / 4;
88		let same_bias_mode = bias_ih.is_some() == bias_hh.is_some();
89		let runtime = weight_ih.runtime().clone();
90		if hidden_size > 1024
91			|| weight_hh.shape() != [*gate_size, hidden_size]
92			|| weight_ih.dtype() != DType::F32
93			|| weight_hh.dtype() != DType::F32
94			|| !runtime.same_as(weight_hh.runtime())
95			|| !same_bias_mode
96			|| bias_ih.as_ref().is_some_and(|value| {
97				value.shape() != [*gate_size]
98					|| value.dtype() != DType::F32
99					|| !runtime.same_as(value.runtime())
100			}) || bias_hh.as_ref().is_some_and(|value| {
101			value.shape() != [*gate_size]
102				|| value.dtype() != DType::F32
103				|| !runtime.same_as(value.runtime())
104		}) {
105			return Err(Error::invalid_argument(
106				"LSTM requires same-runtime F32 weights [4H, I]/[4H, H], paired biases [4H], and 1 <= H <= 1024",
107			));
108		}
109		let input_size = *input_size;
110		let gate_size = *gate_size;
111		let weight_ih = Parameter::new("weight_ih", weight_ih)?;
112		let weight_hh = Parameter::new("weight_hh", weight_hh)?;
113		let bias_ih = match bias_ih {
114			Some(value) => LstmBias::Parameter(Parameter::new("bias_ih", value)?),
115			None => LstmBias::Zero(Matrix::allocate(
116				&runtime,
117				vec![gate_size],
118				gate_size,
119				DType::F32,
120			)?),
121		};
122		let bias_hh = match bias_hh {
123			Some(value) => LstmBias::Parameter(Parameter::new("bias_hh", value)?),
124			None => LstmBias::Zero(Matrix::allocate(
125				&runtime,
126				vec![gate_size],
127				gate_size,
128				DType::F32,
129			)?),
130		};
131		let mut registry = ModuleRegistry::new();
132		registry.register_parameter("weight_ih", weight_ih.clone())?;
133		registry.register_parameter("weight_hh", weight_hh.clone())?;
134		if let LstmBias::Parameter(parameter) = &bias_ih {
135			registry.register_parameter("bias_ih", parameter.clone())?;
136		}
137		if let LstmBias::Parameter(parameter) = &bias_hh {
138			registry.register_parameter("bias_hh", parameter.clone())?;
139		}
140		Ok(Self {
141			input_size,
142			hidden_size,
143			weight_ih,
144			weight_hh,
145			bias_ih,
146			bias_hh,
147			registry,
148		})
149	}
150
151	fn forward(&self, input: &Matrix) -> Result<Matrix> {
152		let [batch, sequence_length, input_size] = input.shape() else {
153			return Err(Error::invalid_argument(
154				"LSTM input must have shape [B, S, I]",
155			));
156		};
157		if *batch == 0 || *sequence_length == 0 || *input_size != self.input_size {
158			return Err(Error::invalid_argument(format!(
159				"LSTM requires nonempty input [B, S, {}]; found {:?}",
160				self.input_size,
161				input.shape()
162			)));
163		}
164		let rows = batch
165			.checked_mul(*sequence_length)
166			.ok_or_else(|| Error::invalid_argument("LSTM flattened row count overflows usize"))?;
167		let flat_input = input.reshape([rows, self.input_size])?;
168		let flat_gates = self.input_projection(&flat_input)?;
169		let gates = flat_gates.reshape([*batch, *sequence_length, 4 * self.hidden_size])?;
170		let (weight_hh, weight_hh_version, _) = self.weight_hh.snapshot();
171		let (bias_hh, bias_hh_parameter, _) = self.bias_hh.snapshot();
172		matrix::lstm_scan_parameterized(
173			&gates,
174			(self.weight_hh.clone(), weight_hh, weight_hh_version),
175			bias_hh_parameter,
176			&bias_hh,
177		)
178	}
179
180	fn input_projection(&self, input: &Matrix) -> Result<Matrix> {
181		let (weight_ih, weight_ih_version, weight_ih_requires_grad) = self.weight_ih.snapshot();
182		let (bias_ih, bias_ih_parameter, bias_ih_requires_grad) = self.bias_ih.snapshot();
183		let gates = matrix::linear(input, &weight_ih, &bias_ih)?;
184		if weight_ih_requires_grad || bias_ih_requires_grad {
185			autograd::record_linear(
186				input,
187				&gates,
188				self.weight_ih.clone(),
189				weight_ih,
190				weight_ih_version,
191				bias_ih_parameter,
192			)?;
193		}
194		Ok(gates)
195	}
196
197	fn step(&self, input: &Matrix, hidden: &Matrix, cell: &Matrix) -> Result<(Matrix, Matrix)> {
198		let [batch, input_size] = input.shape() else {
199			return Err(Error::invalid_argument(
200				"LSTM cell input must have shape [B, I]",
201			));
202		};
203		if *batch == 0
204			|| *input_size != self.input_size
205			|| hidden.shape() != [*batch, self.hidden_size]
206			|| cell.shape() != [*batch, self.hidden_size]
207		{
208			return Err(Error::invalid_argument(format!(
209				"LSTM cell requires input [B, {}], hidden [B, {}], and cell [B, {}]; found {:?}, {:?}, {:?}",
210				self.input_size,
211				self.hidden_size,
212				self.hidden_size,
213				input.shape(),
214				hidden.shape(),
215				cell.shape()
216			)));
217		}
218		let gates = self.input_projection(input)?;
219		let (weight_hh, weight_hh_version, _) = self.weight_hh.snapshot();
220		let (bias_hh, bias_hh_parameter, _) = self.bias_hh.snapshot();
221		matrix::lstm_cell_parameterized(
222			&gates,
223			hidden,
224			cell,
225			(self.weight_hh.clone(), weight_hh, weight_hh_version),
226			bias_hh_parameter,
227			&bias_hh,
228		)
229	}
230
231	fn parameters(&self) -> Vec<Parameter> {
232		let mut parameters = vec![self.weight_ih.clone(), self.weight_hh.clone()];
233		if let LstmBias::Parameter(parameter) = &self.bias_ih {
234			parameters.push(parameter.clone());
235		}
236		if let LstmBias::Parameter(parameter) = &self.bias_hh {
237			parameters.push(parameter.clone());
238		}
239		parameters
240	}
241
242	fn has_bias(&self) -> bool {
243		matches!(self.bias_ih, LstmBias::Parameter(_))
244	}
245}
246
247impl Module for LstmLayer {
248	fn forward(&self, input: &Matrix) -> Result<Matrix> {
249		LstmLayer::forward(self, input)
250	}
251
252	fn registry(&self) -> &ModuleRegistry {
253		&self.registry
254	}
255}
256
257/// One long short-term memory cell cell with an explicit caller-owned hidden state.
258pub struct LstmCell {
259	layer: LstmLayer,
260}
261
262impl LstmCell {
263	#[allow(clippy::too_many_arguments)]
264	pub fn new_with_seed(
265		input_size: usize,
266		hidden_size: usize,
267		bias: bool,
268		seed: u64,
269	) -> Result<Self> {
270		Self::new_with_seed_on(&Runtime::current()?, input_size, hidden_size, bias, seed)
271	}
272
273	/// Construct a deterministically initialized LSTM cell.
274	///
275	/// # Errors
276	///
277	/// Returns an error when dimensions are zero, hidden size exceeds 1024,
278	/// arithmetic overflows, or parameter allocation fails.
279	pub fn new_with_seed_on(
280		runtime: &Runtime,
281		input_size: usize,
282		hidden_size: usize,
283		bias: bool,
284		seed: u64,
285	) -> Result<Self> {
286		if input_size == 0 || hidden_size == 0 || hidden_size > 1024 {
287			return Err(Error::invalid_argument(
288				"LSTM cell requires nonzero input/hidden sizes and hidden size <= 1024",
289			));
290		}
291		Ok(Self {
292			layer: LstmLayer::new_with_seed(runtime, input_size, hidden_size, bias, seed)?,
293		})
294	}
295
296	/// Construct a biased LSTM cell from exact matrices.
297	///
298	/// # Errors
299	///
300	/// Returns an error unless weights use `[4H, I]` and `[4H, H]`, biases use
301	/// `[4H]`, and all values satisfy the F32 runtime and hidden-size contract.
302	pub fn new_from_matrices(
303		weight_ih: Matrix,
304		weight_hh: Matrix,
305		bias_ih: Matrix,
306		bias_hh: Matrix,
307	) -> Result<Self> {
308		Ok(Self {
309			layer: LstmLayer::from_values(weight_ih, weight_hh, Some(bias_ih), Some(bias_hh))?,
310		})
311	}
312
313	/// Construct a bias-free LSTM cell from exact weight matrices.
314	///
315	/// # Errors
316	///
317	/// Returns an error unless both weights satisfy the F32 runtime, shape, and
318	/// hidden-size contract.
319	pub fn new_from_weights(weight_ih: Matrix, weight_hh: Matrix) -> Result<Self> {
320		Ok(Self {
321			layer: LstmLayer::from_values(weight_ih, weight_hh, None, None)?,
322		})
323	}
324
325	/// Create zero `(hidden, cell)` states `[batch, hidden]` on this cell's runtime.
326	///
327	/// # Errors
328	///
329	/// Returns an error when batch is zero, shape arithmetic overflows, or
330	/// allocation fails.
331	pub fn zero_state(&self, batch: usize) -> Result<(Matrix, Matrix)> {
332		if batch == 0 {
333			return Err(Error::invalid_argument("LSTM cell batch must be nonzero"));
334		}
335		let count = batch
336			.checked_mul(self.layer.hidden_size)
337			.ok_or_else(|| Error::invalid_argument("LSTM cell state size overflows usize"))?;
338		let (weight, _, _) = self.layer.weight_hh.snapshot();
339		let hidden = Matrix::allocate(
340			weight.runtime(),
341			vec![batch, self.layer.hidden_size],
342			count,
343			DType::F32,
344		)?;
345		let cell = Matrix::allocate(
346			weight.runtime(),
347			vec![batch, self.layer.hidden_size],
348			count,
349			DType::F32,
350		)?;
351		Ok((hidden, cell))
352	}
353
354	/// Apply one recurrent step to `[B, I]` input with `[B, H]` hidden and
355	/// `[B, H]` cell states. Returns `(hidden_next, cell_next)`.
356	///
357	/// # Errors
358	///
359	/// Returns an error when the input/state contract or runtime recording fails.
360	pub fn step(&self, input: &Matrix, hidden: &Matrix, cell: &Matrix) -> Result<(Matrix, Matrix)> {
361		self.layer.step(input, hidden, cell)
362	}
363
364	/// Return the configured input width.
365	pub const fn input_size(&self) -> usize {
366		self.layer.input_size
367	}
368
369	/// Return the recurrent hidden width.
370	pub const fn hidden_size(&self) -> usize {
371		self.layer.hidden_size
372	}
373
374	/// Return whether the two biases are trainable parameters.
375	pub fn has_bias(&self) -> bool {
376		self.layer.has_bias()
377	}
378
379	/// Return parameters in weight-ih, weight-hh, bias-ih, bias-hh order.
380	pub fn all_parameters(&self) -> Result<Vec<Parameter>> {
381		Module::all_parameters(self)
382	}
383}
384
385impl Module for LstmCell {
386	fn forward(&self, input: &Matrix) -> Result<Matrix> {
387		let [batch, _] = input.shape() else {
388			return Err(Error::invalid_argument(
389				"LSTM cell input must have shape [B, I]",
390			));
391		};
392		let (hidden, cell) = self.zero_state(*batch)?;
393		let (hidden_next, _) = self.step(input, &hidden, &cell)?;
394		Ok(hidden_next)
395	}
396
397	fn registry(&self) -> &ModuleRegistry {
398		&self.layer.registry
399	}
400}
401
402/// Stacked batch-first long short-term memory using whole-sequence composed scans.
403///
404/// Input uses `[batch, sequence, input]`; output uses
405/// `[batch, sequence, hidden]`. Every layer starts from a zero hidden state.
406pub struct Lstm {
407	input_size: usize,
408	hidden_size: usize,
409	layers: Vec<Rc<LstmLayer>>,
410	registry: ModuleRegistry,
411}
412
413impl Lstm {
414	#[allow(clippy::too_many_arguments)]
415	pub fn new_with_seed(
416		input_size: usize,
417		hidden_size: usize,
418		num_layers: usize,
419		bias: bool,
420		seed: u64,
421	) -> Result<Self> {
422		Self::new_with_seed_on(
423			&Runtime::current()?,
424			input_size,
425			hidden_size,
426			num_layers,
427			bias,
428			seed,
429		)
430	}
431
432	/// Construct a deterministically initialized stacked LSTM.
433	///
434	/// # Errors
435	///
436	/// Returns an error when a dimension or layer count is zero, hidden size
437	/// exceeds the 1024-element scan limit, arithmetic overflows, or parameter
438	/// allocation and registration fail.
439	pub fn new_with_seed_on(
440		runtime: &Runtime,
441		input_size: usize,
442		hidden_size: usize,
443		num_layers: usize,
444		bias: bool,
445		seed: u64,
446	) -> Result<Self> {
447		if input_size == 0 || hidden_size == 0 || hidden_size > 1024 || num_layers == 0 {
448			return Err(Error::invalid_argument(
449				"LSTM requires nonzero input/hidden/layer counts and hidden size <= 1024",
450			));
451		}
452		let mut layers = Vec::with_capacity(num_layers);
453		let mut registry = ModuleRegistry::new();
454		for index in 0..num_layers {
455			let layer_input = if index == 0 { input_size } else { hidden_size };
456			let layer = Rc::new(LstmLayer::new_with_seed(
457				runtime,
458				layer_input,
459				hidden_size,
460				bias,
461				seed.wrapping_add((index as u64).wrapping_mul(0xd1b5_4a32_d192_ed03)),
462			)?);
463			registry.register_module(format!("layer{index}"), layer.clone())?;
464			layers.push(layer);
465		}
466		Ok(Self {
467			input_size,
468			hidden_size,
469			layers,
470			registry,
471		})
472	}
473
474	/// Construct a one-layer biased LSTM from exact parameter matrices.
475	///
476	/// # Errors
477	///
478	/// Returns an error unless weights use `[4H, I]` and `[4H, H]`, biases use
479	/// `[4H]`, and all values are nonempty same-runtime F32 matrices with
480	/// `H <= 1024`.
481	pub fn new_from_matrices(
482		weight_ih: Matrix,
483		weight_hh: Matrix,
484		bias_ih: Matrix,
485		bias_hh: Matrix,
486	) -> Result<Self> {
487		Self::from_one_layer(weight_ih, weight_hh, Some(bias_ih), Some(bias_hh))
488	}
489
490	/// Construct a one-layer bias-free LSTM from exact weight matrices.
491	///
492	/// # Errors
493	///
494	/// Returns an error unless weights use `[4H, I]` and `[4H, H]` and are
495	/// nonempty same-runtime F32 matrices with `H <= 1024`.
496	pub fn new_from_weights(weight_ih: Matrix, weight_hh: Matrix) -> Result<Self> {
497		Self::from_one_layer(weight_ih, weight_hh, None, None)
498	}
499
500	fn from_one_layer(
501		weight_ih: Matrix,
502		weight_hh: Matrix,
503		bias_ih: Option<Matrix>,
504		bias_hh: Option<Matrix>,
505	) -> Result<Self> {
506		let [gate_size, input_size] = weight_ih.shape() else {
507			return Err(Error::invalid_argument(
508				"LSTM input weight must have shape [4H, I]",
509			));
510		};
511		if gate_size % 4 != 0 {
512			return Err(Error::invalid_argument(
513				"LSTM input weight first extent must be divisible by four",
514			));
515		}
516		let input_size = *input_size;
517		let hidden_size = gate_size / 4;
518		let layer = Rc::new(LstmLayer::from_values(
519			weight_ih, weight_hh, bias_ih, bias_hh,
520		)?);
521		let mut registry = ModuleRegistry::new();
522		registry.register_module("layer0", layer.clone())?;
523		Ok(Self {
524			input_size,
525			hidden_size,
526			layers: vec![layer],
527			registry,
528		})
529	}
530
531	/// Evaluate the complete sequence with one input projection and one recurrent
532	/// scan dispatch per layer.
533	///
534	/// # Errors
535	///
536	/// Returns an error unless input is same-runtime F32 `[B, S, I]` with nonzero
537	/// extents and the configured input width, or when recording fails.
538	pub fn forward(&self, input: &Matrix) -> Result<Matrix> {
539		let [_, _, input_size] = input.shape() else {
540			return Err(Error::invalid_argument(
541				"LSTM input must have shape [B, S, I]",
542			));
543		};
544		if *input_size != self.input_size {
545			return Err(Error::invalid_argument(format!(
546				"LSTM expected input width {}; found {input_size}",
547				self.input_size
548			)));
549		}
550		let mut output = input.clone();
551		for layer in &self.layers {
552			output = layer.forward(&output)?;
553		}
554		Ok(output)
555	}
556
557	/// Return the configured input width.
558	pub const fn input_size(&self) -> usize {
559		self.input_size
560	}
561
562	/// Return the recurrent hidden width.
563	pub const fn hidden_size(&self) -> usize {
564		self.hidden_size
565	}
566
567	/// Return the number of stacked recurrent layers.
568	pub fn num_layers(&self) -> usize {
569		self.layers.len()
570	}
571
572	/// Return whether layer biases are trainable parameters.
573	pub fn has_bias(&self) -> bool {
574		self.layers.first().is_some_and(|layer| layer.has_bias())
575	}
576
577	/// Return every parameter through the registered layer tree.
578	pub fn all_parameters(&self) -> Result<Vec<Parameter>> {
579		Module::all_parameters(self)
580	}
581
582	/// Return one layer's parameters in weight-ih, weight-hh, bias-ih, bias-hh
583	/// order. Bias-free layers return only the two weights.
584	pub fn layer_parameters(&self, layer: usize) -> Option<Vec<Parameter>> {
585		self.layers.get(layer).map(|layer| layer.parameters())
586	}
587}
588
589impl Module for Lstm {
590	fn forward(&self, input: &Matrix) -> Result<Matrix> {
591		Lstm::forward(self, input)
592	}
593
594	fn registry(&self) -> &ModuleRegistry {
595		&self.registry
596	}
597}
598
599fn xavier_matrix(
600	runtime: &Runtime,
601	output_features: usize,
602	input_features: usize,
603	seed: u64,
604) -> Result<Matrix> {
605	let count = output_features
606		.checked_mul(input_features)
607		.ok_or_else(|| Error::invalid_argument("LSTM weight size overflows usize"))?;
608	let denominator = output_features
609		.checked_add(input_features)
610		.ok_or_else(|| Error::invalid_argument("LSTM Xavier extent overflows usize"))?;
611	let limit = (6.0_f32 / denominator as f32).sqrt();
612	Matrix::new_from_f32_on(
613		runtime,
614		[output_features, input_features],
615		&random::symmetric_uniform(count, limit, seed),
616	)
617}