-
Notifications
You must be signed in to change notification settings - Fork 215
/
deberta_v2.rs
226 lines (203 loc) · 8.16 KB
/
deberta_v2.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
use rust_bert::deberta_v2::{
DebertaV2Config, DebertaV2ConfigResources, DebertaV2ForMaskedLM, DebertaV2ForQuestionAnswering,
DebertaV2ForSequenceClassification, DebertaV2ForTokenClassification, DebertaV2VocabResources,
};
use rust_bert::resources::{RemoteResource, ResourceProvider};
use rust_bert::Config;
use rust_tokenizers::tokenizer::{DeBERTaV2Tokenizer, MultiThreadedTokenizer, TruncationStrategy};
use std::collections::HashMap;
use tch::{nn, no_grad, Device, Kind, Tensor};
extern crate anyhow;
#[test]
fn deberta_v2_masked_lm() -> anyhow::Result<()> {
// Set-up masked LM model
let config_resource = Box::new(RemoteResource::from_pretrained(
DebertaV2ConfigResources::DEBERTA_V3_BASE,
));
let config_path = config_resource.get_local_path()?;
let device = Device::Cpu;
let vs = nn::VarStore::new(device);
let mut config = DebertaV2Config::from_file(config_path);
config.output_attentions = Some(true);
config.output_hidden_states = Some(true);
let deberta_model = DebertaV2ForMaskedLM::new(vs.root(), &config);
// Generate random input
let input_tensor = Tensor::randint(42, [32, 128], (Kind::Int64, device));
let attention_mask = Tensor::ones([32, 128], (Kind::Int64, device));
let position_ids = Tensor::arange(128, (Kind::Int64, device)).unsqueeze(0);
let token_type_ids = Tensor::zeros([32, 128], (Kind::Int64, device));
// Forward pass
let model_output = no_grad(|| {
deberta_model.forward_t(
Some(&input_tensor),
Some(&attention_mask),
Some(&token_type_ids),
Some(&position_ids),
None,
false,
)
})?;
assert_eq!(model_output.logits.size(), vec!(32, 128, config.vocab_size));
assert!(model_output.all_attentions.is_some());
assert!(model_output.all_hidden_states.is_some());
assert_eq!(
config.num_hidden_layers as usize,
model_output.all_hidden_states.as_ref().unwrap().len()
);
assert_eq!(
config.num_hidden_layers as usize,
model_output.all_attentions.as_ref().unwrap().len()
);
assert_eq!(
model_output.all_attentions.as_ref().unwrap()[0].size(),
vec!(32, 12, 128, 128)
);
assert_eq!(
model_output.all_hidden_states.as_ref().unwrap()[0].size(),
vec!(32, 128, config.hidden_size)
);
Ok(())
}
#[test]
fn deberta_v2_for_sequence_classification() -> anyhow::Result<()> {
// Resources paths
let config_resource = Box::new(RemoteResource::from_pretrained(
DebertaV2ConfigResources::DEBERTA_V3_BASE,
));
let vocab_resource = Box::new(RemoteResource::from_pretrained(
DebertaV2VocabResources::DEBERTA_V3_BASE,
));
let config_path = config_resource.get_local_path()?;
let vocab_path = vocab_resource.get_local_path()?;
// Set-up model
let device = Device::cuda_if_available();
let vs = nn::VarStore::new(device);
let tokenizer =
DeBERTaV2Tokenizer::from_file(vocab_path.to_str().unwrap(), false, false, false)?;
let mut config = DebertaV2Config::from_file(config_path);
let mut dummy_label_mapping = HashMap::new();
dummy_label_mapping.insert(0, String::from("Positive"));
dummy_label_mapping.insert(1, String::from("Neutral"));
dummy_label_mapping.insert(2, String::from("Negative"));
config.id2label = Some(dummy_label_mapping);
let model = DebertaV2ForSequenceClassification::new(vs.root(), &config)?;
// Define input
let inputs = ["Where's Paris?", "In Kentucky, United States"];
let tokenized_input = tokenizer.encode_list(&inputs, 128, &TruncationStrategy::LongestFirst, 0);
let max_len = tokenized_input
.iter()
.map(|input| input.token_ids.len())
.max()
.unwrap();
let tokenized_input = tokenized_input
.iter()
.map(|input| input.token_ids.clone())
.map(|mut input| {
input.extend(vec![0; max_len - input.len()]);
input
})
.map(|input| Tensor::from_slice(&(input)))
.collect::<Vec<_>>();
let input_tensor = Tensor::stack(tokenized_input.as_slice(), 0).to(device);
// Forward pass
let model_output =
no_grad(|| model.forward_t(Some(input_tensor.as_ref()), None, None, None, None, false))?;
assert_eq!(model_output.logits.size(), &[2, 3]);
Ok(())
}
#[test]
fn deberta_v2_for_token_classification() -> anyhow::Result<()> {
// Resources paths
let config_resource = Box::new(RemoteResource::from_pretrained(
DebertaV2ConfigResources::DEBERTA_V3_BASE,
));
let vocab_resource = Box::new(RemoteResource::from_pretrained(
DebertaV2VocabResources::DEBERTA_V3_BASE,
));
let config_path = config_resource.get_local_path()?;
let vocab_path = vocab_resource.get_local_path()?;
// Set-up model
let device = Device::cuda_if_available();
let vs = nn::VarStore::new(device);
let tokenizer =
DeBERTaV2Tokenizer::from_file(vocab_path.to_str().unwrap(), false, false, false)?;
let mut config = DebertaV2Config::from_file(config_path);
let mut dummy_label_mapping = HashMap::new();
dummy_label_mapping.insert(0, String::from("O"));
dummy_label_mapping.insert(1, String::from("LOC"));
dummy_label_mapping.insert(2, String::from("PER"));
dummy_label_mapping.insert(3, String::from("ORG"));
config.id2label = Some(dummy_label_mapping);
let model = DebertaV2ForTokenClassification::new(vs.root(), &config)?;
// Define input
let inputs = ["Where's Paris?", "In Kentucky, United States"];
let tokenized_input = tokenizer.encode_list(&inputs, 128, &TruncationStrategy::LongestFirst, 0);
let max_len = tokenized_input
.iter()
.map(|input| input.token_ids.len())
.max()
.unwrap();
let tokenized_input = tokenized_input
.iter()
.map(|input| input.token_ids.clone())
.map(|mut input| {
input.extend(vec![0; max_len - input.len()]);
input
})
.map(|input| Tensor::from_slice(&(input)))
.collect::<Vec<_>>();
let input_tensor = Tensor::stack(tokenized_input.as_slice(), 0).to(device);
// Forward pass
let model_output =
no_grad(|| model.forward_t(Some(input_tensor.as_ref()), None, None, None, None, false))?;
assert_eq!(model_output.logits.size(), &[2, 7, 4]);
Ok(())
}
#[test]
fn deberta_v2_for_question_answering() -> anyhow::Result<()> {
// Resources paths
let config_resource = Box::new(RemoteResource::from_pretrained(
DebertaV2ConfigResources::DEBERTA_V3_BASE,
));
let vocab_resource = Box::new(RemoteResource::from_pretrained(
DebertaV2VocabResources::DEBERTA_V3_BASE,
));
let config_path = config_resource.get_local_path()?;
let vocab_path = vocab_resource.get_local_path()?;
// Set-up model
let device = Device::cuda_if_available();
let vs = nn::VarStore::new(device);
let tokenizer =
DeBERTaV2Tokenizer::from_file(vocab_path.to_str().unwrap(), false, false, false)?;
let config = DebertaV2Config::from_file(config_path);
let model = DebertaV2ForQuestionAnswering::new(vs.root(), &config);
// Define input
let inputs = ["Where's Paris?", "Paris is in In Kentucky, United States"];
let tokenized_input = tokenizer.encode_pair_list(
&[(inputs[0], inputs[1])],
128,
&TruncationStrategy::LongestFirst,
0,
);
let max_len = tokenized_input
.iter()
.map(|input| input.token_ids.len())
.max()
.unwrap();
let tokenized_input = tokenized_input
.iter()
.map(|input| input.token_ids.clone())
.map(|mut input| {
input.extend(vec![0; max_len - input.len()]);
input
})
.map(|input| Tensor::from_slice(&(input)))
.collect::<Vec<_>>();
let input_tensor = Tensor::stack(tokenized_input.as_slice(), 0).to(device);
// Forward pass
let model_output =
no_grad(|| model.forward_t(Some(input_tensor.as_ref()), None, None, None, None, false))?;
assert_eq!(model_output.start_logits.size(), &[1, 16]);
assert_eq!(model_output.end_logits.size(), &[1, 16]);
Ok(())
}