incin-core 0.1.0

Core tensor operations and static shape checking for incin
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
use crate::backend_authoring::SupportsDType;
use crate::err::{Error, Result};
use crate::exec::catalog::op;
use crate::nn::init::Init;
use crate::nn::linear::LinearShape;
use crate::nn::optional::{False, True};
use crate::nn::param::{Frozen, TrainState, Trainable};
use crate::nn::{Linear, Module, VisitParameters};
use crate::shapes::shape::{DimCons, Nil};
use crate::shapes::{Dim, Dyn, DynShape, Shape, ShapeValue};
use crate::tensor::backend::Execute;
use crate::tensor::base::Tensor;
use crate::tensor::device::Device;
use crate::tensor::dtype::DType;
use alloc::string::ToString;
use alloc::vec::Vec;

type D2<A, B> = DimCons<A, DimCons<B, Nil>>;
type D3<A, B, C> = DimCons<A, DimCons<B, DimCons<C, Nil>>>;

/// A shape marker trait specifying the input and output features of an [`LSTMCell`] / [`LSTM`].
///
/// Supply `(In, Out)` for fully static dimensions, or [`Dyn`] for fully runtime sizes.
pub trait LstmShape: Shape + DynShape {
    /// `In`.
    type In: Dim;
    /// `Out`.
    type Out: Dim;
    /// Input-to-hidden projection geometry.
    type IhShape: LinearShape<InF = Self::In, OutF = Self::Out>;
    /// Hidden-to-hidden recurrence geometry.
    type HhShape: LinearShape<InF = Self::Out, OutF = Self::Out>;
}

impl<In: Dim, Out: Dim> LstmShape
    for crate::shapes::shape::DimCons<
        In,
        crate::shapes::shape::DimCons<Out, crate::shapes::shape::Nil>,
    >
{
    type In = In;
    type Out = Out;
    type IhShape = crate::shapes::shape::DimCons<
        In,
        crate::shapes::shape::DimCons<Out, crate::shapes::shape::Nil>,
    >;
    type HhShape = crate::shapes::shape::DimCons<
        Out,
        crate::shapes::shape::DimCons<Out, crate::shapes::shape::Nil>,
    >;
}

impl LstmShape for Dyn {
    /// `In`.
    type In = usize;
    /// `Out`.
    type Out = usize;
    type IhShape = Dyn;
    type HhShape = Dyn;
}

// ---------------------------------------------------------------------------
// LSTMCellBuilder: typestate builder
// ---------------------------------------------------------------------------

/// A builder for constructing an [`LSTMCell`] before target-based initialization.
///
/// Stores the layer geometry ([`ShapeValue`]), weight and bias initializer policies
/// (grouped semantically as input and hidden), and compile-time typestate parameters
/// for bias presence and trainability.
pub struct LSTMCellBuilder<
    S: LstmShape,
    BiasIh: crate::nn::optional::OptionalField = True,
    BiasHh: crate::nn::optional::OptionalField = True,
    Train: TrainState = Trainable,
> {
    /// Shape specification (encodes `[in_features, out_features]`).
    pub shape: ShapeValue<S>,
    /// Initializer for all input-to-hidden weight matrices (`W_ih_i`, `W_ih_f`, etc.).
    pub input_weight_init: Init,
    /// Initializer for all hidden-to-hidden weight matrices (`W_hh_i`, `W_hh_f`, etc.).
    pub hidden_weight_init: Init,
    /// Initializer for all input-to-hidden bias vectors.
    pub input_bias_init: Init,
    /// Initializer for all hidden-to-hidden bias vectors.
    pub hidden_bias_init: Init,
    /// Bias-presence and train-state markers.
    pub _phantom: core::marker::PhantomData<(BiasIh, BiasHh, Train)>,
}

impl<
    S: LstmShape,
    BiasIh: crate::nn::optional::OptionalField,
    BiasHh: crate::nn::optional::OptionalField,
    Train: TrainState,
> LSTMCellBuilder<S, BiasIh, BiasHh, Train>
{
    /// Returns a reference to the shape specification of this builder.
    pub fn shape(&self) -> &ShapeValue<S> {
        &self.shape
    }

    /// Removes input-to-hidden biases from the built cell.
    pub fn no_input_bias(self) -> LSTMCellBuilder<S, False, BiasHh, Train> {
        LSTMCellBuilder {
            shape: self.shape,
            input_weight_init: self.input_weight_init,
            hidden_weight_init: self.hidden_weight_init,
            input_bias_init: self.input_bias_init,
            hidden_bias_init: self.hidden_bias_init,
            _phantom: core::marker::PhantomData,
        }
    }

    /// Removes hidden-to-hidden biases from the built cell.
    pub fn no_hidden_bias(self) -> LSTMCellBuilder<S, BiasIh, False, Train> {
        LSTMCellBuilder {
            shape: self.shape,
            input_weight_init: self.input_weight_init,
            hidden_weight_init: self.hidden_weight_init,
            input_bias_init: self.input_bias_init,
            hidden_bias_init: self.hidden_bias_init,
            _phantom: core::marker::PhantomData,
        }
    }

    /// Removes all biases from the built cell.
    pub fn no_bias(self) -> LSTMCellBuilder<S, False, False, Train> {
        LSTMCellBuilder {
            shape: self.shape,
            input_weight_init: self.input_weight_init,
            hidden_weight_init: self.hidden_weight_init,
            input_bias_init: self.input_bias_init,
            hidden_bias_init: self.hidden_bias_init,
            _phantom: core::marker::PhantomData,
        }
    }

    /// Marks the created cell parameters as frozen (non-trainable).
    pub fn frozen(self) -> LSTMCellBuilder<S, BiasIh, BiasHh, Frozen> {
        LSTMCellBuilder {
            shape: self.shape,
            input_weight_init: self.input_weight_init,
            hidden_weight_init: self.hidden_weight_init,
            input_bias_init: self.input_bias_init,
            hidden_bias_init: self.hidden_bias_init,
            _phantom: core::marker::PhantomData,
        }
    }

    /// Sets the initializer used for all input-to-hidden weight matrices.
    pub fn input_weight_init(mut self, init: Init) -> Self {
        self.input_weight_init = init;
        self
    }

    /// Sets the initializer used for all hidden-to-hidden weight matrices.
    pub fn hidden_weight_init(mut self, init: Init) -> Self {
        self.hidden_weight_init = init;
        self
    }

    /// Sets the initializer used for all input-to-hidden bias vectors.
    pub fn input_bias_init(mut self, init: Init) -> Self {
        self.input_bias_init = init;
        self
    }

    /// Sets the initializer used for all hidden-to-hidden bias vectors.
    pub fn hidden_bias_init(mut self, init: Init) -> Self {
        self.hidden_bias_init = init;
        self
    }
}

/// Free constructor for a backend-independent [`LSTMCellBuilder`].
pub fn lstm_cell<S: LstmShape>(shape: ShapeValue<S>) -> LSTMCellBuilder<S> {
    let init = crate::nn::init::kaiming_uniform();
    LSTMCellBuilder {
        shape,
        input_weight_init: init,
        hidden_weight_init: init,
        input_bias_init: init,
        hidden_bias_init: init,
        _phantom: core::marker::PhantomData,
    }
}

// ---------------------------------------------------------------------------
// LSTMBuilder: typestate builder for the multi-step LSTM
// ---------------------------------------------------------------------------

/// A builder for constructing an [`LSTM`] before target-based initialization.
///
/// Wraps an [`LSTMCellBuilder`] and exposes the same bias/trainability controls.
pub struct LSTMBuilder<
    S: LstmShape,
    BiasIh: crate::nn::optional::OptionalField = True,
    BiasHh: crate::nn::optional::OptionalField = True,
    Train: TrainState = Trainable,
> {
    /// The inner cell builder.
    pub cell: LSTMCellBuilder<S, BiasIh, BiasHh, Train>,
}

impl<
    S: LstmShape,
    BiasIh: crate::nn::optional::OptionalField,
    BiasHh: crate::nn::optional::OptionalField,
    Train: TrainState,
> LSTMBuilder<S, BiasIh, BiasHh, Train>
{
    /// Returns a reference to the shape specification of this builder.
    pub fn shape(&self) -> &ShapeValue<S> {
        self.cell.shape()
    }

    /// Removes input-to-hidden biases from the built LSTM.
    pub fn no_input_bias(self) -> LSTMBuilder<S, False, BiasHh, Train> {
        LSTMBuilder {
            cell: self.cell.no_input_bias(),
        }
    }

    /// Removes hidden-to-hidden biases from the built LSTM.
    pub fn no_hidden_bias(self) -> LSTMBuilder<S, BiasIh, False, Train> {
        LSTMBuilder {
            cell: self.cell.no_hidden_bias(),
        }
    }

    /// Removes all biases from the built LSTM.
    pub fn no_bias(self) -> LSTMBuilder<S, False, False, Train> {
        LSTMBuilder {
            cell: self.cell.no_bias(),
        }
    }

    /// Marks the created LSTM parameters as frozen (non-trainable).
    pub fn frozen(self) -> LSTMBuilder<S, BiasIh, BiasHh, Frozen> {
        LSTMBuilder {
            cell: self.cell.frozen(),
        }
    }

    /// Sets the initializer used for all input-to-hidden weight matrices.
    pub fn input_weight_init(mut self, init: Init) -> Self {
        self.cell = self.cell.input_weight_init(init);
        self
    }

    /// Sets the initializer used for all hidden-to-hidden weight matrices.
    pub fn hidden_weight_init(mut self, init: Init) -> Self {
        self.cell = self.cell.hidden_weight_init(init);
        self
    }

    /// Sets the initializer used for all input-to-hidden bias vectors.
    pub fn input_bias_init(mut self, init: Init) -> Self {
        self.cell = self.cell.input_bias_init(init);
        self
    }

    /// Sets the initializer used for all hidden-to-hidden bias vectors.
    pub fn hidden_bias_init(mut self, init: Init) -> Self {
        self.cell = self.cell.hidden_bias_init(init);
        self
    }
}

/// Free constructor for a backend-independent [`LSTMBuilder`].
pub fn lstm<S: LstmShape>(shape: ShapeValue<S>) -> LSTMBuilder<S> {
    LSTMBuilder {
        cell: lstm_cell(shape),
    }
}

// ---------------------------------------------------------------------------
// LSTMCell: concrete BiasIh / BiasHh combinations
// ---------------------------------------------------------------------------

/// A single LSTM step cell implementing the standard 4-gate recurrence.
///
/// * `S`: [`LstmShape`]: `(In, Out)` static or [`Dyn`] for runtime sizes.
/// * `BiasIh`: whether input-to-hidden biases exist: [`True`], [`False`].
/// * `BiasHh`: whether hidden-to-hidden biases exist: [`True`], [`False`].
/// * `K`: parameter dtype (default: `f32`).
/// * `Train`: trainability typestate (default: [`Trainable`]).
///
/// ## Examples
///
/// ```rust
/// # extern crate incin_core as incin;
/// # fn main() -> incin::prelude::Result<()> {
/// # type DefaultBackend = incin_backends::cpu::CpuBackendImpl;
/// use incin::prelude::*;
///
/// // Fully static, both biases present (default)
/// let cell = LSTMCell::<s![10, 20], DefaultBackend>::build(())?;
///
/// // Fully static, input bias present, hidden bias absent
/// let cell = LSTMCell::<s![10, 20], DefaultBackend, True, False>::build(())?;
///
/// // Fully dynamic shape, both biases always present
/// let cell = LSTMCell::<Dyn, DefaultBackend>::build((10, 20))?;
///
/// // Fully dynamic shape, no biases
/// let cell = LSTMCell::<Dyn, DefaultBackend, False, False>::build((10, 20))?;
/// # Ok(()) }
/// ```
#[derive(Debug, Clone)]
pub struct LSTMCell<
    S: LstmShape,
    B: crate::tensor::backend::VariableBackend,
    BiasIh: crate::nn::optional::OptionalField = True,
    BiasHh: crate::nn::optional::OptionalField = True,
    K: DType = f32,
    Train: TrainState = Trainable,
> where
    S::IhShape: LinearShape,
    S::HhShape: LinearShape,
{
    /// `wi_i`.
    pub wi_i: Linear<S::IhShape, B, BiasIh, K, Train>,
    /// `wi_f`.
    pub wi_f: Linear<S::IhShape, B, BiasIh, K, Train>,
    /// `wi_g`.
    pub wi_g: Linear<S::IhShape, B, BiasIh, K, Train>,
    /// `wi_o`.
    pub wi_o: Linear<S::IhShape, B, BiasIh, K, Train>,
    /// `wh_i`.
    pub wh_i: Linear<S::HhShape, B, BiasHh, K, Train>,
    /// `wh_f`.
    pub wh_f: Linear<S::HhShape, B, BiasHh, K, Train>,
    /// `wh_g`.
    pub wh_g: Linear<S::HhShape, B, BiasHh, K, Train>,
    /// `wh_o`.
    pub wh_o: Linear<S::HhShape, B, BiasHh, K, Train>,
}

impl<S, B, BiasIh, BiasHh, K: DType, Train: TrainState> LSTMCell<S, B, BiasIh, BiasHh, K, Train>
where
    S: LstmShape,
    B: crate::tensor::backend::VariableBackend
        + SupportsDType<K>
        + crate::tensor::backend::SupportsDType<K>
        + crate::nn::param::ParameterInit<K>,
    BiasIh: crate::nn::optional::OptionalField,
    BiasHh: crate::nn::optional::OptionalField,
    <K as DType>::Arg: Clone,
    <S::In as Dim>::Arg: Clone,
    <S::Out as Dim>::Arg: Clone,
    <B::Device as Device>::Arg: Clone,
    <BiasIh as crate::nn::optional::OptionalField>::Arg: Clone,
    <BiasHh as crate::nn::optional::OptionalField>::Arg: Clone,
{
    /// Constructs the cell directly from explicit arguments (the "build" path).
    ///
    /// Prefer the target-aware `LSTMCellBuilder::init()` path for new code.
    pub fn build<A>(args: A) -> Result<Self>
    where
        A: crate::tensor::arg_into::LayerArgInto<(
                <S::In as Dim>::Arg,
                <S::Out as Dim>::Arg,
                <K as DType>::Arg,
                <B::Device as Device>::Arg,
                <BiasIh as crate::nn::optional::OptionalField>::Arg,
                <BiasHh as crate::nn::optional::OptionalField>::Arg,
            )>,
    {
        let (input, output, dtype, device, bias_ih, bias_hh) = args.into_layer_arg();
        Ok(Self {
            wi_i: Linear::<_, _, _, K, Train>::build_full(
                input.clone(),
                output.clone(),
                dtype.clone(),
                device.clone(),
                bias_ih.clone(),
            )?,
            wi_f: Linear::<_, _, _, K, Train>::build_full(
                input.clone(),
                output.clone(),
                dtype.clone(),
                device.clone(),
                bias_ih.clone(),
            )?,
            wi_g: Linear::<_, _, _, K, Train>::build_full(
                input.clone(),
                output.clone(),
                dtype.clone(),
                device.clone(),
                bias_ih.clone(),
            )?,
            wi_o: Linear::<_, _, _, K, Train>::build_full(
                input,
                output.clone(),
                dtype.clone(),
                device.clone(),
                bias_ih,
            )?,
            wh_i: Linear::<_, _, _, K, Train>::build_full(
                output.clone(),
                output.clone(),
                dtype.clone(),
                device.clone(),
                bias_hh.clone(),
            )?,
            wh_f: Linear::<_, _, _, K, Train>::build_full(
                output.clone(),
                output.clone(),
                dtype.clone(),
                device.clone(),
                bias_hh.clone(),
            )?,
            wh_g: Linear::<_, _, _, K, Train>::build_full(
                output.clone(),
                output.clone(),
                dtype.clone(),
                device.clone(),
                bias_hh.clone(),
            )?,
            wh_o: Linear::<_, _, _, K, Train>::build_full(
                output.clone(),
                output,
                dtype,
                device,
                bias_hh,
            )?,
        })
    }

    /// Converts this cell's parameters to frozen typestate.
    pub fn freeze(self) -> LSTMCell<S, B, BiasIh, BiasHh, K, Frozen> {
        LSTMCell {
            wi_i: self.wi_i.freeze(),
            wi_f: self.wi_f.freeze(),
            wi_g: self.wi_g.freeze(),
            wi_o: self.wi_o.freeze(),
            wh_i: self.wh_i.freeze(),
            wh_f: self.wh_f.freeze(),
            wh_g: self.wh_g.freeze(),
            wh_o: self.wh_o.freeze(),
        }
    }

    /// Converts this cell's parameters to trainable typestate.
    pub fn unfreeze(self) -> LSTMCell<S, B, BiasIh, BiasHh, K, Trainable> {
        LSTMCell {
            wi_i: self.wi_i.unfreeze(),
            wi_f: self.wi_f.unfreeze(),
            wi_g: self.wi_g.unfreeze(),
            wi_o: self.wi_o.unfreeze(),
            wh_i: self.wh_i.unfreeze(),
            wh_f: self.wh_f.unfreeze(),
            wh_g: self.wh_g.unfreeze(),
            wh_o: self.wh_o.unfreeze(),
        }
    }
}

// ---------------------------------------------------------------------------
// Parameter visitor (generic over all BiasIh/BiasHh/K/Train combinations)
// ---------------------------------------------------------------------------

impl<
    In: Dim,
    Out: Dim,
    B: crate::tensor::backend::VariableBackend,
    BiasIh: crate::nn::optional::OptionalField,
    BiasHh: crate::nn::optional::OptionalField,
    K: DType,
    Train: TrainState,
> VisitParameters<B> for LSTMCell<D2<In, Out>, B, BiasIh, BiasHh, K, Train>
where
    Linear<D2<In, Out>, B, BiasIh, K, Train>: VisitParameters<B>,
    Linear<D2<Out, Out>, B, BiasHh, K, Train>: VisitParameters<B>,
{
    fn visit_parameters<V: crate::nn::ParameterVisitor<B>>(
        &self,
        path: &crate::nn::StatePath,
        visitor: &mut V,
    ) -> crate::err::Result<()> {
        self.wi_i
            .visit_parameters(&path.try_child("wi_i")?, visitor)?;
        self.wi_f
            .visit_parameters(&path.try_child("wi_f")?, visitor)?;
        self.wi_g
            .visit_parameters(&path.try_child("wi_g")?, visitor)?;
        self.wi_o
            .visit_parameters(&path.try_child("wi_o")?, visitor)?;
        self.wh_i
            .visit_parameters(&path.try_child("wh_i")?, visitor)?;
        self.wh_f
            .visit_parameters(&path.try_child("wh_f")?, visitor)?;
        self.wh_g
            .visit_parameters(&path.try_child("wh_g")?, visitor)?;
        self.wh_o
            .visit_parameters(&path.try_child("wh_o")?, visitor)
    }
}

// ---------------------------------------------------------------------------
// Module (forward) impl: static shapes
// ---------------------------------------------------------------------------

impl<
    In: Dim,
    Out: Dim,
    Batch: Dim,
    B: crate::tensor::backend::VariableBackend
        + Execute<op::Add>
        + Execute<op::Mul>
        + Execute<op::Sigmoid>
        + Execute<op::Tanh>,
    BiasIh: crate::nn::optional::OptionalField,
    BiasHh: crate::nn::optional::OptionalField,
    K: DType,
    Train: TrainState,
>
    Module<(
        Tensor<D2<Batch, In>, B, K>,
        (Tensor<D2<Batch, Out>, B, K>, Tensor<D2<Batch, Out>, B, K>),
    )> for LSTMCell<D2<In, Out>, B, BiasIh, BiasHh, K, Train>
where
    Linear<D2<In, Out>, B, BiasIh, K, Train>:
        Module<Tensor<D2<Batch, In>, B, K>, Output = Tensor<D2<Batch, Out>, B, K>, Error = Error>,
    Linear<D2<Out, Out>, B, BiasHh, K, Train>:
        Module<Tensor<D2<Batch, Out>, B, K>, Output = Tensor<D2<Batch, Out>, B, K>, Error = Error>,
    <B as Execute<op::Add>>::Output: Into<B::Storage<K>>,
    <B as Execute<op::Mul>>::Output: Into<B::Storage<K>>,
    <B as Execute<op::Sigmoid>>::Output: Into<B::Storage<K>>,
    <B as Execute<op::Tanh>>::Output: Into<B::Storage<K>>,
{
    /// The output tensor type produced by this module's forward pass.
    type Output = (Tensor<D2<Batch, Out>, B, K>, Tensor<D2<Batch, Out>, B, K>);
    /// The error type returned if the forward pass fails.
    type Error = Error;

    #[inline]
    /// Runs the forward pass of this module on the given input.
    fn forward(
        &self,
        (x, (h_prev, c_prev)): (
            Tensor<D2<Batch, In>, B, K>,
            (Tensor<D2<Batch, Out>, B, K>, Tensor<D2<Batch, Out>, B, K>),
        ),
    ) -> core::result::Result<Self::Output, Error> {
        let i = self
            .wi_i
            .forward(x.clone())?
            .add_exact(&self.wh_i.forward(h_prev.clone())?)?
            .sigmoid()?;
        let f = self
            .wi_f
            .forward(x.clone())?
            .add_exact(&self.wh_f.forward(h_prev.clone())?)?
            .sigmoid()?;
        let g = self
            .wi_g
            .forward(x.clone())?
            .add_exact(&self.wh_g.forward(h_prev.clone())?)?
            .tanh()?;
        let o = self
            .wi_o
            .forward(x)?
            .add_exact(&self.wh_o.forward(h_prev)?)?
            .sigmoid()?;
        let c = f.mul_exact(&c_prev)?.add_exact(&i.mul_exact(&g)?)?;
        let h = o.mul_exact(&c.clone().tanh()?)?;
        Ok((h, c))
    }
}

// ---------------------------------------------------------------------------
// LSTM (multi-step wrapper)
// ---------------------------------------------------------------------------

#[derive(Debug, Clone)]
/// `LSTM`.
#[allow(clippy::upper_case_acronyms)]
pub struct LSTM<
    S: LstmShape,
    B: crate::tensor::backend::VariableBackend,
    BiasIh: crate::nn::optional::OptionalField = True,
    BiasHh: crate::nn::optional::OptionalField = True,
    K: DType = f32,
    Train: TrainState = Trainable,
> {
    /// `cell`.
    pub cell: LSTMCell<S, B, BiasIh, BiasHh, K, Train>,
}

impl<
    S: LstmShape,
    B: crate::tensor::backend::VariableBackend,
    BiasIh: crate::nn::optional::OptionalField,
    BiasHh: crate::nn::optional::OptionalField,
    K: DType,
    Train: TrainState,
> LSTM<S, B, BiasIh, BiasHh, K, Train>
{
    /// Creates a new instance from a pre-built cell.
    pub fn new(cell: LSTMCell<S, B, BiasIh, BiasHh, K, Train>) -> Self {
        Self { cell }
    }

    /// Converts this LSTM's parameters to frozen typestate.
    pub fn freeze(self) -> LSTM<S, B, BiasIh, BiasHh, K, Frozen>
    where
        LSTMCell<S, B, BiasIh, BiasHh, K, Train>: Sized,
        S: LstmShape,
        B: crate::tensor::backend::VariableBackend
            + SupportsDType<K>
            + crate::tensor::backend::SupportsDType<K>
            + crate::nn::param::ParameterInit<K>,
        <K as DType>::Arg: Clone,
        <S::In as Dim>::Arg: Clone,
        <S::Out as Dim>::Arg: Clone,
        <B::Device as Device>::Arg: Clone,
        <BiasIh as crate::nn::optional::OptionalField>::Arg: Clone,
        <BiasHh as crate::nn::optional::OptionalField>::Arg: Clone,
    {
        LSTM {
            cell: self.cell.freeze(),
        }
    }

    /// Converts this LSTM's parameters to trainable typestate.
    pub fn unfreeze(self) -> LSTM<S, B, BiasIh, BiasHh, K, Trainable>
    where
        LSTMCell<S, B, BiasIh, BiasHh, K, Train>: Sized,
        S: LstmShape,
        B: crate::tensor::backend::VariableBackend
            + SupportsDType<K>
            + crate::tensor::backend::SupportsDType<K>
            + crate::nn::param::ParameterInit<K>,
        <K as DType>::Arg: Clone,
        <S::In as Dim>::Arg: Clone,
        <S::Out as Dim>::Arg: Clone,
        <B::Device as Device>::Arg: Clone,
        <BiasIh as crate::nn::optional::OptionalField>::Arg: Clone,
        <BiasHh as crate::nn::optional::OptionalField>::Arg: Clone,
    {
        LSTM {
            cell: self.cell.unfreeze(),
        }
    }
}

impl<
    In: Dim,
    Out: Dim,
    B: crate::tensor::backend::VariableBackend,
    BiasIh: crate::nn::optional::OptionalField,
    BiasHh: crate::nn::optional::OptionalField,
    K: DType,
    Train: TrainState,
> VisitParameters<B> for LSTM<D2<In, Out>, B, BiasIh, BiasHh, K, Train>
where
    LSTMCell<D2<In, Out>, B, BiasIh, BiasHh, K, Train>: VisitParameters<B>,
{
    fn visit_parameters<V: crate::nn::ParameterVisitor<B>>(
        &self,
        path: &crate::nn::StatePath,
        visitor: &mut V,
    ) -> crate::err::Result<()> {
        self.cell
            .visit_parameters(&path.try_child("cell")?, visitor)
    }
}

impl<
    In: Dim<Arg = ()>,
    Out: Dim<Arg = ()>,
    Batch: Dim<Arg = ()>,
    Seq: Dim<Arg = ()>,
    B: crate::tensor::backend::VariableBackend
        + Execute<op::StackExact>
        + Execute<op::Narrow>
        + Execute<op::SqueezeExact>
        + crate::exec::Capabilities,
    BiasIh: crate::nn::optional::OptionalField,
    BiasHh: crate::nn::optional::OptionalField,
    K: DType,
    Train: TrainState,
>
    Module<(
        Tensor<D3<Batch, Seq, In>, B, K>,
        (Tensor<D2<Batch, Out>, B, K>, Tensor<D2<Batch, Out>, B, K>),
    )> for LSTM<D2<In, Out>, B, BiasIh, BiasHh, K, Train>
where
    <B as Execute<op::StackExact>>::Output: Into<B::Storage<K>>,
    <B as Execute<op::Narrow>>::Output: Into<B::Storage<K>>,
    <B as Execute<op::SqueezeExact>>::Output: Into<B::Storage<K>>,
    LSTMCell<D2<In, Out>, B, BiasIh, BiasHh, K, Train>: Module<
            (
                Tensor<D2<Batch, In>, B, K>,
                (Tensor<D2<Batch, Out>, B, K>, Tensor<D2<Batch, Out>, B, K>),
            ),
            Output = (Tensor<D2<Batch, Out>, B, K>, Tensor<D2<Batch, Out>, B, K>),
            Error = Error,
        >,
{
    /// The output tensor type produced by this module's forward pass.
    type Output = (
        Tensor<D3<Batch, Seq, Out>, B, K>,
        (Tensor<D2<Batch, Out>, B, K>, Tensor<D2<Batch, Out>, B, K>),
    );
    /// The error type returned if the forward pass fails.
    type Error = Error;

    #[inline]
    /// Runs the forward pass of this module on the given input.
    fn forward(
        &self,
        (x, (mut h, mut c)): (
            Tensor<D3<Batch, Seq, In>, B, K>,
            (Tensor<D2<Batch, Out>, B, K>, Tensor<D2<Batch, Out>, B, K>),
        ),
    ) -> core::result::Result<Self::Output, Error> {
        let seq_len = Seq::static_size().map_err(Error::Shape)?;
        let mut outputs = Vec::with_capacity(seq_len);

        for i in 0..seq_len {
            let x_step = x.clone().try_narrow(1isize, i, 1)?.try_squeeze(1isize)?;
            let x_step_static: Tensor<D2<Batch, In>, B, K> = x_step.into_shape()?;
            let (h_next, c_next) = self.cell.forward((x_step_static, (h, c)))?;
            h = h_next;
            c = c_next;
            outputs.push(h.clone().into_shape::<Dyn>()?);
        }

        let refs: Vec<&Tensor<Dyn, B, K>> = outputs.iter().collect();
        let stacked_dyn = crate::tensor::ops::manipulation::try_stack_tensors(&refs, 1)?;
        let stacked: Tensor<D3<Batch, Seq, Out>, B, K> = stacked_dyn.into_shape()?;
        Ok((stacked, (h, c)))
    }
}

impl<
    S: LstmShape,
    B: crate::tensor::backend::VariableBackend,
    BiasIh: crate::nn::optional::OptionalField,
    BiasHh: crate::nn::optional::OptionalField,
    K: DType,
    Train: TrainState,
> crate::nn::module::NamedLayers for LSTMCell<S, B, BiasIh, BiasHh, K, Train>
where
    Linear<S::IhShape, B, BiasIh, K, Train>: crate::nn::module::NamedLayers,
    Linear<S::HhShape, B, BiasHh, K, Train>: crate::nn::module::NamedLayers,
{
    /// Returns the layer hierarchy rooted at this module for visualization.
    fn layer_structure(&self, prefix: &str) -> Vec<crate::nn::module::LayerNode> {
        let mut children = Vec::new();

        let p_wi_i = if prefix.is_empty() {
            alloc::string::String::from("wi_i")
        } else {
            format!("{}.wi_i", prefix)
        };
        children.extend(self.wi_i.layer_structure(&p_wi_i));
        let p_wi_f = if prefix.is_empty() {
            alloc::string::String::from("wi_f")
        } else {
            format!("{}.wi_f", prefix)
        };
        children.extend(self.wi_f.layer_structure(&p_wi_f));
        let p_wi_g = if prefix.is_empty() {
            alloc::string::String::from("wi_g")
        } else {
            format!("{}.wi_g", prefix)
        };
        children.extend(self.wi_g.layer_structure(&p_wi_g));
        let p_wi_o = if prefix.is_empty() {
            alloc::string::String::from("wi_o")
        } else {
            format!("{}.wi_o", prefix)
        };
        children.extend(self.wi_o.layer_structure(&p_wi_o));
        let p_wh_i = if prefix.is_empty() {
            alloc::string::String::from("wh_i")
        } else {
            format!("{}.wh_i", prefix)
        };
        children.extend(self.wh_i.layer_structure(&p_wh_i));
        let p_wh_f = if prefix.is_empty() {
            alloc::string::String::from("wh_f")
        } else {
            format!("{}.wh_f", prefix)
        };
        children.extend(self.wh_f.layer_structure(&p_wh_f));
        let p_wh_g = if prefix.is_empty() {
            alloc::string::String::from("wh_g")
        } else {
            format!("{}.wh_g", prefix)
        };
        children.extend(self.wh_g.layer_structure(&p_wh_g));
        let p_wh_o = if prefix.is_empty() {
            alloc::string::String::from("wh_o")
        } else {
            format!("{}.wh_o", prefix)
        };
        children.extend(self.wh_o.layer_structure(&p_wh_o));

        let node_name = if prefix.is_empty() {
            alloc::string::String::from("LSTMCell")
        } else {
            prefix.to_string()
        };
        vec![crate::nn::module::LayerNode {
            name: node_name,
            type_name: alloc::string::String::from("LSTMCell"),
            shape_info: "".to_string(),
            children,
        }]
    }
}

impl<
    S: LstmShape,
    B: crate::tensor::backend::VariableBackend,
    BiasIh: crate::nn::optional::OptionalField,
    BiasHh: crate::nn::optional::OptionalField,
    K: DType,
    Train: TrainState,
> crate::nn::module::NamedLayers for LSTM<S, B, BiasIh, BiasHh, K, Train>
where
    LSTMCell<S, B, BiasIh, BiasHh, K, Train>: crate::nn::module::NamedLayers,
{
    /// Returns the layer hierarchy rooted at this module for visualization.
    fn layer_structure(&self, prefix: &str) -> Vec<crate::nn::module::LayerNode> {
        let mut children = Vec::new();
        let p_cell = if prefix.is_empty() {
            alloc::string::String::from("cell")
        } else {
            format!("{}.cell", prefix)
        };
        children.extend(self.cell.layer_structure(&p_cell));

        let node_name = if prefix.is_empty() {
            alloc::string::String::from("LSTM")
        } else {
            prefix.to_string()
        };
        vec![crate::nn::module::LayerNode {
            name: node_name,
            type_name: alloc::string::String::from("LSTM"),
            shape_info: "".to_string(),
            children,
        }]
    }
}