Skip to main content

nbml/layers/
sequence_pooling.rs

1use ndarray::{Array2, Array3, Axis, s};
2use serde::{Deserialize, Serialize};
3
4use crate::optim::{ToIntermediates, ToParams};
5
6// These only implement serialize for models that have already been serialized with them
7// Typically you wouldn't care to serialize any of these, since they have no learnable params.
8
9#[derive(Default, Debug, Clone)]
10pub struct SequencePoolingCache {
11    pub mask: Array2<f32>,
12    pub seq_lens: Array2<f32>,
13}
14
15#[derive(Serialize, Deserialize, Debug, Clone)]
16pub struct SequencePooling {
17    #[serde(skip)]
18    pub cache: SequencePoolingCache,
19}
20
21impl SequencePooling {
22    pub fn new() -> Self {
23        Self {
24            cache: SequencePoolingCache::default(),
25        }
26    }
27
28    pub fn forward(&mut self, x: Array3<f32>, mask: Array2<f32>, grad: bool) -> Array2<f32> {
29        let seq_lens = mask.sum_axis(Axis(1)).insert_axis(Axis(1));
30
31        if grad {
32            self.cache.mask = mask.clone();
33            self.cache.seq_lens = seq_lens.clone();
34        }
35
36        let x_sums = (&x * &mask.insert_axis(Axis(2))).sum_axis(Axis(1));
37
38        &x_sums / &seq_lens
39    }
40
41    pub fn backward(&mut self, d_loss: Array2<f32>) -> Array3<f32> {
42        let (batch_size, features) = d_loss.dim();
43        let (.., seq_len) = self.cache.mask.dim();
44
45        let d_loss_mean = &d_loss / &self.cache.seq_lens;
46        let d_loss_3d = d_loss_mean
47            .insert_axis(Axis(1))
48            .broadcast((batch_size, seq_len, features))
49            .unwrap()
50            .to_owned();
51        let d_loss_masked = &d_loss_3d * &self.cache.mask.clone().insert_axis(Axis(2));
52
53        d_loss_masked
54    }
55}
56
57impl ToParams for SequencePooling {
58    fn params(&mut self) -> Vec<crate::optim::Param> {
59        vec![]
60    }
61}
62
63impl ToIntermediates for SequencePooling {
64    fn intermediates(&mut self) -> Vec<&mut dyn crate::optim::Intermediate> {
65        vec![&mut self.cache.mask, &mut self.cache.seq_lens]
66    }
67}
68
69#[derive(Default, Debug, Clone)]
70pub struct LastTokenPoolingCache {
71    pub mask: Array2<f32>,
72}
73
74#[derive(Serialize, Deserialize, Debug, Clone)]
75pub struct LastTokenPooling {
76    #[serde(skip)]
77    cache: LastTokenPoolingCache,
78}
79
80impl LastTokenPooling {
81    pub fn new() -> Self {
82        Self {
83            cache: LastTokenPoolingCache::default(),
84        }
85    }
86
87    pub fn forward(&mut self, x: Array3<f32>, mask: Array2<f32>, grad: bool) -> Array2<f32> {
88        let (batch_size, _, features) = x.dim();
89
90        let mut out = Array2::zeros((batch_size, features));
91
92        for b in 0..batch_size {
93            let last = mask.slice(s![b, ..]).sum() as usize - 1;
94            out.slice_mut(s![b, ..]).assign(&x.slice(s![b, last, ..]));
95        }
96
97        if grad {
98            self.cache.mask = mask;
99        }
100
101        out
102    }
103
104    pub fn backward(&mut self, d_loss: Array2<f32>) -> Array3<f32> {
105        let (batch_size, seq_len) = self.cache.mask.dim();
106        let features = d_loss.dim().1;
107
108        let mut d_loss_3d = Array3::zeros((batch_size, seq_len, features));
109
110        for b in 0..batch_size {
111            let last = self.cache.mask.slice(s![b, ..]).sum() as usize - 1;
112
113            d_loss_3d
114                .slice_mut(s![b, last, ..])
115                .assign(&d_loss.slice(s![b, ..]));
116        }
117
118        d_loss_3d
119    }
120}
121
122impl ToParams for LastTokenPooling {
123    fn params(&mut self) -> Vec<crate::optim::Param> {
124        vec![]
125    }
126}
127
128impl ToIntermediates for LastTokenPooling {
129    fn intermediates(&mut self) -> Vec<&mut dyn crate::optim::Intermediate> {
130        vec![&mut self.cache.mask]
131    }
132}