-
Notifications
You must be signed in to change notification settings - Fork 209
/
openai_gpt.rs
331 lines (302 loc) · 10.1 KB
/
openai_gpt.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
326
327
328
329
330
331
use rust_bert::openai_gpt::{
OpenAIGPTLMHeadModel, OpenAiGptConfig, OpenAiGptConfigResources, OpenAiGptMergesResources,
OpenAiGptModelResources, OpenAiGptVocabResources,
};
use rust_bert::pipelines::common::ModelType;
use rust_bert::pipelines::generation_utils::Cache;
use rust_bert::pipelines::text_generation::{TextGenerationConfig, TextGenerationModel};
use rust_bert::resources::{RemoteResource, ResourceProvider};
use rust_bert::Config;
use rust_tokenizers::tokenizer::{OpenAiGptTokenizer, Tokenizer, TruncationStrategy};
use tch::{nn, Device, Tensor};
#[test]
fn openai_gpt_lm_model() -> anyhow::Result<()> {
// Resources paths
let config_resource = Box::new(RemoteResource::from_pretrained(
OpenAiGptConfigResources::GPT,
));
let vocab_resource = Box::new(RemoteResource::from_pretrained(
OpenAiGptVocabResources::GPT,
));
let merges_resource = Box::new(RemoteResource::from_pretrained(
OpenAiGptMergesResources::GPT,
));
let weights_resource = Box::new(RemoteResource::from_pretrained(
OpenAiGptModelResources::GPT,
));
let config_path = config_resource.get_local_path()?;
let vocab_path = vocab_resource.get_local_path()?;
let merges_path = merges_resource.get_local_path()?;
let weights_path = weights_resource.get_local_path()?;
// Set-up masked LM model
let device = Device::Cpu;
let mut vs = nn::VarStore::new(device);
let tokenizer = OpenAiGptTokenizer::from_file(
vocab_path.to_str().unwrap(),
merges_path.to_str().unwrap(),
true,
)?;
let config = OpenAiGptConfig::from_file(config_path);
let openai_gpt = OpenAIGPTLMHeadModel::new(vs.root(), &config);
vs.load(weights_path)?;
// Define input
let input = ["Wondering what the next word will"];
let tokenized_input = tokenizer.encode_list(&input, 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::of_slice(&(input)))
.collect::<Vec<_>>();
let input_tensor = Tensor::stack(tokenized_input.as_slice(), 0).to(device);
// Forward pass
let model_output = openai_gpt
.forward_t(
Some(&input_tensor),
Cache::None,
None,
None,
None,
None,
None,
None,
false,
)
.unwrap();
let next_word_id = model_output
.lm_logits
.get(0)
.get(-1)
.argmax(-1, true)
.int64_value(&[0]);
let next_word = tokenizer.decode(&[next_word_id], true, true);
assert_eq!(model_output.lm_logits.size(), vec!(1, 6, 40478));
assert!(
(model_output.lm_logits.double_value(&[
0,
model_output.lm_logits.size()[1] - 1,
next_word_id
]) - (9.1056))
.abs()
< 1e-4
);
assert_eq!(next_word_id, 580i64);
assert_eq!(next_word, String::from("be"));
Ok(())
}
#[test]
fn openai_gpt_generation_greedy() -> anyhow::Result<()> {
// Resources paths
let config_resource = Box::new(RemoteResource::from_pretrained(
OpenAiGptConfigResources::GPT,
));
let vocab_resource = Box::new(RemoteResource::from_pretrained(
OpenAiGptVocabResources::GPT,
));
let merges_resource = Box::new(RemoteResource::from_pretrained(
OpenAiGptMergesResources::GPT,
));
let model_resource = Box::new(RemoteResource::from_pretrained(
OpenAiGptModelResources::GPT,
));
// Set-up model
let generate_config = TextGenerationConfig {
model_type: ModelType::OpenAiGpt,
model_resource,
config_resource,
vocab_resource,
merges_resource: Some(merges_resource),
max_length: Some(40),
do_sample: false,
num_beams: 1,
top_p: 1.0,
no_repeat_ngram_size: 1,
temperature: 1.1,
..Default::default()
};
let model = TextGenerationModel::new(generate_config)?;
let input_context = "It was an intense machine dialogue. ";
let output = model.generate(&[input_context], None);
assert_eq!(output.len(), 1);
assert_eq!(output[0], "it was an intense machine dialogue. \n \" i\'m sorry, but we have to go now! the police are on their way and they\'re going after you - or at least that\'s what my");
Ok(())
}
#[test]
fn openai_gpt_generation_beam_search() -> anyhow::Result<()> {
// Resources paths
let config_resource = Box::new(RemoteResource::from_pretrained(
OpenAiGptConfigResources::GPT,
));
let vocab_resource = Box::new(RemoteResource::from_pretrained(
OpenAiGptVocabResources::GPT,
));
let merges_resource = Box::new(RemoteResource::from_pretrained(
OpenAiGptMergesResources::GPT,
));
let model_resource = Box::new(RemoteResource::from_pretrained(
OpenAiGptModelResources::GPT,
));
// Set-up model
let generate_config = TextGenerationConfig {
model_type: ModelType::OpenAiGpt,
model_resource,
config_resource,
vocab_resource,
merges_resource: Some(merges_resource),
max_length: Some(20),
do_sample: false,
early_stopping: true,
num_beams: 5,
temperature: 1.0,
num_return_sequences: 3,
..Default::default()
};
let model = TextGenerationModel::new(generate_config)?;
let input_context = "The dog is";
let output = model.generate(&[input_context], None);
assert_eq!(output.len(), 3);
assert_eq!(
output[0],
"the dog is a good dog. \" \n \" he's a good dog, \" i agreed."
);
assert_eq!(
output[1],
"the dog is a good dog. \" \n \" he\'s a good dog. \" \n \" he"
);
assert_eq!(
output[2],
"the dog is a good dog. \" \n \" he\'s a good dog. \" \n \" i"
);
Ok(())
}
#[test]
fn openai_gpt_generation_beam_search_multiple_prompts_without_padding() -> anyhow::Result<()> {
// Resources paths
let config_resource = Box::new(RemoteResource::from_pretrained(
OpenAiGptConfigResources::GPT,
));
let vocab_resource = Box::new(RemoteResource::from_pretrained(
OpenAiGptVocabResources::GPT,
));
let merges_resource = Box::new(RemoteResource::from_pretrained(
OpenAiGptMergesResources::GPT,
));
let model_resource = Box::new(RemoteResource::from_pretrained(
OpenAiGptModelResources::GPT,
));
// Set-up model
let generate_config = TextGenerationConfig {
model_type: ModelType::OpenAiGpt,
model_resource,
config_resource,
vocab_resource,
merges_resource: Some(merges_resource),
max_length: Some(20),
do_sample: false,
early_stopping: true,
num_beams: 5,
temperature: 1.0,
num_return_sequences: 3,
..Default::default()
};
let model = TextGenerationModel::new(generate_config)?;
let input_context_1 = "The dog is";
let input_context_2 = "The cat";
let output = model.generate(&[input_context_1, input_context_2], None);
assert_eq!(output.len(), 6);
// Un-padded sequence (generation for `The dog is`) is identical to the case with a unique input
assert_eq!(
output[0],
"the dog is a good dog. \" \n \" he's a good dog, \" i agreed."
);
assert_eq!(
output[1],
"the dog is a good dog. \" \n \" he\'s a good dog. \" \n \" he"
);
assert_eq!(
output[2],
"the dog is a good dog. \" \n \" he\'s a good dog. \" \n \" i"
);
assert_eq!(
output[3],
"the cat. \" \n \" what? \" \n \" you heard me. \" \n \" i"
);
assert_eq!(
output[4],
"the cat. \" \n \" what? \" \n \" you heard me. \" \n \" no"
);
assert_eq!(
output[5],
"the cat. \" \n \" what? \" \n \" you heard me. \" \n \" oh"
);
Ok(())
}
#[test]
fn openai_gpt_generation_beam_search_multiple_prompts_with_padding() -> anyhow::Result<()> {
// Resources paths
let config_resource = Box::new(RemoteResource::from_pretrained(
OpenAiGptConfigResources::GPT,
));
let vocab_resource = Box::new(RemoteResource::from_pretrained(
OpenAiGptVocabResources::GPT,
));
let merges_resource = Box::new(RemoteResource::from_pretrained(
OpenAiGptMergesResources::GPT,
));
let model_resource = Box::new(RemoteResource::from_pretrained(
OpenAiGptModelResources::GPT,
));
// Set-up model
let generate_config = TextGenerationConfig {
model_type: ModelType::OpenAiGpt,
model_resource,
config_resource,
vocab_resource,
merges_resource: Some(merges_resource),
max_length: Some(20),
do_sample: false,
num_beams: 5,
temperature: 2.0,
num_return_sequences: 3,
..Default::default()
};
let model = TextGenerationModel::new(generate_config)?;
let input_context_1 = "The dog is";
let input_context_2 = "The cat was in";
let output = model.generate(&[input_context_1, input_context_2], None);
assert_eq!(output.len(), 6);
// Left padding impacts the generated sentences output
assert_eq!(
output[0],
"the dog is a dog. \" \n \" i don\'t know what you\'re talking about."
);
assert_eq!(
output[1],
"the dog is a dog. \" \n \" i don\'t know what you\'re talking about,"
);
assert_eq!(
output[2],
"the dog is a dog. \" \n \" i don\'t know what you\'re talking about!"
);
assert_eq!(
output[3],
"the cat was in the room with them. \n \" what\'s going on? \" i asked."
);
assert_eq!(
output[4],
"the cat was in the room with them. \n \" what\'s going on? \" she asked."
);
assert_eq!(
output[5],
"the cat was in the room with them. \n \" what\'s going on? why are you all"
);
Ok(())
}