Skip to main content

tract_core/ops/
gru_cell.rs

1use crate::internal::*;
2use tract_linalg::element_wise::ElementWise;
3use tract_linalg::routines::Func;
4
5/// Fused GRU cell epilogue.
6///
7/// Given `xh = Xt·Wᵀ + Wb` and `rh = Ht-1·Rᵀ + Rb`, both `[batch, 3*hidden]` in
8/// ONNX gate order z, r, h, and the previous hidden state `h_prev`
9/// `[batch, hidden]`, computes the new hidden state in a single fused pass:
10///
11/// ```text
12/// zt = sigmoid(xh[..h]    + rh[..h])
13/// rt = sigmoid(xh[h..2h]  + rh[h..2h])
14/// ht = tanh   (xh[2h..3h] + rt (.) rh[2h..3h])
15/// Ht = ht + zt (.) (h_prev - ht)
16/// ```
17///
18/// This is the ONNX GRU with `linear_before_reset != 0`, where the reset gate
19/// scales the already-biased recurrent product so the cell needs no second
20/// matmul. With `linear_before_reset == 0` the reset gate applies to `Ht-1`
21/// before that product and no such epilogue exists; the importer keeps the
22/// decomposed form there, as it does for non-standard activations (`f` must be
23/// sigmoid, `g` must be tanh) and for a symbolic hidden size.
24///
25/// Activations use tract's vectorised `sigmoid`/`tanh` linalg kernels over
26/// contiguous gate slices, so they match the decomposed path; the gate sums are
27/// associated differently, so results differ by rounding. Runs in `f32` or
28/// `f16`, matching the dtype the precision transform settled the graph on.
29#[derive(Debug, Clone, Hash, PartialEq, Eq)]
30pub struct GruEpilogue {
31    pub hidden: usize,
32}
33
34impl Op for GruEpilogue {
35    fn name(&self) -> StaticName {
36        "GruEpilogue".into()
37    }
38
39    fn info(&self) -> TractResult<Vec<String>> {
40        Ok(vec![format!("hidden={}", self.hidden)])
41    }
42
43    op_as_typed_op!();
44}
45
46impl EvalOp for GruEpilogue {
47    op_out_of_plan!();
48
49    fn eval(&self, _ctx: &EvalContext, inputs: TVec<TValue>) -> TractResult<TVec<TValue>> {
50        match inputs[0].datum_type().unquantized() {
51            DatumType::F32 => {
52                self.eval_t::<f32>(inputs, Func::Sigmoid.ew_f32()?, Func::Tanh.ew_f32()?)
53            }
54            DatumType::F16 => {
55                self.eval_t::<f16>(inputs, Func::Sigmoid.ew_f16()?, Func::Tanh.ew_f16()?)
56            }
57            dt => bail!("GruEpilogue only supports f32 and f16 preactivations, got {dt:?}"),
58        }
59    }
60}
61
62impl GruEpilogue {
63    fn eval_t<T>(
64        &self,
65        inputs: TVec<TValue>,
66        sigmoid: Box<dyn ElementWise<T>>,
67        tanh: Box<dyn ElementWise<T>>,
68    ) -> TractResult<TVec<TValue>>
69    where
70        T: Datum
71            + Copy
72            + std::ops::Mul<Output = T>
73            + std::ops::Add<Output = T>
74            + std::ops::Sub<Output = T>,
75    {
76        let h = self.hidden;
77        let h_prev = &inputs[2];
78        let hp = unsafe { h_prev.as_slice_unchecked::<T>() };
79        // Rows come from the state, which also sizes the output: a gate operand
80        // left broadcast on the batch axis would otherwise under-fill it.
81        let rows = hp.len() / h;
82        ensure!(
83            inputs[0].len() == rows * 3 * h && inputs[1].len() == rows * 3 * h,
84            "GruEpilogue expects xh and rh shaped [{rows}, 3*{h}], got {:?} and {:?}",
85            inputs[0].shape(),
86            inputs[1].shape()
87        );
88        let rh = unsafe { inputs[1].as_slice_unchecked::<T>() };
89        let mut acc_t = inputs[0].clone().into_tensor();
90        let acc = unsafe { acc_t.as_slice_mut_unchecked::<T>() };
91        let mut ht = unsafe { Tensor::uninitialized_dt(T::datum_type(), h_prev.shape())? };
92        {
93            let hs = unsafe { ht.as_slice_mut_unchecked::<T>() };
94            for row in 0..rows {
95                let gb = row * 3 * h;
96                let hb = row * h;
97                let g = &mut acc[gb..gb + 3 * h];
98                let r = &rh[gb..gb + 3 * h];
99                for j in 0..2 * h {
100                    g[j] = g[j] + r[j];
101                }
102                sigmoid.run(&mut g[0..2 * h])?;
103                for j in 0..h {
104                    g[2 * h + j] = g[2 * h + j] + g[h + j] * r[2 * h + j];
105                }
106                tanh.run(&mut g[2 * h..3 * h])?;
107                for j in 0..h {
108                    let cand = g[2 * h + j];
109                    hs[hb + j] = cand + g[j] * (hp[hb + j] - cand);
110                }
111            }
112        }
113        Ok(tvec!(ht.into_tvalue()))
114    }
115}
116
117impl TypedOp for GruEpilogue {
118    as_op!();
119
120    fn output_facts(&self, inputs: &[&TypedFact]) -> TractResult<TVec<TypedFact>> {
121        ensure!(inputs.len() == 3, "GruEpilogue expects [xh, rh, h_prev]");
122        ensure!(
123            inputs[0].datum_type == inputs[2].datum_type,
124            "GruEpilogue gate and state datum types differ: {:?} and {:?}",
125            inputs[0].datum_type,
126            inputs[2].datum_type
127        );
128        let h_prev = inputs[2];
129        Ok(tvec!(h_prev.datum_type.fact(h_prev.shape.clone())))
130    }
131}
132
133#[cfg(test)]
134mod tests {
135    use super::*;
136
137    // Fused epilogue must match a scalar reference GRU cell with
138    // linear_before_reset = 1. The reference keeps the ONNX form of the output
139    // update, (1-zt)*ht + zt*Ht-1, so the rearranged form is checked too.
140    // Tolerance covers the rational sigmoid/tanh approximation vs the exact
141    // reference. Multi-row exercises batch.
142    #[test]
143    fn epilogue_matches_scalar_reference() {
144        let h = 4usize;
145        let batch = 3usize;
146        let xh: Vec<f32> =
147            (0..batch * 3 * h).map(|i| ((i * 7 % 29) as f32 - 14.0) * 0.25).collect();
148        let rh: Vec<f32> =
149            (0..batch * 3 * h).map(|i| ((i * 11 % 23) as f32 - 11.0) * 0.3).collect();
150        let hprev: Vec<f32> = (0..batch * h).map(|i| ((i * 5 % 17) as f32 - 8.0) * 0.2).collect();
151        let xh_t = Tensor::from_shape(&[batch, 3 * h], &xh).unwrap();
152        let rh_t = Tensor::from_shape(&[batch, 3 * h], &rh).unwrap();
153        let hprev_t = Tensor::from_shape(&[batch, h], &hprev).unwrap();
154        let op = GruEpilogue { hidden: h };
155        let out = op
156            .eval(
157                &EvalContext::out_of_plan(),
158                tvec!(xh_t.into_tvalue(), rh_t.into_tvalue(), hprev_t.into_tvalue()),
159            )
160            .unwrap();
161        let got = unsafe { out[0].as_slice_unchecked::<f32>() };
162
163        let sig = |x: f32| 1.0 / (1.0 + (-x).exp());
164        for r in 0..batch {
165            for j in 0..h {
166                let p = r * 3 * h; // gate order on the 3*h axis: z, r, h
167                let zt = sig(xh[p + j] + rh[p + j]);
168                let rt = sig(xh[p + h + j] + rh[p + h + j]);
169                let ht = (xh[p + 2 * h + j] + rt * rh[p + 2 * h + j]).tanh();
170                let h_ref = (1.0 - zt) * ht + zt * hprev[r * h + j];
171                assert!((got[r * h + j] - h_ref).abs() < 1e-3, "Ht mismatch at ({r},{j})");
172            }
173        }
174    }
175}