1use std::rc::Rc;
6
7use crate::{DType, Error, Matrix, Result, Runtime};
8
9use super::super::{Module, ModuleRegistry, Parameter, autograd, matrix, random};
10
11enum GruBias {
14 Parameter(Parameter),
15 Zero(Matrix),
16}
17
18impl GruBias {
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 GruLayer {
35 input_size: usize,
36 hidden_size: usize,
37 weight_ih: Parameter,
38 weight_hh: Parameter,
39 bias_ih: GruBias,
40 bias_hh: GruBias,
41 registry: ModuleRegistry,
42}
43
44impl GruLayer {
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(3)
54 .ok_or_else(|| Error::invalid_argument("GRU 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 "GRU input weight must have shape [3H, I]",
80 ));
81 };
82 if *gate_size == 0 || gate_size % 3 != 0 || *input_size == 0 {
83 return Err(Error::invalid_argument(
84 "GRU input weight requires nonzero shape [3H, I]",
85 ));
86 }
87 let hidden_size = gate_size / 3;
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 "GRU requires same-runtime F32 weights [3H, I]/[3H, H], paired biases [3H], 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) => GruBias::Parameter(Parameter::new("bias_ih", value)?),
115 None => GruBias::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) => GruBias::Parameter(Parameter::new("bias_hh", value)?),
124 None => GruBias::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 GruBias::Parameter(parameter) = &bias_ih {
135 registry.register_parameter("bias_ih", parameter.clone())?;
136 }
137 if let GruBias::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 "GRU 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 "GRU 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("GRU 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, 3 * 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::gru_scan_parameterized(
173 &gates,
174 (self.weight_hh.clone(), weight_hh, weight_hh_version),
175 bias_hh_parameter,
176 &bias_hh,
177 self.has_bias(),
178 )
179 }
180
181 fn input_projection(&self, input: &Matrix) -> Result<Matrix> {
182 let (weight_ih, weight_ih_version, weight_ih_requires_grad) = self.weight_ih.snapshot();
183 let (bias_ih, bias_ih_parameter, bias_ih_requires_grad) = self.bias_ih.snapshot();
184 let gates = matrix::linear(input, &weight_ih, &bias_ih)?;
185 if weight_ih_requires_grad || bias_ih_requires_grad {
186 autograd::record_linear(
187 input,
188 &gates,
189 self.weight_ih.clone(),
190 weight_ih,
191 weight_ih_version,
192 bias_ih_parameter,
193 )?;
194 }
195 Ok(gates)
196 }
197
198 fn step(&self, input: &Matrix, hidden: &Matrix) -> Result<Matrix> {
199 let [batch, input_size] = input.shape() else {
200 return Err(Error::invalid_argument(
201 "GRU cell input must have shape [B, I]",
202 ));
203 };
204 if *batch == 0 || *input_size != self.input_size || hidden.shape() != [*batch, self.hidden_size]
205 {
206 return Err(Error::invalid_argument(format!(
207 "GRU cell requires input [B, {}] and hidden [B, {}]; found {:?} and {:?}",
208 self.input_size,
209 self.hidden_size,
210 input.shape(),
211 hidden.shape()
212 )));
213 }
214 let gates = self.input_projection(input)?;
215 let (weight_hh, weight_hh_version, _) = self.weight_hh.snapshot();
216 let (bias_hh, bias_hh_parameter, _) = self.bias_hh.snapshot();
217 matrix::gru_cell_parameterized(
218 &gates,
219 hidden,
220 (self.weight_hh.clone(), weight_hh, weight_hh_version),
221 bias_hh_parameter,
222 &bias_hh,
223 self.has_bias(),
224 )
225 }
226
227 fn parameters(&self) -> Vec<Parameter> {
228 let mut parameters = vec![self.weight_ih.clone(), self.weight_hh.clone()];
229 if let GruBias::Parameter(parameter) = &self.bias_ih {
230 parameters.push(parameter.clone());
231 }
232 if let GruBias::Parameter(parameter) = &self.bias_hh {
233 parameters.push(parameter.clone());
234 }
235 parameters
236 }
237
238 fn has_bias(&self) -> bool {
239 matches!(self.bias_ih, GruBias::Parameter(_))
240 }
241}
242
243impl Module for GruLayer {
244 fn forward(&self, input: &Matrix) -> Result<Matrix> {
245 GruLayer::forward(self, input)
246 }
247
248 fn registry(&self) -> &ModuleRegistry {
249 &self.registry
250 }
251}
252
253pub struct GruCell {
255 layer: GruLayer,
256}
257
258impl GruCell {
259 #[allow(clippy::too_many_arguments)]
260 pub fn new_with_seed(
261 input_size: usize,
262 hidden_size: usize,
263 bias: bool,
264 seed: u64,
265 ) -> Result<Self> {
266 Self::new_with_seed_on(&Runtime::current()?, input_size, hidden_size, bias, seed)
267 }
268
269 pub fn new_with_seed_on(
276 runtime: &Runtime,
277 input_size: usize,
278 hidden_size: usize,
279 bias: bool,
280 seed: u64,
281 ) -> Result<Self> {
282 if input_size == 0 || hidden_size == 0 || hidden_size > 1024 {
283 return Err(Error::invalid_argument(
284 "GRU cell requires nonzero input/hidden sizes and hidden size <= 1024",
285 ));
286 }
287 Ok(Self {
288 layer: GruLayer::new_with_seed(runtime, input_size, hidden_size, bias, seed)?,
289 })
290 }
291
292 pub fn new_from_matrices(
299 weight_ih: Matrix,
300 weight_hh: Matrix,
301 bias_ih: Matrix,
302 bias_hh: Matrix,
303 ) -> Result<Self> {
304 Ok(Self {
305 layer: GruLayer::from_values(weight_ih, weight_hh, Some(bias_ih), Some(bias_hh))?,
306 })
307 }
308
309 pub fn new_from_weights(weight_ih: Matrix, weight_hh: Matrix) -> Result<Self> {
316 Ok(Self {
317 layer: GruLayer::from_values(weight_ih, weight_hh, None, None)?,
318 })
319 }
320
321 pub fn zero_state(&self, batch: usize) -> Result<Matrix> {
328 if batch == 0 {
329 return Err(Error::invalid_argument("GRU cell batch must be nonzero"));
330 }
331 let count = batch
332 .checked_mul(self.layer.hidden_size)
333 .ok_or_else(|| Error::invalid_argument("GRU cell state size overflows usize"))?;
334 let (weight, _, _) = self.layer.weight_hh.snapshot();
335 Matrix::allocate(
336 weight.runtime(),
337 vec![batch, self.layer.hidden_size],
338 count,
339 DType::F32,
340 )
341 }
342
343 pub fn step(&self, input: &Matrix, hidden: &Matrix) -> Result<Matrix> {
349 self.layer.step(input, hidden)
350 }
351
352 pub const fn input_size(&self) -> usize {
354 self.layer.input_size
355 }
356
357 pub const fn hidden_size(&self) -> usize {
359 self.layer.hidden_size
360 }
361
362 pub fn has_bias(&self) -> bool {
364 self.layer.has_bias()
365 }
366
367 pub fn all_parameters(&self) -> Result<Vec<Parameter>> {
369 Module::all_parameters(self)
370 }
371}
372
373impl Module for GruCell {
374 fn forward(&self, input: &Matrix) -> Result<Matrix> {
375 let [batch, _] = input.shape() else {
376 return Err(Error::invalid_argument(
377 "GRU cell input must have shape [B, I]",
378 ));
379 };
380 self.step(input, &self.zero_state(*batch)?)
381 }
382
383 fn registry(&self) -> &ModuleRegistry {
384 &self.layer.registry
385 }
386}
387
388pub struct Gru {
393 input_size: usize,
394 hidden_size: usize,
395 layers: Vec<Rc<GruLayer>>,
396 registry: ModuleRegistry,
397}
398
399impl Gru {
400 #[allow(clippy::too_many_arguments)]
401 pub fn new_with_seed(
402 input_size: usize,
403 hidden_size: usize,
404 num_layers: usize,
405 bias: bool,
406 seed: u64,
407 ) -> Result<Self> {
408 Self::new_with_seed_on(
409 &Runtime::current()?,
410 input_size,
411 hidden_size,
412 num_layers,
413 bias,
414 seed,
415 )
416 }
417
418 pub fn new_with_seed_on(
426 runtime: &Runtime,
427 input_size: usize,
428 hidden_size: usize,
429 num_layers: usize,
430 bias: bool,
431 seed: u64,
432 ) -> Result<Self> {
433 if input_size == 0 || hidden_size == 0 || hidden_size > 1024 || num_layers == 0 {
434 return Err(Error::invalid_argument(
435 "GRU requires nonzero input/hidden/layer counts and hidden size <= 1024",
436 ));
437 }
438 let mut layers = Vec::with_capacity(num_layers);
439 let mut registry = ModuleRegistry::new();
440 for index in 0..num_layers {
441 let layer_input = if index == 0 { input_size } else { hidden_size };
442 let layer = Rc::new(GruLayer::new_with_seed(
443 runtime,
444 layer_input,
445 hidden_size,
446 bias,
447 seed.wrapping_add((index as u64).wrapping_mul(0xd1b5_4a32_d192_ed03)),
448 )?);
449 registry.register_module(format!("layer{index}"), layer.clone())?;
450 layers.push(layer);
451 }
452 Ok(Self {
453 input_size,
454 hidden_size,
455 layers,
456 registry,
457 })
458 }
459
460 pub fn new_from_matrices(
468 weight_ih: Matrix,
469 weight_hh: Matrix,
470 bias_ih: Matrix,
471 bias_hh: Matrix,
472 ) -> Result<Self> {
473 Self::from_one_layer(weight_ih, weight_hh, Some(bias_ih), Some(bias_hh))
474 }
475
476 pub fn new_from_weights(weight_ih: Matrix, weight_hh: Matrix) -> Result<Self> {
483 Self::from_one_layer(weight_ih, weight_hh, None, None)
484 }
485
486 fn from_one_layer(
487 weight_ih: Matrix,
488 weight_hh: Matrix,
489 bias_ih: Option<Matrix>,
490 bias_hh: Option<Matrix>,
491 ) -> Result<Self> {
492 let [gate_size, input_size] = weight_ih.shape() else {
493 return Err(Error::invalid_argument(
494 "GRU input weight must have shape [3H, I]",
495 ));
496 };
497 if gate_size % 3 != 0 {
498 return Err(Error::invalid_argument(
499 "GRU input weight first extent must be divisible by three",
500 ));
501 }
502 let input_size = *input_size;
503 let hidden_size = gate_size / 3;
504 let layer = Rc::new(GruLayer::from_values(
505 weight_ih, weight_hh, bias_ih, bias_hh,
506 )?);
507 let mut registry = ModuleRegistry::new();
508 registry.register_module("layer0", layer.clone())?;
509 Ok(Self {
510 input_size,
511 hidden_size,
512 layers: vec![layer],
513 registry,
514 })
515 }
516
517 pub fn forward(&self, input: &Matrix) -> Result<Matrix> {
525 let [_, _, input_size] = input.shape() else {
526 return Err(Error::invalid_argument(
527 "GRU input must have shape [B, S, I]",
528 ));
529 };
530 if *input_size != self.input_size {
531 return Err(Error::invalid_argument(format!(
532 "GRU expected input width {}; found {input_size}",
533 self.input_size
534 )));
535 }
536 let mut output = input.clone();
537 for layer in &self.layers {
538 output = layer.forward(&output)?;
539 }
540 Ok(output)
541 }
542
543 pub const fn input_size(&self) -> usize {
545 self.input_size
546 }
547
548 pub const fn hidden_size(&self) -> usize {
550 self.hidden_size
551 }
552
553 pub fn num_layers(&self) -> usize {
555 self.layers.len()
556 }
557
558 pub fn has_bias(&self) -> bool {
560 self.layers.first().is_some_and(|layer| layer.has_bias())
561 }
562
563 pub fn all_parameters(&self) -> Result<Vec<Parameter>> {
565 Module::all_parameters(self)
566 }
567
568 pub fn layer_parameters(&self, layer: usize) -> Option<Vec<Parameter>> {
571 self.layers.get(layer).map(|layer| layer.parameters())
572 }
573}
574
575impl Module for Gru {
576 fn forward(&self, input: &Matrix) -> Result<Matrix> {
577 Gru::forward(self, input)
578 }
579
580 fn registry(&self) -> &ModuleRegistry {
581 &self.registry
582 }
583}
584
585fn xavier_matrix(
586 runtime: &Runtime,
587 output_features: usize,
588 input_features: usize,
589 seed: u64,
590) -> Result<Matrix> {
591 let count = output_features
592 .checked_mul(input_features)
593 .ok_or_else(|| Error::invalid_argument("GRU weight size overflows usize"))?;
594 let denominator = output_features
595 .checked_add(input_features)
596 .ok_or_else(|| Error::invalid_argument("GRU Xavier extent overflows usize"))?;
597 let limit = (6.0_f32 / denominator as f32).sqrt();
598 Matrix::new_from_f32_on(
599 runtime,
600 [output_features, input_features],
601 &random::symmetric_uniform(count, limit, seed),
602 )
603}