Skip to main content

tract_core/ops/nn/
rms_norm.rs

1use crate::internal::*;
2use crate::ops::binary::{BinMiniOp, TypedBinOp};
3use crate::ops::element_wise::ElementWiseOp;
4use crate::ops::math::{Add, Mul, Rsqrt};
5use crate::ops::nn::{Reduce, Reducer};
6use tract_itertools::Itertools;
7
8#[derive(Clone, Debug, Hash, PartialEq, Eq)]
9pub struct RmsNorm {
10    pub axis: usize,
11    pub eps: Arc<Tensor>,
12}
13
14impl Op for RmsNorm {
15    fn name(&self) -> StaticName {
16        "RmsNorm".to_string().into()
17    }
18    fn info(&self) -> TractResult<Vec<String>> {
19        Ok(vec![format!("axis: {:?}, eps: {:?}", self.axis, self.eps)])
20    }
21    op_as_typed_op!();
22}
23
24impl EvalOp for RmsNorm {
25    op_out_of_plan!();
26
27    fn eval(&self, _ctx: &EvalContext, inputs: TVec<TValue>) -> TractResult<TVec<TValue>> {
28        let input = args_1!(inputs);
29        let in_dt = input.datum_type();
30
31        // Fast path: F32 or F16 input where the normalised axis is the last
32        // (contiguous) one. Use the fused tract_linalg::rms_norm_f32 kernel
33        // (AVX-512 when available; scalar fallback otherwise) instead of the
34        // 4-call MeanOfSquares + Add + Rsqrt + Mul composition below. ~16-18x
35        // faster on Cascade Lake AVX-512, ~equivalent on the scalar fallback
36        // since the composition is also memory-bandwidth bound.
37        if matches!(in_dt, DatumType::F32 | DatumType::F16)
38            && input.rank() > 0
39            && self.axis == input.rank() - 1
40        {
41            let eps_f32: f32 = self.eps.cast_to_scalar::<f32>()?;
42            let already_f32 = in_dt == DatumType::F32;
43            let mut buf = if already_f32 {
44                input.into_tensor()
45            } else {
46                input.cast_to::<f32>()?.into_owned()
47            };
48            let row_len = buf.shape()[self.axis];
49            if row_len > 0 {
50                let data = unsafe { buf.as_slice_mut_unchecked::<f32>() };
51                let rms_norm = tract_linalg::routines::rms_norm_f32()?;
52                let total = data.len();
53                tract_linalg::multithread::par_chunks_mut(data, row_len, total, |_, chunk| {
54                    for row in chunk.chunks_mut(row_len) {
55                        rms_norm(row, eps_f32);
56                    }
57                    Ok(())
58                })?;
59            }
60            if already_f32 {
61                return Ok(tvec![buf.into_tvalue()]);
62            }
63            return Ok(tvec![buf.cast_to_dt(in_dt)?.into_owned().into()]);
64        }
65
66        // Slow path: original 4-call composition (kept for non-contiguous axes).
67        let already_f32 = in_dt == DatumType::F32;
68        let input_f32 =
69            if already_f32 { input.into_tensor() } else { input.cast_to::<f32>()?.into_owned() };
70        // eps inherits the input dtype from the declutter pattern (F16 when the
71        // surrounding LayerNorm chain is F16). The MeanOfSquares + Add + Rsqrt
72        // + Mul chain below all runs at F32, so eps must be cast to match —
73        // otherwise the Add::eval call below panics with
74        //   "tensor is F32, accessed as F16"
75        // when input is F16.
76        let eps = self.eps.cast_to::<f32>()?.into_owned();
77        let a1 = Reducer::MeanOfSquares.reduce(&[self.axis], &input_f32)?;
78        let mut a2 = Add.eval(a1.into_tvalue(), eps.into_tvalue(), DatumType::F32)?;
79        Rsqrt {}.eval_in_place(&mut a2, None)?;
80        let a3 = Mul.eval(a2.into_tvalue(), input_f32.into_tvalue(), DatumType::F32)?;
81        if already_f32 {
82            return Ok(tvec![a3.into_tvalue()]);
83        }
84        Ok(tvec![a3.cast_to_dt(in_dt)?.into_owned().into()])
85    }
86}
87
88impl TypedOp for RmsNorm {
89    fn output_facts(&self, inputs: &[&TypedFact]) -> TractResult<TVec<TypedFact>> {
90        ensure!(self.eps.rank() == 0, "RmsNorm: eps must be a rank-0 tensor");
91        ensure!(
92            self.axis < inputs[0].rank(),
93            "RmsNorm: axis {} is out of bounds for input rank {}",
94            self.axis,
95            inputs[0].rank()
96        );
97        let dt = inputs[0].datum_type;
98        let fact = dt.fact(inputs[0].shape.clone());
99        Ok(tvec!(fact))
100    }
101
102    fn input_roi(
103        &self,
104        model: &TypedModel,
105        node: &TypedNode,
106    ) -> TractResult<Option<TVec<Option<TDim>>>> {
107        crate::optim::propagate_roi::bubble_roi(model, node)
108    }
109
110    fn axes_mapping(
111        &self,
112        inputs: &[&TypedFact],
113        _outputs: &[&TypedFact],
114    ) -> TractResult<AxesMapping> {
115        let rank = inputs[0].rank();
116        let mut letters = 'a'..;
117        let axes = (0..rank)
118            .map(|ix| {
119                Axis::new(letters.next().unwrap(), inputs.len(), 1).input(0, ix).output(0, ix)
120            })
121            .collect_vec();
122        AxesMapping::new(1, 1, axes)
123    }
124
125    fn change_axes(
126        &self,
127        model: &TypedModel,
128        node: &TypedNode,
129        _io: InOut,
130        change: &AxisOp,
131    ) -> TractResult<Option<AxisChangeConsequence>> {
132        if let Some(axis) = change.transform_axis(self.axis) {
133            let op = Some(Box::new(RmsNorm { axis, eps: self.eps.clone() }) as _);
134            Ok(Some(AxisChangeConsequence::new(model, node, op, change)))
135        } else {
136            Ok(None)
137        }
138    }
139
140    fn slice(
141        &self,
142        patch: &mut TypedModelPatch,
143        _model: &TypedModel,
144        node: &TypedNode,
145        _prefix: &str,
146        inputs: &[OutletId],
147        output_axis: usize,
148        _start: &TDim,
149        _end: &TDim,
150    ) -> TractResult<Option<TVec<OutletId>>> {
151        rule_if!(output_axis != self.axis);
152        patch.wire_node(&node.name, self.clone(), inputs).map(Some)
153    }
154
155    fn cost(&self, inputs: &[&TypedFact]) -> TractResult<TVec<(Cost, TDim)>> {
156        let dt = inputs[0].datum_type;
157        let count: TDim = inputs[0].shape.iter().product();
158        // per element: square + accumulate + mul by rsqrt ≈ 3 FMA
159        // per reduction group: 1 div (rsqrt)
160        let groups: TDim = inputs[0]
161            .shape
162            .iter()
163            .enumerate()
164            .filter(|(i, _)| *i != self.axis)
165            .map(|(_, d)| d)
166            .product();
167        Ok(tvec!((Cost::FMA(dt), count * 3), (Cost::Div(dt), groups)))
168    }
169
170    as_op!();
171}
172
173/// Search pattern => A = A * RSQRT(MEAN_OF_SQUARES(A) + EPS)
174pub fn detect_rms_norm(
175    op: &Reduce,
176    model: &TypedModel,
177    node: &TypedNode,
178) -> TractResult<Option<TypedModelPatch>> {
179    rule_if!(op.reducer == Reducer::MeanOfSquares);
180    rule_if!(op.axes.len() == 1);
181    let axis = op.axes[0];
182
183    let in_fact = model.node_input_facts(node.id)?[0];
184    let dt = in_fact.datum_type;
185
186    // Only F16 and F32 is supported.
187    rule_if!(matches!(dt, DatumType::F32 | DatumType::F16));
188
189    // Identify Add operator
190    rule_if_some!(add_succ = model.single_succ(node.id)?);
191    rule_if_some!(add_succ_op = add_succ.op_as::<TypedBinOp>());
192    rule_if!(add_succ_op.0.is::<Add>());
193
194    // Retrieve epsilon
195    let add_consts = model.collect_const_inputs(add_succ);
196    rule_if!(add_consts.len() == 1);
197    let eps = add_consts[0].val().clone();
198    rule_if!(eps.len() == 1);
199    rule_if!(eps.datum_type() == dt);
200    let eps = eps.into_tensor().into_shape(&[])?.into_arc_tensor();
201
202    // Identify Rsqrt
203    rule_if_some!(rsqrt_succ = model.single_succ(add_succ.id)?);
204    rule_if_some!(rsqrt_succ_op = rsqrt_succ.op_as::<ElementWiseOp>());
205    rule_if!(rsqrt_succ_op.0.is::<Rsqrt>());
206
207    // Identify Mul: RSQRT(...) * A
208    rule_if_some!(mul_succ = model.find_succ_bin_with_outlet::<Mul>(rsqrt_succ, &node.inputs[0]));
209
210    let mut patch = TypedModelPatch::default();
211    let rsm_input = patch.taps(model, &node.inputs)?;
212    let out =
213        patch.wire_node(format!("{}.rms_norm", node.name), RmsNorm { axis, eps }, &rsm_input)?;
214
215    patch.shunt_outside(model, mul_succ.id.into(), out[0])?;
216    Ok(Some(patch))
217}
218
219#[cfg(test)]
220mod tests {
221    use super::*;
222    use crate::ops::nn::RmsNorm;
223
224    /// Regression: the declutter pattern (`detect_rms_norm`) stores `eps` with
225    /// the input dtype (F16 when the surrounding LayerNorm chain is F16) — see
226    /// `rule_if!(eps.datum_type() == dt)` above. The eval path runs at F32, so
227    /// it must cast `self.eps` to F32 before using it. Without the cast in
228    /// `RmsNorm::eval`, this test panics with "tensor is F32, accessed as F16".
229    #[test]
230    fn eval_with_f16_eps_and_f16_input() {
231        let to_h = |x: f32| f16::from_f32(x);
232        let input = tensor1(&[to_h(1.0), to_h(2.0), to_h(3.0), to_h(4.0)]);
233        let eps = tensor0(to_h(1e-5)).into_arc_tensor();
234        let op = RmsNorm { axis: 0, eps };
235        let out = op
236            .eval(&EvalContext::out_of_plan(), tvec!(input.clone().into()))
237            .expect("eval should not panic");
238        let out = out.into_iter().next().unwrap().into_tensor();
239        assert_eq!(out.datum_type(), DatumType::F16);
240        assert_eq!(out.shape(), &[4]);
241        // Reference: rms = sqrt((1+4+9+16)/4 + eps) = sqrt(7.5 + 1e-5) ≈ 2.7386
242        // normalised: [1, 2, 3, 4] / 2.7386 ≈ [0.365, 0.730, 1.095, 1.461]
243        let got = unsafe { out.as_slice_unchecked::<f16>() };
244        let expected = [0.365_f32, 0.730, 1.095, 1.461];
245        for (i, (g, e)) in got.iter().zip(expected.iter()).enumerate() {
246            let diff = (g.to_f32() - e).abs();
247            assert!(diff < 0.01, "lane {i}: got {} expected {}", g.to_f32(), e);
248        }
249    }
250
251    /// Slow path: when the normalised axis is NOT the trailing one, the fast
252    /// path in `eval` (which dispatches to `tract_linalg::routines::rms_norm_f32`)
253    /// is skipped and the original 4-call `MeanOfSquares` + `Add` + `Rsqrt` +
254    /// `Mul` composition runs. Asserts the result is identical to a hand-
255    /// computed reference, so the slow path stays correct after the fast-path
256    /// addition.
257    #[test]
258    fn eval_with_non_trailing_axis_f32() {
259        // 2x3 input, axis=0 means we normalise across the 2 rows for each
260        // column independently:
261        //   col 0: [1, 4] → mean_sq = (1 + 16) / 2 =  8.5 → 1/√8.5
262        //   col 1: [2, 5] → mean_sq = (4 + 25) / 2 = 14.5 → 1/√14.5
263        //   col 2: [3, 6] → mean_sq = (9 + 36) / 2 = 22.5 → 1/√22.5
264        let input = tensor2(&[[1.0_f32, 2.0, 3.0], [4.0, 5.0, 6.0]]);
265        let eps = tensor0(0.0_f32).into_arc_tensor();
266        let op = RmsNorm { axis: 0, eps };
267        let out = op
268            .eval(&EvalContext::out_of_plan(), tvec!(input.into()))
269            .expect("eval should not panic");
270        let out = out.into_iter().next().unwrap().into_tensor();
271        assert_eq!(out.datum_type(), DatumType::F32);
272        assert_eq!(out.shape(), &[2, 3]);
273        let got = unsafe { out.as_slice_unchecked::<f32>() };
274        let inv = |ms: f32| ms.sqrt().recip();
275        let expected: [f32; 6] = [
276            1.0 * inv(8.5),
277            2.0 * inv(14.5),
278            3.0 * inv(22.5),
279            4.0 * inv(8.5),
280            5.0 * inv(14.5),
281            6.0 * inv(22.5),
282        ];
283        for (i, (g, e)) in got.iter().zip(expected.iter()).enumerate() {
284            let diff = (g - e).abs();
285            assert!(diff < 1e-5, "lane {i}: got {g}, want {e}, diff {diff}");
286        }
287    }
288}