1use std::rc::Rc;
6
7use crate::{DType, Error, Matrix, Result, Runtime};
8
9use super::super::{Module, ModuleRegistry, Parameter, autograd, matrix, random};
10
11enum RnnBias {
14 Parameter(Parameter),
15 Zero(Matrix),
16}
17
18impl RnnBias {
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 RnnLayer {
35 input_size: usize,
36 hidden_size: usize,
37 weight_ih: Parameter,
38 weight_hh: Parameter,
39 bias_ih: RnnBias,
40 bias_hh: RnnBias,
41 registry: ModuleRegistry,
42}
43
44impl RnnLayer {
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 weight_ih_count = hidden_size
53 .checked_mul(input_size)
54 .ok_or_else(|| Error::invalid_argument("RNN input weight size overflows usize"))?;
55 let weight_hh_count = hidden_size
56 .checked_mul(hidden_size)
57 .ok_or_else(|| Error::invalid_argument("RNN recurrent weight size overflows usize"))?;
58 let xavier_extent = input_size
59 .checked_add(hidden_size)
60 .ok_or_else(|| Error::invalid_argument("RNN Xavier extent overflows usize"))?;
61 let input_limit = (6.0_f32 / xavier_extent as f32).sqrt();
62 let hidden_limit = (3.0_f32 / hidden_size as f32).sqrt();
63 let weight_ih = Matrix::new_from_f32_on(
64 runtime,
65 [hidden_size, input_size],
66 &random::symmetric_uniform(weight_ih_count, input_limit, seed),
67 )?;
68 let weight_hh = Matrix::new_from_f32_on(
69 runtime,
70 [hidden_size, hidden_size],
71 &random::symmetric_uniform(
72 weight_hh_count,
73 hidden_limit,
74 seed.wrapping_add(0x9e37_79b9_7f4a_7c15),
75 ),
76 )?;
77 let bias_ih = bias
78 .then(|| Matrix::new_from_f32_on(runtime, [hidden_size], &vec![0.0; hidden_size]))
79 .transpose()?;
80 let bias_hh = bias
81 .then(|| Matrix::new_from_f32_on(runtime, [hidden_size], &vec![0.0; hidden_size]))
82 .transpose()?;
83 Self::from_values(weight_ih, weight_hh, bias_ih, bias_hh)
84 }
85
86 fn from_values(
87 weight_ih: Matrix,
88 weight_hh: Matrix,
89 bias_ih: Option<Matrix>,
90 bias_hh: Option<Matrix>,
91 ) -> Result<Self> {
92 let [hidden_size, input_size] = weight_ih.shape() else {
93 return Err(Error::invalid_argument(
94 "RNN input weight must have shape [H, I]",
95 ));
96 };
97 let same_bias_mode = bias_ih.is_some() == bias_hh.is_some();
98 let runtime = weight_ih.runtime().clone();
99 if *hidden_size == 0
100 || *input_size == 0
101 || *hidden_size > 1024
102 || weight_hh.shape() != [*hidden_size, *hidden_size]
103 || weight_ih.dtype() != DType::F32
104 || weight_hh.dtype() != DType::F32
105 || !runtime.same_as(weight_hh.runtime())
106 || !same_bias_mode
107 || bias_ih.as_ref().is_some_and(|value| {
108 value.shape() != [*hidden_size]
109 || value.dtype() != DType::F32
110 || !runtime.same_as(value.runtime())
111 }) || bias_hh.as_ref().is_some_and(|value| {
112 value.shape() != [*hidden_size]
113 || value.dtype() != DType::F32
114 || !runtime.same_as(value.runtime())
115 }) {
116 return Err(Error::invalid_argument(
117 "RNN requires same-runtime F32 weights [H, I]/[H, H], paired biases [H], and 1 <= H <= 1024",
118 ));
119 }
120 let input_size = *input_size;
121 let hidden_size = *hidden_size;
122 let weight_ih = Parameter::new("weight_ih", weight_ih)?;
123 let weight_hh = Parameter::new("weight_hh", weight_hh)?;
124 let bias_ih = match bias_ih {
125 Some(value) => RnnBias::Parameter(Parameter::new("bias_ih", value)?),
126 None => RnnBias::Zero(Matrix::allocate(
127 &runtime,
128 vec![hidden_size],
129 hidden_size,
130 DType::F32,
131 )?),
132 };
133 let bias_hh = match bias_hh {
134 Some(value) => RnnBias::Parameter(Parameter::new("bias_hh", value)?),
135 None => RnnBias::Zero(Matrix::allocate(
136 &runtime,
137 vec![hidden_size],
138 hidden_size,
139 DType::F32,
140 )?),
141 };
142 let mut registry = ModuleRegistry::new();
143 registry.register_parameter("weight_ih", weight_ih.clone())?;
144 registry.register_parameter("weight_hh", weight_hh.clone())?;
145 if let RnnBias::Parameter(parameter) = &bias_ih {
146 registry.register_parameter("bias_ih", parameter.clone())?;
147 }
148 if let RnnBias::Parameter(parameter) = &bias_hh {
149 registry.register_parameter("bias_hh", parameter.clone())?;
150 }
151 Ok(Self {
152 input_size,
153 hidden_size,
154 weight_ih,
155 weight_hh,
156 bias_ih,
157 bias_hh,
158 registry,
159 })
160 }
161
162 fn forward(&self, input: &Matrix) -> Result<Matrix> {
163 let [batch, sequence_length, input_size] = input.shape() else {
164 return Err(Error::invalid_argument(
165 "RNN input must have shape [B, S, I]",
166 ));
167 };
168 if *batch == 0 || *sequence_length == 0 || *input_size != self.input_size {
169 return Err(Error::invalid_argument(format!(
170 "RNN requires nonempty input [B, S, {}]; found {:?}",
171 self.input_size,
172 input.shape()
173 )));
174 }
175 let rows = batch
176 .checked_mul(*sequence_length)
177 .ok_or_else(|| Error::invalid_argument("RNN flattened row count overflows usize"))?;
178 let flat_input = input.reshape([rows, self.input_size])?;
179 let flat_gates = self.input_projection(&flat_input)?;
180 let gates = flat_gates.reshape([*batch, *sequence_length, self.hidden_size])?;
181 let (weight_hh, weight_hh_version, _) = self.weight_hh.snapshot();
182 let (bias_hh, bias_hh_parameter, _) = self.bias_hh.snapshot();
183 matrix::rnn_scan_parameterized(
184 &gates,
185 (self.weight_hh.clone(), weight_hh, weight_hh_version),
186 bias_hh_parameter,
187 &bias_hh,
188 self.has_bias(),
189 )
190 }
191
192 fn input_projection(&self, input: &Matrix) -> Result<Matrix> {
193 let (weight_ih, weight_ih_version, weight_ih_requires_grad) = self.weight_ih.snapshot();
194 let (bias_ih, bias_ih_parameter, bias_ih_requires_grad) = self.bias_ih.snapshot();
195 let gates = matrix::linear(input, &weight_ih, &bias_ih)?;
196 if weight_ih_requires_grad || bias_ih_requires_grad {
197 autograd::record_linear(
198 input,
199 &gates,
200 self.weight_ih.clone(),
201 weight_ih,
202 weight_ih_version,
203 bias_ih_parameter,
204 )?;
205 }
206 Ok(gates)
207 }
208
209 fn step(&self, input: &Matrix, hidden: &Matrix) -> Result<Matrix> {
210 let [batch, input_size] = input.shape() else {
211 return Err(Error::invalid_argument(
212 "RNN cell input must have shape [B, I]",
213 ));
214 };
215 if *batch == 0 || *input_size != self.input_size || hidden.shape() != [*batch, self.hidden_size]
216 {
217 return Err(Error::invalid_argument(format!(
218 "RNN cell requires input [B, {}] and hidden [B, {}]; found {:?} and {:?}",
219 self.input_size,
220 self.hidden_size,
221 input.shape(),
222 hidden.shape()
223 )));
224 }
225 let gates = self.input_projection(input)?;
226 let (weight_hh, weight_hh_version, _) = self.weight_hh.snapshot();
227 let (bias_hh, bias_hh_parameter, _) = self.bias_hh.snapshot();
228 matrix::rnn_cell_parameterized(
229 &gates,
230 hidden,
231 (self.weight_hh.clone(), weight_hh, weight_hh_version),
232 bias_hh_parameter,
233 &bias_hh,
234 self.has_bias(),
235 )
236 }
237
238 fn parameters(&self) -> Vec<Parameter> {
239 let mut parameters = vec![self.weight_ih.clone(), self.weight_hh.clone()];
240 if let RnnBias::Parameter(parameter) = &self.bias_ih {
241 parameters.push(parameter.clone());
242 }
243 if let RnnBias::Parameter(parameter) = &self.bias_hh {
244 parameters.push(parameter.clone());
245 }
246 parameters
247 }
248
249 fn has_bias(&self) -> bool {
250 matches!(self.bias_ih, RnnBias::Parameter(_))
251 }
252}
253
254impl Module for RnnLayer {
255 fn forward(&self, input: &Matrix) -> Result<Matrix> {
256 RnnLayer::forward(self, input)
257 }
258
259 fn registry(&self) -> &ModuleRegistry {
260 &self.registry
261 }
262}
263
264pub struct RnnCell {
266 layer: RnnLayer,
267}
268
269impl RnnCell {
270 #[allow(clippy::too_many_arguments)]
271 pub fn new_with_seed(
272 input_size: usize,
273 hidden_size: usize,
274 bias: bool,
275 seed: u64,
276 ) -> Result<Self> {
277 Self::new_with_seed_on(&Runtime::current()?, input_size, hidden_size, bias, seed)
278 }
279
280 pub fn new_with_seed_on(
287 runtime: &Runtime,
288 input_size: usize,
289 hidden_size: usize,
290 bias: bool,
291 seed: u64,
292 ) -> Result<Self> {
293 if input_size == 0 || hidden_size == 0 || hidden_size > 1024 {
294 return Err(Error::invalid_argument(
295 "RNN cell requires nonzero input/hidden sizes and hidden size <= 1024",
296 ));
297 }
298 Ok(Self {
299 layer: RnnLayer::new_with_seed(runtime, input_size, hidden_size, bias, seed)?,
300 })
301 }
302
303 pub fn new_from_matrices(
310 weight_ih: Matrix,
311 weight_hh: Matrix,
312 bias_ih: Matrix,
313 bias_hh: Matrix,
314 ) -> Result<Self> {
315 Ok(Self {
316 layer: RnnLayer::from_values(weight_ih, weight_hh, Some(bias_ih), Some(bias_hh))?,
317 })
318 }
319
320 pub fn new_from_weights(weight_ih: Matrix, weight_hh: Matrix) -> Result<Self> {
327 Ok(Self {
328 layer: RnnLayer::from_values(weight_ih, weight_hh, None, None)?,
329 })
330 }
331
332 pub fn zero_state(&self, batch: usize) -> Result<Matrix> {
339 if batch == 0 {
340 return Err(Error::invalid_argument("RNN cell batch must be nonzero"));
341 }
342 let count = batch
343 .checked_mul(self.layer.hidden_size)
344 .ok_or_else(|| Error::invalid_argument("RNN cell state size overflows usize"))?;
345 let (weight, _, _) = self.layer.weight_hh.snapshot();
346 Matrix::allocate(
347 weight.runtime(),
348 vec![batch, self.layer.hidden_size],
349 count,
350 DType::F32,
351 )
352 }
353
354 pub fn step(&self, input: &Matrix, hidden: &Matrix) -> Result<Matrix> {
360 self.layer.step(input, hidden)
361 }
362
363 pub const fn input_size(&self) -> usize {
365 self.layer.input_size
366 }
367
368 pub const fn hidden_size(&self) -> usize {
370 self.layer.hidden_size
371 }
372
373 pub fn has_bias(&self) -> bool {
375 self.layer.has_bias()
376 }
377
378 pub fn all_parameters(&self) -> Result<Vec<Parameter>> {
380 Module::all_parameters(self)
381 }
382}
383
384impl Module for RnnCell {
385 fn forward(&self, input: &Matrix) -> Result<Matrix> {
386 let [batch, _] = input.shape() else {
387 return Err(Error::invalid_argument(
388 "RNN cell input must have shape [B, I]",
389 ));
390 };
391 self.step(input, &self.zero_state(*batch)?)
392 }
393
394 fn registry(&self) -> &ModuleRegistry {
395 &self.layer.registry
396 }
397}
398
399pub struct Rnn {
404 input_size: usize,
405 hidden_size: usize,
406 layers: Vec<Rc<RnnLayer>>,
407 registry: ModuleRegistry,
408}
409
410impl Rnn {
411 #[allow(clippy::too_many_arguments)]
412 pub fn new_with_seed(
413 input_size: usize,
414 hidden_size: usize,
415 num_layers: usize,
416 seed: u64,
417 ) -> Result<Self> {
418 Self::new_with_seed_on(
419 &Runtime::current()?,
420 input_size,
421 hidden_size,
422 num_layers,
423 seed,
424 )
425 }
426
427 pub fn new_with_seed_on(
435 runtime: &Runtime,
436 input_size: usize,
437 hidden_size: usize,
438 num_layers: usize,
439 seed: u64,
440 ) -> Result<Self> {
441 Self::new_with_seed_and_bias_on(runtime, input_size, hidden_size, num_layers, true, seed)
442 }
443
444 #[allow(clippy::too_many_arguments)]
445 pub fn new_with_seed_and_bias(
446 input_size: usize,
447 hidden_size: usize,
448 num_layers: usize,
449 bias: bool,
450 seed: u64,
451 ) -> Result<Self> {
452 Self::new_with_seed_and_bias_on(
453 &Runtime::current()?,
454 input_size,
455 hidden_size,
456 num_layers,
457 bias,
458 seed,
459 )
460 }
461
462 pub fn new_with_seed_and_bias_on(
470 runtime: &Runtime,
471 input_size: usize,
472 hidden_size: usize,
473 num_layers: usize,
474 bias: bool,
475 seed: u64,
476 ) -> Result<Self> {
477 if input_size == 0 || hidden_size == 0 || hidden_size > 1024 || num_layers == 0 {
478 return Err(Error::invalid_argument(
479 "RNN requires nonzero input/hidden/layer counts and hidden size <= 1024",
480 ));
481 }
482 let mut layers = Vec::with_capacity(num_layers);
483 let mut registry = ModuleRegistry::new();
484 for index in 0..num_layers {
485 let layer_input = if index == 0 { input_size } else { hidden_size };
486 let layer = Rc::new(RnnLayer::new_with_seed(
487 runtime,
488 layer_input,
489 hidden_size,
490 bias,
491 seed.wrapping_add((index as u64).wrapping_mul(0xd1b5_4a32_d192_ed03)),
492 )?);
493 registry.register_module(format!("layer{index}"), layer.clone())?;
494 layers.push(layer);
495 }
496 Ok(Self {
497 input_size,
498 hidden_size,
499 layers,
500 registry,
501 })
502 }
503
504 pub fn new_from_matrices(
511 weight_ih: Matrix,
512 weight_hh: Matrix,
513 bias_ih: Matrix,
514 bias_hh: Matrix,
515 ) -> Result<Self> {
516 Self::from_one_layer(weight_ih, weight_hh, Some(bias_ih), Some(bias_hh))
517 }
518
519 pub fn new_from_weights(weight_ih: Matrix, weight_hh: Matrix) -> Result<Self> {
526 Self::from_one_layer(weight_ih, weight_hh, None, None)
527 }
528
529 fn from_one_layer(
530 weight_ih: Matrix,
531 weight_hh: Matrix,
532 bias_ih: Option<Matrix>,
533 bias_hh: Option<Matrix>,
534 ) -> Result<Self> {
535 let [hidden_size, input_size] = weight_ih.shape() else {
536 return Err(Error::invalid_argument(
537 "RNN input weight must have shape [H, I]",
538 ));
539 };
540 let input_size = *input_size;
541 let hidden_size = *hidden_size;
542 let layer = Rc::new(RnnLayer::from_values(
543 weight_ih, weight_hh, bias_ih, bias_hh,
544 )?);
545 let mut registry = ModuleRegistry::new();
546 registry.register_module("layer0", layer.clone())?;
547 Ok(Self {
548 input_size,
549 hidden_size,
550 layers: vec![layer],
551 registry,
552 })
553 }
554
555 pub fn forward(&self, input: &Matrix) -> Result<Matrix> {
563 let [_, _, input_size] = input.shape() else {
564 return Err(Error::invalid_argument(
565 "RNN input must have shape [B, S, I]",
566 ));
567 };
568 if *input_size != self.input_size {
569 return Err(Error::invalid_argument(format!(
570 "RNN expected input width {}; found {input_size}",
571 self.input_size
572 )));
573 }
574 let mut output = input.clone();
575 for layer in &self.layers {
576 output = layer.forward(&output)?;
577 }
578 Ok(output)
579 }
580
581 pub const fn input_size(&self) -> usize {
583 self.input_size
584 }
585
586 pub const fn hidden_size(&self) -> usize {
588 self.hidden_size
589 }
590
591 pub fn num_layers(&self) -> usize {
593 self.layers.len()
594 }
595
596 pub fn has_bias(&self) -> bool {
598 self.layers.first().is_some_and(|layer| layer.has_bias())
599 }
600
601 pub fn all_parameters(&self) -> Result<Vec<Parameter>> {
603 Module::all_parameters(self)
604 }
605
606 pub fn layer_parameters(&self, layer: usize) -> Option<Vec<Parameter>> {
609 self.layers.get(layer).map(|layer| layer.parameters())
610 }
611}
612
613impl Module for Rnn {
614 fn forward(&self, input: &Matrix) -> Result<Matrix> {
615 Rnn::forward(self, input)
616 }
617
618 fn registry(&self) -> &ModuleRegistry {
619 &self.registry
620 }
621}