Skip to main content

ruxla_nn/
layers.rs

1//! Layers with the computations of Flax's (`flax.linen`), so that weights
2//! trained in JAX give the same results and the traced IR has the form of
3//! Flax's jaxpr.
4
5use ruxla_core::lax::{ConvOptions, Padding};
6use ruxla_core::{Array, Backend, Float, Native, Scalar, Tree, jnp, lax};
7
8pub use ruxla_core::jnp::tanh;
9use ruxla_ir::{ConvDims, DotDims, Value};
10
11use crate::weights::{Weights, WeightsError};
12
13/// A fully connected layer, `x @ kernel + bias` (`flax.linen.Dense`).
14///
15/// # Examples
16///
17/// ```
18/// use ruxla_core::{Array, Native};
19/// use ruxla_nn::Dense;
20///
21/// let layer = Dense::<Native> {
22///     kernel: Array::from_vec(vec![1.0, 2.0, 3.0, 4.0, 5.0, 6.0], [3, 2]),
23///     bias: Array::from_vec(vec![0.5, -0.5], [2]),
24/// };
25/// let y = layer.apply(&Array::from_vec(vec![1.0, 0.0, 1.0], [3]));
26/// assert_eq!(y.to_vec(), [6.5, 7.5]);
27/// ```
28#[derive(Clone, Debug, Tree)]
29pub struct Dense<B: Backend, T: Float = f32> {
30    /// `[in, out]`.
31    pub kernel: Array<B, T>,
32    /// `[out]`.
33    pub bias: Array<B, T>,
34}
35
36impl<B: Backend, T: Float> Dense<B, T> {
37    /// Applies the layer to the last dimension of `x`.
38    ///
39    /// # Panics
40    ///
41    /// Panics if the last dimension of `x` is not the input size.
42    #[track_caller]
43    pub fn apply(&self, x: &Array<B, T>) -> Array<B, T> {
44        let n = x.ndim();
45        assert!(n >= 1, "Dense needs an input of rank 1 or more");
46        let dims = DotDims {
47            lhs_contracting: vec![n - 1],
48            rhs_contracting: vec![0],
49            ..DotDims::default()
50        };
51        let y = lax::dot_general(x, &self.kernel, &dims);
52        // `y + reshape(bias, (1,) * (ndim - 1) + (-1,))`, as Flax computes it
53        // (the reshape is left out for rank 1, as `jnp.reshape` does).
54        if n == 1 {
55            return y + &self.bias;
56        }
57        let mut shape = vec![1; n - 1];
58        shape.extend(self.bias.shape().iter().copied());
59        y + self.bias.reshape(shape)
60    }
61
62    /// The number of inputs.
63    pub fn in_features(&self) -> usize {
64        self.kernel.shape()[0]
65    }
66
67    /// The number of outputs.
68    pub fn out_features(&self) -> usize {
69        self.kernel.shape()[1]
70    }
71}
72
73impl<T: Float> Dense<Native, T> {
74    /// Loads `{prefix}/kernel` (`[in, out]`) and `{prefix}/bias` (`[out]`),
75    /// such as the weights of `params/Dense_0` of a Flax model.
76    ///
77    /// # Errors
78    ///
79    /// Returns an error if a weight is missing or has another type, or if
80    /// the shapes do not fit together.
81    pub fn load(weights: &Weights, prefix: &str) -> Result<Self, WeightsError> {
82        let kernel_name = format!("{prefix}/kernel");
83        let k = weights.get(&kernel_name)?;
84        let dims = k.shape().dims().to_vec();
85        let [n_in, n_out] = dims[..] else {
86            return Err(WeightsError::Mismatch {
87                name: kernel_name,
88                actual: k.aval().to_string(),
89                expected: String::from("a matrix"),
90            });
91        };
92        Ok(Self {
93            kernel: weights.array(&kernel_name, &[n_in, n_out])?,
94            bias: weights.array(&format!("{prefix}/bias"), &[n_out])?,
95        })
96    }
97}
98
99/// A scalar of a float type from an `f64` (as JAX converts Python floats).
100fn float<B: Backend, T: Float>(v: f64) -> Scalar<B, T> {
101    Scalar::new(T::from_value(Value::Float(v)))
102}
103
104/// A convolution of channels-last inputs with an `HWIO` kernel, and a bias
105/// (`flax.linen.Conv`).
106///
107/// The input has dimensions `(*batch, spatial..., features)`: one batch
108/// dimension is used as it is, several are flattened into one and restored,
109/// and none is allowed (a batch of one is added and removed), as in Flax.
110/// The configuration ([`Conv::strides`], ...) is not part of the weights.
111///
112/// # Examples
113///
114/// ```
115/// use ruxla_core::lax::Padding;
116/// use ruxla_core::{Array, Native};
117/// use ruxla_nn::Conv;
118///
119/// // One input and one output feature, a kernel of width 2.
120/// let conv = Conv::<Native>::new(Array::from_vec(vec![1.0, 10.0], [2, 1, 1]), None)
121///     .padding(Padding::Valid);
122/// let y = conv.apply(&Array::from_vec(vec![1.0, 2.0, 3.0], [3, 1]));
123/// assert_eq!(y.to_vec(), [21.0, 32.0]);
124/// ```
125#[derive(Clone, Debug, Tree)]
126pub struct Conv<B: Backend, T: Float = f32> {
127    /// `[*kernel_size, in_features / feature_group_count, features]`.
128    pub kernel: Array<B, T>,
129    /// `[features]`, if the layer has a bias (`use_bias`).
130    pub bias: Option<Array<B, T>>,
131    /// The step between windows in each spatial dimension.
132    #[tree(static)]
133    pub strides: Vec<usize>,
134    /// The padding (`'SAME'` by default, as in Flax).
135    #[tree(static)]
136    pub padding: Padding,
137    /// The dilation of the input in each spatial dimension.
138    #[tree(static)]
139    pub input_dilation: Vec<usize>,
140    /// The dilation of the kernel in each spatial dimension.
141    #[tree(static)]
142    pub kernel_dilation: Vec<usize>,
143    /// The number of groups of features.
144    #[tree(static)]
145    pub feature_group_count: usize,
146}
147
148impl<B: Backend, T: Float> Conv<B, T> {
149    /// A layer with Flax's defaults: unit strides and dilations, `'SAME'`
150    /// padding, and one group.
151    ///
152    /// # Panics
153    ///
154    /// Panics if the kernel has rank less than 3.
155    #[track_caller]
156    pub fn new(kernel: Array<B, T>, bias: Option<Array<B, T>>) -> Self {
157        let rank = kernel.ndim();
158        assert!(
159            rank >= 3,
160            "a Conv kernel has the kernel size, the input features, and the features"
161        );
162        let n = rank - 2;
163        Self {
164            kernel,
165            bias,
166            strides: vec![1; n],
167            padding: Padding::Same,
168            input_dilation: vec![1; n],
169            kernel_dilation: vec![1; n],
170            feature_group_count: 1,
171        }
172    }
173
174    /// Sets the strides.
175    #[must_use]
176    pub fn strides(mut self, strides: &[usize]) -> Self {
177        self.strides = strides.to_vec();
178        self
179    }
180
181    /// Sets the padding.
182    #[must_use]
183    pub fn padding(mut self, padding: impl Into<Padding>) -> Self {
184        self.padding = padding.into();
185        self
186    }
187
188    /// Sets the dilation of the input.
189    #[must_use]
190    pub fn input_dilation(mut self, dilation: &[usize]) -> Self {
191        self.input_dilation = dilation.to_vec();
192        self
193    }
194
195    /// Sets the dilation of the kernel.
196    #[must_use]
197    pub fn kernel_dilation(mut self, dilation: &[usize]) -> Self {
198        self.kernel_dilation = dilation.to_vec();
199        self
200    }
201
202    /// Sets the number of feature groups.
203    #[must_use]
204    pub fn feature_group_count(mut self, groups: usize) -> Self {
205        self.feature_group_count = groups;
206        self
207    }
208
209    /// The number of outputs.
210    pub fn features(&self) -> usize {
211        let shape = self.kernel.shape();
212        shape[shape.rank() - 1]
213    }
214
215    /// Applies the layer.
216    ///
217    /// # Panics
218    ///
219    /// Panics if the input does not fit the kernel.
220    #[track_caller]
221    pub fn apply(&self, x: &Array<B, T>) -> Array<B, T> {
222        let n = self.kernel.ndim() - 2;
223        let shape = x.shape();
224        assert!(
225            shape.rank() > n,
226            "Conv needs an input with {n} spatial dimensions and features"
227        );
228        let num_batch = shape.rank() - (n + 1);
229        let batch_shape = shape.dims()[..num_batch].to_vec();
230        let mut x = x.clone();
231        if num_batch != 1 {
232            let mut flat = vec![batch_shape.iter().product()];
233            flat.extend_from_slice(&shape.dims()[num_batch..]);
234            x = x.reshape(flat);
235        }
236        // Flax's `_conv_dimension_numbers`: `(N, C, spatial)` of a
237        // channels-last input, and `(O, I, spatial)` of an `HWIO` kernel.
238        let rank = n + 2;
239        let mut lhs_spec = vec![0, rank - 1];
240        lhs_spec.extend(1..rank - 1);
241        let mut rhs_spec = vec![rank - 1, rank - 2];
242        rhs_spec.extend(0..rank - 2);
243        let options = ConvOptions {
244            lhs_dilation: Some(self.input_dilation.clone()),
245            rhs_dilation: Some(self.kernel_dilation.clone()),
246            dimension_numbers: Some(ConvDims {
247                lhs_spec: lhs_spec.clone(),
248                rhs_spec,
249                out_spec: lhs_spec,
250            }),
251            feature_group_count: self.feature_group_count,
252            ..ConvOptions::default()
253        };
254        let mut y = lax::conv_general_dilated(
255            &x,
256            &self.kernel,
257            &self.strides,
258            self.padding.clone(),
259            &options,
260        );
261        if let Some(bias) = &self.bias {
262            let mut b_shape = vec![1; rank - 1];
263            b_shape.extend(bias.shape().iter().copied());
264            y = y + bias.reshape(b_shape);
265        }
266        if num_batch != 1 {
267            let mut out = batch_shape;
268            out.extend_from_slice(&y.shape().dims()[1..]);
269            y = y.reshape(out);
270        }
271        y
272    }
273}
274
275impl<T: Float> Conv<Native, T> {
276    /// Loads `{prefix}/kernel` and, if there is one, `{prefix}/bias`, such
277    /// as the weights of `params/Conv_0` of a Flax model, with Flax's
278    /// default configuration (see [`Conv::new`]; set the rest with
279    /// [`Conv::strides`], ...).
280    ///
281    /// # Errors
282    ///
283    /// Returns an error if the kernel is missing or a weight has another
284    /// type, or if the shapes do not fit together.
285    pub fn load(weights: &Weights, prefix: &str) -> Result<Self, WeightsError> {
286        let kernel_name = format!("{prefix}/kernel");
287        let k = weights.get(&kernel_name)?;
288        let dims = k.shape().dims().to_vec();
289        if dims.len() < 3 {
290            return Err(WeightsError::Mismatch {
291                name: kernel_name,
292                actual: k.aval().to_string(),
293                expected: String::from("a kernel of rank 3 or more"),
294            });
295        }
296        let kernel = weights.array(&kernel_name, &dims)?;
297        let bias_name = format!("{prefix}/bias");
298        let bias = if weights.contains(&bias_name) {
299            Some(weights.array(&bias_name, &dims[dims.len() - 1..])?)
300        } else {
301            None
302        };
303        Ok(Self::new(kernel, bias))
304    }
305}
306
307/// Flax's `pool`: a windowed reduction over the spatial dimensions of an
308/// input `(*batch, spatial..., features)` (or without a batch dimension).
309#[track_caller]
310fn pool<B: Backend, T: Float>(
311    x: &Array<B, T>,
312    op: lax::ReduceOp,
313    window_shape: &[usize],
314    strides: Option<&[usize]>,
315    padding: &Padding,
316) -> Array<B, T> {
317    let n = window_shape.len();
318    let rank = x.ndim();
319    assert!(
320        rank > n,
321        "pooling needs an input with {n} spatial dimensions and features"
322    );
323    let num_batch = rank - (n + 1);
324    let ones = vec![1; n];
325    let strides = strides.unwrap_or(&ones);
326    assert_eq!(strides.len(), n, "one stride per window dimension");
327    let mut full_strides = vec![1; num_batch];
328    full_strides.extend_from_slice(strides);
329    full_strides.push(1);
330    let mut dims = vec![1; num_batch];
331    dims.extend_from_slice(window_shape);
332    dims.push(1);
333    let mut x = x.clone();
334    let single = num_batch == 0;
335    if single {
336        x = jnp::expand_dims(&x, 0);
337        full_strides.insert(0, 1);
338        dims.insert(0, 1);
339    }
340    let padding = match padding {
341        Padding::Explicit(pads) => {
342            assert_eq!(pads.len(), n, "one (low, high) pair per window dimension");
343            let mut full = vec![(0, 0); x.ndim() - n - 1];
344            full.extend_from_slice(pads);
345            full.push((0, 0));
346            Padding::Explicit(full)
347        }
348        p => p.clone(),
349    };
350    let y = lax::reduce_window(&x, op, &dims, &full_strides, padding, None, None);
351    if single {
352        let shape = y.shape().dims()[1..].to_vec();
353        return y.reshape(shape);
354    }
355    y
356}
357
358/// The maximum over windows of the spatial dimensions of an input
359/// `(*batch, spatial..., features)` (`flax.linen.max_pool`; strides of 1
360/// for `None`).
361///
362/// # Examples
363///
364/// ```
365/// use ruxla_core::lax::Padding;
366/// use ruxla_core::{Array, Native};
367///
368/// let x = Array::<Native, f32>::from_vec(vec![1.0, 5.0, 2.0, 4.0], [1, 4, 1]);
369/// let y = ruxla_nn::max_pool(&x, &[2], Some(&[2]), Padding::Valid);
370/// assert_eq!(y.to_vec(), [5.0, 4.0]);
371/// ```
372///
373/// # Panics
374///
375/// Panics if the window does not fit the input.
376#[track_caller]
377pub fn max_pool<B: Backend, T: Float>(
378    x: &Array<B, T>,
379    window_shape: &[usize],
380    strides: Option<&[usize]>,
381    padding: impl Into<Padding>,
382) -> Array<B, T> {
383    pool(
384        x,
385        lax::ReduceOp::Max,
386        window_shape,
387        strides,
388        &padding.into(),
389    )
390}
391
392/// The minimum over windows (`flax.linen.min_pool`); see [`max_pool`].
393///
394/// # Panics
395///
396/// Panics if the window does not fit the input.
397#[track_caller]
398pub fn min_pool<B: Backend, T: Float>(
399    x: &Array<B, T>,
400    window_shape: &[usize],
401    strides: Option<&[usize]>,
402    padding: impl Into<Padding>,
403) -> Array<B, T> {
404    pool(
405        x,
406        lax::ReduceOp::Min,
407        window_shape,
408        strides,
409        &padding.into(),
410    )
411}
412
413/// The average over windows of the spatial dimensions of an input
414/// `(*batch, spatial..., features)` (`flax.linen.avg_pool`). With
415/// `count_include_pad`, padding counts as zeros; otherwise each window is
416/// divided by the number of elements it covers.
417///
418/// # Examples
419///
420/// ```
421/// use ruxla_core::lax::Padding;
422/// use ruxla_core::{Array, Native};
423///
424/// let x = Array::<Native, f32>::from_vec(vec![1.0, 3.0, 5.0], [1, 3, 1]);
425/// let y = ruxla_nn::avg_pool(&x, &[2], None, Padding::Same, false);
426/// assert_eq!(y.to_vec(), [2.0, 4.0, 5.0]);
427/// let y = ruxla_nn::avg_pool(&x, &[2], None, Padding::Same, true);
428/// assert_eq!(y.to_vec(), [2.0, 4.0, 2.5]);
429/// ```
430///
431/// # Panics
432///
433/// Panics if the window does not fit the input.
434#[track_caller]
435pub fn avg_pool<B: Backend, T: Float>(
436    x: &Array<B, T>,
437    window_shape: &[usize],
438    strides: Option<&[usize]>,
439    padding: impl Into<Padding>,
440    count_include_pad: bool,
441) -> Array<B, T> {
442    let padding = padding.into();
443    let y = pool(x, lax::ReduceOp::Sum, window_shape, strides, &padding);
444    if count_include_pad {
445        let n: usize = window_shape.iter().product();
446        return y / float::<B, T>(n as f64);
447    }
448    // The number of elements of each window, from an array of ones with
449    // one feature (and one example, if batched).
450    let shape = x.shape();
451    let mut div_shape = shape.dims()[..shape.rank() - 1].to_vec();
452    div_shape.push(1);
453    if div_shape.len() - 2 == window_shape.len() {
454        div_shape[0] = 1;
455    }
456    let ones = jnp::ones::<B, T>(div_shape);
457    y / pool(&ones, lax::ReduceOp::Sum, window_shape, strides, &padding)
458}
459
460/// Layer normalization over the last dimension, with a learned scale and
461/// bias (`flax.linen.LayerNorm`).
462///
463/// The mean and the variance are computed as Flax's `_compute_stats` does:
464/// by default (`use_fast_variance`) as `E[x^2] - E[x]^2`, clipped at zero;
465/// otherwise as `E[(x - E[x])^2]`. Then `y = (x - mean) * (rsqrt(var +
466/// epsilon) * scale) + bias`, as in Flax's `_normalize`. Statistics are
467/// computed in the input type (Flax computes them in `f32` for 16-bit
468/// inputs).
469///
470/// # Examples
471///
472/// ```
473/// use ruxla_core::{Array, Native};
474/// use ruxla_nn::LayerNorm;
475///
476/// let ln = LayerNorm::<Native>::new(None, None);
477/// let y = ln.apply(&Array::from_vec(vec![1.0, 3.0], [2])).to_vec();
478/// assert!((y[0] + 1.0).abs() < 1e-5 && (y[1] - 1.0).abs() < 1e-5);
479/// ```
480#[derive(Clone, Debug, Tree)]
481pub struct LayerNorm<B: Backend, T: Float = f32> {
482    /// `[features]`, if the layer has a scale (`use_scale`).
483    pub scale: Option<Array<B, T>>,
484    /// `[features]`, if the layer has a bias (`use_bias`).
485    pub bias: Option<Array<B, T>>,
486    /// Added to the variance (`1e-6` by default, as in Flax).
487    #[tree(static)]
488    pub epsilon: f64,
489    /// Whether the variance is computed as `E[x^2] - E[x]^2` (Flax's
490    /// default).
491    #[tree(static)]
492    pub use_fast_variance: bool,
493}
494
495impl<B: Backend, T: Float> LayerNorm<B, T> {
496    /// A layer with Flax's defaults (`epsilon = 1e-6`, fast variance).
497    pub fn new(scale: Option<Array<B, T>>, bias: Option<Array<B, T>>) -> Self {
498        Self {
499            scale,
500            bias,
501            epsilon: 1e-6,
502            use_fast_variance: true,
503        }
504    }
505
506    /// Sets `epsilon`.
507    #[must_use]
508    pub fn epsilon(mut self, epsilon: f64) -> Self {
509        self.epsilon = epsilon;
510        self
511    }
512
513    /// Sets whether the variance is computed as `E[x^2] - E[x]^2`.
514    #[must_use]
515    pub fn use_fast_variance(mut self, fast: bool) -> Self {
516        self.use_fast_variance = fast;
517        self
518    }
519
520    /// Normalizes the last dimension of `x`.
521    ///
522    /// # Panics
523    ///
524    /// Panics if `x` is a scalar or its last dimension does not fit the
525    /// scale or the bias.
526    #[track_caller]
527    pub fn apply(&self, x: &Array<B, T>) -> Array<B, T> {
528        let rank = x.ndim();
529        assert!(rank >= 1, "LayerNorm needs an input of rank 1 or more");
530        let axis = rank - 1;
531        let last = [axis as i64];
532        // `_compute_stats`.
533        let mu = jnp::mean(x, last);
534        let var = if self.use_fast_variance {
535            let mu2 = jnp::mean(x.square(), last);
536            jnp::maximum(float::<B, T>(0.0), mu2 - mu.square())
537        } else {
538            let d = x - jnp::expand_dims(&mu, axis as i64);
539            jnp::mean(d.square(), last)
540        };
541        // `_normalize`.
542        let mean = jnp::expand_dims(&mu, axis as i64);
543        let var = jnp::expand_dims(&var, axis as i64);
544        let mut feature_shape = vec![1; rank];
545        feature_shape[axis] = x.shape()[axis];
546        let y = x - mean;
547        let mut mul = lax::rsqrt(&(var + float::<B, T>(self.epsilon)));
548        if let Some(scale) = &self.scale {
549            mul = mul * scale.reshape(feature_shape.clone());
550        }
551        let mut y = y * mul;
552        if let Some(bias) = &self.bias {
553            y = y + bias.reshape(feature_shape);
554        }
555        y
556    }
557}
558
559impl<T: Float> LayerNorm<Native, T> {
560    /// Loads `{prefix}/scale` and `{prefix}/bias`, each if there is one,
561    /// such as the weights of `params/LayerNorm_0` of a Flax model, with
562    /// Flax's default configuration (see [`LayerNorm::new`]).
563    ///
564    /// # Errors
565    ///
566    /// Returns an error if a weight has another type or is not a vector.
567    pub fn load(weights: &Weights, prefix: &str) -> Result<Self, WeightsError> {
568        let vector = |name: String| -> Result<Option<Array<Native, T>>, WeightsError> {
569            if !weights.contains(&name) {
570                return Ok(None);
571            }
572            let h = weights.get(&name)?;
573            match h.shape().dims() {
574                &[n] => Ok(Some(weights.array(&name, &[n])?)),
575                _ => Err(WeightsError::Mismatch {
576                    name,
577                    actual: h.aval().to_string(),
578                    expected: String::from("a vector"),
579                }),
580            }
581        };
582        let scale = vector(format!("{prefix}/scale"))?;
583        let bias = vector(format!("{prefix}/bias"))?;
584        Ok(Self::new(scale, bias))
585    }
586}
587
588/// `max(x, 0)` (`flax.linen.relu`, `jax.nn.relu`).
589pub fn relu<B: Backend, T: Float>(x: &Array<B, T>) -> Array<B, T> {
590    jnp::maximum(x, T::default())
591}
592
593#[cfg(test)]
594mod tests {
595    use super::*;
596    use ruxla_core::{Trace, make_ir};
597
598    /// The traced layer has the equations of Flax's `Dense`: `dot_general`
599    /// and `add`, with a reshape of the bias for batched inputs.
600    #[test]
601    fn traces_like_flax() {
602        let layer = Dense::<Native> {
603            kernel: Array::from_vec(vec![0.0; 6], [3, 2]),
604            bias: Array::from_vec(vec![0.0; 2], [2]),
605        };
606        let prims = |x: Array<Native, f32>| {
607            let ir = make_ir(
608                |(l, x): (Dense<Trace>, Array<Trace, f32>)| l.apply(&x),
609                &(layer.clone(), x),
610            );
611            ir.eqns.iter().map(|e| e.prim.name()).collect::<Vec<_>>()
612        };
613        assert_eq!(
614            prims(Array::from_vec(vec![0.0; 3], [3])),
615            ["dot_general", "add"]
616        );
617        assert_eq!(
618            prims(Array::from_vec(vec![0.0; 12], [4, 3])),
619            ["dot_general", "reshape", "broadcast_in_dim", "add"]
620        );
621        let relu_ir = make_ir(
622            |x: Array<Trace, f32>| relu(&x),
623            &Array::<Native, f32>::from_vec(vec![0.0; 2], [2]),
624        );
625        assert_eq!(relu_ir.eqns.last().unwrap().prim.name(), "max");
626    }
627
628    /// `Conv` traces like Flax's (a convolution and the bias), and pooling
629    /// like `reduce_window`.
630    #[test]
631    fn conv_and_pooling_trace_like_flax() {
632        let conv = Conv::<Native>::new(
633            Array::from_vec(vec![0.0; 18], [3, 3, 2, 1]),
634            Some(Array::from_vec(vec![0.0], [1])),
635        );
636        let x = Array::<Native, f32>::from_vec(vec![0.0; 32], [1, 4, 4, 2]);
637        let ir = make_ir(
638            |(l, x): (Conv<Trace>, Array<Trace, f32>)| {
639                max_pool(&l.apply(&x), &[2, 2], Some(&[2, 2]), Padding::Valid)
640            },
641            &(conv, x),
642        );
643        let prims: Vec<&str> = ir.eqns.iter().map(|e| e.prim.name()).collect();
644        assert_eq!(
645            prims,
646            [
647                "conv_general_dilated",
648                "reshape",
649                "broadcast_in_dim",
650                "add",
651                "reduce_window_max"
652            ]
653        );
654    }
655}