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
use std::borrow::Borrow;
use syntaxdot_tch_ext::PathExt;
use tch::nn::Init;
use tch::{Kind, Tensor};
use crate::cow::CowTensor;
use crate::layers::{Dropout, Embedding, LayerNorm};
use crate::models::bert::config::BertConfig;
use crate::module::{FallibleModule, FallibleModuleT};
use crate::TransformerError;
#[derive(Debug)]
pub struct BertEmbeddings {
position_embeddings: Embedding,
token_type_embeddings: Embedding,
word_embeddings: Embedding,
layer_norm: LayerNorm,
dropout: Dropout,
}
impl BertEmbeddings {
pub fn new<'a>(
vs: impl Borrow<PathExt<'a>>,
config: &BertConfig,
) -> Result<Self, TransformerError> {
let vs = vs.borrow();
let normal_init = Init::Randn {
mean: 0.,
stdev: config.initializer_range,
};
let word_embeddings = Embedding::new(
vs / "word_embeddings",
"embeddings",
config.vocab_size,
config.hidden_size,
normal_init,
)?;
let position_embeddings = Embedding::new(
vs / "position_embeddings",
"embeddings",
config.max_position_embeddings,
config.hidden_size,
normal_init,
)?;
let token_type_embeddings = Embedding::new(
vs / "token_type_embeddings",
"embeddings",
config.type_vocab_size,
config.hidden_size,
normal_init,
)?;
let layer_norm = LayerNorm::new(
vs / "layer_norm",
vec![config.hidden_size],
config.layer_norm_eps,
true,
);
let dropout = Dropout::new(config.hidden_dropout_prob);
Ok(BertEmbeddings {
position_embeddings,
token_type_embeddings,
word_embeddings,
layer_norm,
dropout,
})
}
pub fn forward(
&self,
input_ids: &Tensor,
token_type_ids: Option<&Tensor>,
position_ids: Option<&Tensor>,
train: bool,
) -> Result<Tensor, TransformerError> {
let input_shape = input_ids.size();
let seq_length = input_shape[1];
let device = input_ids.device();
let position_ids = match position_ids {
Some(position_ids) => CowTensor::Borrowed(position_ids),
None => CowTensor::Owned(
Tensor::f_arange(seq_length, (Kind::Int64, device))?
.f_unsqueeze(0)?
.f_expand(&input_shape, false)?,
),
};
let token_type_ids = match token_type_ids {
Some(token_type_ids) => CowTensor::Borrowed(token_type_ids),
None => CowTensor::Owned(Tensor::f_zeros(&input_shape, (Kind::Int64, device))?),
};
let input_embeddings = self.word_embeddings.forward(input_ids)?;
let position_embeddings = self.position_embeddings.forward(&*position_ids)?;
let token_type_embeddings = self.token_type_embeddings.forward(&*token_type_ids)?;
let embeddings = input_embeddings
.f_add(&position_embeddings)?
.f_add(&token_type_embeddings)?;
let embeddings = self.layer_norm.forward(&embeddings)?;
self.dropout.forward_t(&embeddings, train)
}
}
impl FallibleModuleT for BertEmbeddings {
type Error = TransformerError;
fn forward_t(&self, input: &Tensor, train: bool) -> Result<Tensor, Self::Error> {
self.forward(input, None, None, train)
}
}
#[cfg(feature = "model-tests")]
#[cfg(test)]
mod tests {
use std::collections::BTreeSet;
use std::convert::TryInto;
use approx::assert_abs_diff_eq;
use maplit::btreeset;
use ndarray::{array, ArrayD};
use syntaxdot_tch_ext::RootExt;
use tch::nn::VarStore;
use tch::{Device, Kind, Tensor};
use crate::activations::Activation;
use crate::models::bert::{BertConfig, BertEmbeddings};
use crate::module::FallibleModuleT;
const BERT_BASE_GERMAN_CASED: &str = env!("BERT_BASE_GERMAN_CASED");
fn german_bert_config() -> BertConfig {
BertConfig {
attention_probs_dropout_prob: 0.1,
hidden_act: Activation::Gelu,
hidden_dropout_prob: 0.1,
hidden_size: 768,
initializer_range: 0.02,
intermediate_size: 3072,
layer_norm_eps: 1e-12,
max_position_embeddings: 512,
num_attention_heads: 12,
num_hidden_layers: 12,
type_vocab_size: 2,
vocab_size: 30000,
}
}
fn varstore_variables(vs: &VarStore) -> BTreeSet<String> {
vs.variables()
.into_iter()
.map(|(k, _)| k)
.collect::<BTreeSet<_>>()
}
#[test]
fn bert_embeddings() {
let config = german_bert_config();
let mut vs = VarStore::new(Device::Cpu);
let root = vs.root_ext(|_| 0);
let embeddings = BertEmbeddings::new(root.sub("embeddings"), &config).unwrap();
vs.load(BERT_BASE_GERMAN_CASED).unwrap();
let pieces = Tensor::of_slice(&[133i64, 1937, 14010, 30, 32, 26939, 26962, 12558, 2739, 2])
.reshape(&[1, 10]);
let summed_embeddings = embeddings
.forward_t(&pieces, false)
.unwrap()
.sum_dim_intlist(&[-1], false, Kind::Float);
let sums: ArrayD<f32> = (&summed_embeddings).try_into().unwrap();
assert_abs_diff_eq!(
sums,
(array![[
-8.0342, -7.3383, -10.1286, 7.7298, 2.3506, -2.3831, -0.5961, -4.6270, -6.5415,
2.1995
]])
.into_dyn(),
epsilon = 1e-4
);
}
#[test]
fn bert_embeddings_names() {
let config = german_bert_config();
let vs = VarStore::new(Device::Cpu);
let _ = BertEmbeddings::new(vs.root_ext(|_| 0), &config);
let variables = varstore_variables(&vs);
assert_eq!(
variables,
btreeset![
"layer_norm.bias".to_string(),
"layer_norm.weight".to_string(),
"position_embeddings.embeddings".to_string(),
"token_type_embeddings.embeddings".to_string(),
"word_embeddings.embeddings".to_string()
]
);
}
}