oxidized_transformers/layers/transformer/
layer.rs

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
/// Transformer building blocks.
use candle_core::{ModuleT, Tensor};
use candle_nn::VarBuilder;
use snafu::{ResultExt, Snafu};

use crate::architectures::{BuildDecoderLayer, DecoderLayer};
use crate::architectures::{BuildEncoderLayer, EncoderLayer};
use crate::error::BoxedError;
use crate::kv_cache::LayerKeyValueCache;
use crate::layers::attention::{Attention, AttentionMask, BuildAttention, SelfAttentionConfig};
use crate::layers::build_module::BuildModule;
use crate::layers::feedforward::PointwiseFeedForwardConfig;
use crate::layers::identity::Identity;

/// Transformer layer configuration.
#[derive(Debug)]
pub struct TransformerLayerConfig {
    /// Attention residual connection layer norm.
    attn_residual_layer_norm: Box<dyn BuildModule>,

    /// Attention layer configuration.
    attention: SelfAttentionConfig,

    /// Feed-forward layer configuration.
    feedforward: PointwiseFeedForwardConfig,

    /// Feed-forward residual connection layer norm.
    ffn_residual_layer_norm: Box<dyn BuildModule>,

    /// Parallel attention dropout.
    parallel_attn_dropout: Box<dyn BuildModule>,

    /// Use parallel attention.
    use_parallel_attention: bool,
}

impl TransformerLayerConfig {
    /// Generic layer builder.
    fn build_layer(&self, vb: VarBuilder) -> Result<TransformerLayer, TransformerLayerError> {
        Ok(TransformerLayer {
            attn_residual_layer_norm: self
                .attn_residual_layer_norm
                .build(vb.push_prefix("attn_residual_layer_norm"))
                .context(CreateLayerNormSnafu)?,
            ffn: self
                .feedforward
                .build(vb.push_prefix("ffn"))
                .context(BuildPointwiseFeedForwardSnafu)?,
            ffn_residual_layer_norm: self
                .ffn_residual_layer_norm
                .build(vb.push_prefix("ffn_residual_layer_norm"))
                .context(CreateLayerNormSnafu)?,
            mha: self
                .attention
                .build(vb.push_prefix("attention"))
                .context(BuildAttentionSnafu)?,
            parallel_attention_dropout: self
                .parallel_attn_dropout
                .build(vb.push_prefix("parallel_attention_dropout"))
                .context(BuildParallelAttentionDropoutSnafu)?,
            use_parallel_attention: self.use_parallel_attention,
        })
    }

    /// Attention residual connection layer norm.
    ///
    /// Default: `Identity`
    pub fn attn_residual_layer_norm(
        mut self,
        attn_residual_layer_norm: Box<dyn BuildModule>,
    ) -> Self {
        self.attn_residual_layer_norm = attn_residual_layer_norm;
        self
    }

    /// Attention layer configuration.
    ///
    /// Default: `SelfAttentionConfig::default()`
    pub fn attention(mut self, attention: SelfAttentionConfig) -> Self {
        self.attention = attention;
        self
    }

    /// Feed-forward layer configuration.
    ///
    /// Default: `PointwiseFeedForwardConfig::default()`
    pub fn feedforward(mut self, feedforward: PointwiseFeedForwardConfig) -> Self {
        self.feedforward = feedforward;
        self
    }

    /// Feed-forward residual connection layer norm.
    ///
    /// Default: `Identity`
    pub fn ffn_residual_layer_norm(
        mut self,
        ffn_residual_layer_norm: Box<dyn BuildModule>,
    ) -> Self {
        self.ffn_residual_layer_norm = ffn_residual_layer_norm;
        self
    }

    /// Parallel attention dropout.
    ///
    /// Default: `Identity`
    pub fn parallel_attn_dropout(mut self, parallel_attn_dropout: Box<dyn BuildModule>) -> Self {
        self.parallel_attn_dropout = parallel_attn_dropout;
        self
    }

    /// Whether to use parallel attention.
    ///
    /// Default: `false`
    pub fn use_parallel_attention(mut self, use_parallel_attention: bool) -> Self {
        self.use_parallel_attention = use_parallel_attention;
        self
    }
}

impl Default for TransformerLayerConfig {
    fn default() -> Self {
        Self {
            attn_residual_layer_norm: Box::new(Identity),
            attention: SelfAttentionConfig::default(),
            feedforward: PointwiseFeedForwardConfig::default(),
            ffn_residual_layer_norm: Box::new(Identity),
            parallel_attn_dropout: Box::new(Identity),
            use_parallel_attention: false,
        }
    }
}

impl BuildDecoderLayer for TransformerLayerConfig {
    type Cache = LayerKeyValueCache;

    fn build_decoder_layer(
        &self,
        vb: VarBuilder,
    ) -> Result<Box<dyn DecoderLayer<Cache = Self::Cache>>, BoxedError> {
        Ok(Box::new(TransformerDecoderLayer {
            inner: self.build_layer(vb)?,
        }))
    }
}

impl BuildEncoderLayer for TransformerLayerConfig {
    fn build_encoder_layer(&self, vb: VarBuilder) -> Result<Box<dyn EncoderLayer>, BoxedError> {
        Ok(Box::new(TransformerEncoderLayer {
            inner: self.build_layer(vb)?,
        }))
    }
}

/// Errors for transformer layers.
#[derive(Debug, Snafu)]
pub enum TransformerLayerError {
    #[snafu(display("Cannot build attention layer"))]
    BuildAttention { source: BoxedError },

    #[snafu(display("Cannot build parallel attention dropout"))]
    BuildParallelAttentionDropout { source: BoxedError },

    #[snafu(display("Cannot build pointwise feed-forward layer"))]
    BuildPointwiseFeedForward { source: BoxedError },

    #[snafu(display("Cannot create layer norm"))]
    CreateLayerNorm { source: BoxedError },

    #[snafu(display("Cannot apply point-wise feed-forward layer"))]
    FeedForward { source: candle_core::Error },

    #[snafu(display("Cannot apply parallel attention"))]
    ParallelAttention { source: candle_core::Error },

    #[snafu(display("Cannot apply residual connection"))]
    Residual { source: candle_core::Error },

    #[snafu(display("Cannot apply self-attention"))]
    SelfAttention { source: BoxedError },
}

/// Transformer layer.
///
/// This is a generic transformer layer that is used by `DecoderLayer` and
/// `EncoderLayer` to provide specialized layers.
///
/// See [Vaswani et al. (2017)](https://arxiv.org/abs/1706.03762).
struct TransformerLayer {
    attn_residual_layer_norm: Box<dyn ModuleT>,
    ffn_residual_layer_norm: Box<dyn ModuleT>,
    mha: Box<dyn Attention>,
    parallel_attention_dropout: Box<dyn ModuleT>,
    ffn: Box<dyn ModuleT>,
    use_parallel_attention: bool,
}

impl TransformerLayer {
    /// Apply the transformer layer to the given piece hidden representations.
    ///
    /// * `input` - Hidden representations to apply the layer to.
    ///   *Shape:* `(batch_size, seq_len, width)`
    /// * `attention_mask` - Attention mask. Sequence elements for which the
    ///    corresponding mask element is set to `false` are ignored
    ///    during attention calculation.
    /// * `cache` - Key/value cache to avoid recomputing key/value representations
    ///    for tokens that were previously seen.
    /// * `positions` - Input positions. Positions are needed to look up rotary
    ///    embeddings. Normally, these positions are calculated automatically.
    ///    But if the positions deviate for some reason, they can be provided
    ///    through this argument.
    ///    *Shape:* `(batch_size, seq_len)`
    /// * `train` - Whether to train the layer.
    /// * `use_causal_mask` - Mask out succeeding sequence elements when `true`.
    ///
    /// Returns layer output and the key/value cache.
    /// *Shape:* ``(batch_size, seq_len, width)``
    #[allow(clippy::too_many_arguments)]
    fn forward(
        &self,
        input: &Tensor,
        attention_mask: &AttentionMask,
        cache: &mut LayerKeyValueCache,
        positions: Option<&Tensor>,
        train: bool,
        use_causal_mask: bool,
    ) -> Result<Tensor, TransformerLayerError> {
        let mut residual = input.clone();

        // Apply attention block.
        let attn_out = self
            .mha
            .forward_t(
                input,
                attention_mask,
                cache,
                positions,
                train,
                use_causal_mask,
            )
            .context(SelfAttentionSnafu)?;

        // Apply post-attention residual connection.
        let ffn_in = if self.use_parallel_attention {
            input
        } else {
            residual = (residual + &attn_out)
                .and_then(|xs| self.attn_residual_layer_norm.forward_t(&xs, train))
                .context(ResidualSnafu)?;
            &residual
        };

        // Apply feed-forward block.
        let ffn_out = self
            .ffn
            .forward_t(ffn_in, train)
            .context(FeedForwardSnafu)?;

        // Apply parallel attention.
        let output = if self.use_parallel_attention {
            (attn_out + ffn_out)
                .and_then(|xs| self.parallel_attention_dropout.forward_t(&xs, train))
                .context(ParallelAttentionSnafu)?
        } else {
            ffn_out
        };

        let output = (residual + output)
            .and_then(|xs| self.ffn_residual_layer_norm.forward_t(&xs, train))
            .context(ResidualSnafu)?;

        Ok(output)
    }
}

/// Transformer decoder layer.
///
/// See [Vaswani et al. (2017)](https://arxiv.org/abs/1706.03762).
pub struct TransformerDecoderLayer {
    inner: TransformerLayer,
}

impl DecoderLayer for TransformerDecoderLayer {
    type Cache = LayerKeyValueCache;

    fn forward_t(
        &self,
        input: &Tensor,
        attention_mask: &AttentionMask,
        cache: &mut Self::Cache,
        positions: Option<&Tensor>,
        train: bool,
    ) -> Result<Tensor, BoxedError> {
        Ok(self
            .inner
            .forward(input, attention_mask, cache, positions, train, true)?)
    }
}

/// Transformer encoder layer.
///
/// See [Vaswani et al. (2017)](https://arxiv.org/abs/1706.03762).
pub struct TransformerEncoderLayer {
    inner: TransformerLayer,
}

impl EncoderLayer for TransformerEncoderLayer {
    fn forward_t(
        &self,
        input: &Tensor,
        attention_mask: &AttentionMask,
        positions: Option<&Tensor>,
        train: bool,
    ) -> Result<Tensor, BoxedError> {
        self.inner
            .forward(
                input,
                attention_mask,
                &mut LayerKeyValueCache::no_cache(),
                positions,
                train,
                false,
            )
            .boxed()
    }
}