1use std::rc::Rc;
6
7use crate::{DType, Error, Matrix, Result, Runtime};
8
9use super::super::{Module, ModuleRegistry, Parameter, autograd, matrix, random};
10
11enum 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
257pub 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 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 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 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 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 pub fn step(&self, input: &Matrix, hidden: &Matrix, cell: &Matrix) -> Result<(Matrix, Matrix)> {
361 self.layer.step(input, hidden, cell)
362 }
363
364 pub const fn input_size(&self) -> usize {
366 self.layer.input_size
367 }
368
369 pub const fn hidden_size(&self) -> usize {
371 self.layer.hidden_size
372 }
373
374 pub fn has_bias(&self) -> bool {
376 self.layer.has_bias()
377 }
378
379 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
402pub 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 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 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 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 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 pub const fn input_size(&self) -> usize {
559 self.input_size
560 }
561
562 pub const fn hidden_size(&self) -> usize {
564 self.hidden_size
565 }
566
567 pub fn num_layers(&self) -> usize {
569 self.layers.len()
570 }
571
572 pub fn has_bias(&self) -> bool {
574 self.layers.first().is_some_and(|layer| layer.has_bias())
575 }
576
577 pub fn all_parameters(&self) -> Result<Vec<Parameter>> {
579 Module::all_parameters(self)
580 }
581
582 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}