BartModel forward pass validated

This commit is contained in:
Guillaume B 2020-04-02 14:48:28 +02:00
parent 642874b22b
commit fe529b2fec
4 changed files with 72 additions and 70 deletions

View File

@ -14,8 +14,8 @@ extern crate failure;
extern crate dirs;
use std::path::PathBuf;
use tch::{Device, nn};
use rust_tokenizers::RobertaTokenizer;
use tch::{Device, nn, Tensor, no_grad};
use rust_tokenizers::{RobertaTokenizer, TruncationStrategy, Tokenizer};
use failure::err_msg;
use rust_bert::bart::BartConfig;
use rust_bert::Config;
@ -40,67 +40,59 @@ fn main() -> failure::Fallible<()> {
}
// Set-up masked LM model
let device = Device::Cpu;
let device = Device::cuda_if_available();
let mut vs = nn::VarStore::new(device);
let _tokenizer = RobertaTokenizer::from_file(vocab_path.to_str().unwrap(), merges_path.to_str().unwrap(), false);
let tokenizer = RobertaTokenizer::from_file(vocab_path.to_str().unwrap(), merges_path.to_str().unwrap(), false);
let config = BartConfig::from_file(config_path);
let bart_model = BartModel::new(&vs.root(), &config, false);
let mut bart_model = BartModel::new(&vs.root(), &config, false);
vs.load(weights_path)?;
//
//// Define input
// let input = ["New York (CNN)When Liana Barrientos was 23 years old, she got married in Westchester County, New York.
// A year later, she got married again in Westchester County, but to a different man and without divorcing her first husband.
// Only 18 days after that marriage, she got hitched yet again. Then, Barrientos declared \"I do\" five more times, sometimes only within two weeks of each other. \
// In 2010, she married once more, this time in the Bronx. In an application for a marriage license, she stated it was her \"first and only\" marriage. \
// Barrientos, now 39, is facing two criminal counts of \"offering a false instrument for filing in the first degree,\" referring to her false statements on the
// 2010 marriage license application, according to court documents.
// Prosecutors said the marriages were part of an immigration scam.
// On Friday, she pleaded not guilty at State Supreme Court in the Bronx, according to her attorney, Christopher Wright, who declined to comment further.
// After leaving court, Barrientos was arrested and charged with theft of service and criminal trespass for allegedly sneaking into the New York subway through an emergency exit, said Detective
// Annette Markowski, a police spokeswoman. In total, Barrientos has been married 10 times, with nine of her marriages occurring between 1999 and 2002.
// All occurred either in Westchester County, Long Island, New Jersey or the Bronx. She is believed to still be married to four men, and at one time, she was married to eight men at once, prosecutors say.
// Prosecutors said the immigration scam involved some of her husbands, who filed for permanent residence status shortly after the marriages.
// Any divorces happened only after such filings were approved. It was unclear whether any of the men will be prosecuted.
// The case was referred to the Bronx District Attorney\'s Office by Immigration and Customs Enforcement and the Department of Homeland Security\'s \
// Investigation Division. Seven of the men are from so-called \"red-flagged\" countries, including Egypt, Turkey, Georgia, Pakistan and Mali.
// Her eighth husband, Rashid Rajput, was deported in 2006 to his native Pakistan after an investigation by the Joint Terrorism Task Force.
// If convicted, Barrientos faces up to four years in prison. Her next court appearance is scheduled for May 18."];
// let tokenized_input = tokenizer.encode_list(input.to_vec(), 1024, &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);
// Define input
let input = ["New York (CNN)When Liana Barrientos was 23 years old, she got married in Westchester County, New York.
A year later, she got married again in Westchester County, but to a different man and without divorcing her first husband.
Only 18 days after that marriage, she got hitched yet again. Then, Barrientos declared \"I do\" five more times, sometimes only within two weeks of each other. \
In 2010, she married once more, this time in the Bronx. In an application for a marriage license, she stated it was her \"first and only\" marriage. \
Barrientos, now 39, is facing two criminal counts of \"offering a false instrument for filing in the first degree,\" referring to her false statements on the
2010 marriage license application, according to court documents.
Prosecutors said the marriages were part of an immigration scam.
On Friday, she pleaded not guilty at State Supreme Court in the Bronx, according to her attorney, Christopher Wright, who declined to comment further.
After leaving court, Barrientos was arrested and charged with theft of service and criminal trespass for allegedly sneaking into the New York subway through an emergency exit, said Detective
Annette Markowski, a police spokeswoman. In total, Barrientos has been married 10 times, with nine of her marriages occurring between 1999 and 2002.
All occurred either in Westchester County, Long Island, New Jersey or the Bronx. She is believed to still be married to four men, and at one time, she was married to eight men at once, prosecutors say.
Prosecutors said the immigration scam involved some of her husbands, who filed for permanent residence status shortly after the marriages.
Any divorces happened only after such filings were approved. It was unclear whether any of the men will be prosecuted.
The case was referred to the Bronx District Attorney\'s Office by Immigration and Customs Enforcement and the Department of Homeland Security\'s \
Investigation Division. Seven of the men are from so-called \"red-flagged\" countries, including Egypt, Turkey, Georgia, Pakistan and Mali.
Her eighth husband, Rashid Rajput, was deported in 2006 to his native Pakistan after an investigation by the Joint Terrorism Task Force.
If convicted, Barrientos faces up to four years in prison. Her next court appearance is scheduled for May 18."];
let tokenized_input = tokenizer.encode_list(input.to_vec(), 1024, &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 (output, _, _) = no_grad(|| {
// bert_model
// .forward_t(Some(input_tensor),
// None,
// None,
// None,
// None,
// &None,
// &None,
// false)
// });
//
//// Print masked tokens
// let index_1 = output.get(0).get(4).argmax(0, false);
// let index_2 = output.get(1).get(7).argmax(0, false);
// let word_1 = tokenizer.vocab().id_to_token(&index_1.int64_value(&[]));
// let word_2 = tokenizer.vocab().id_to_token(&index_2.int64_value(&[]));
//
// println!("{}", word_1); // Outputs "person" : "Looks like one [person] is missing"
// println!("{}", word_2);// Outputs "pear" : "It was a very nice and [pleasant] day"
// Forward pass
let (decoder_output, encoder_output) = no_grad(|| {
bart_model
.forward_t(&input_tensor,
None,
None,
None,
None,
false)
});
// Print masked tokens
println!("{:?}", encoder_output);
println!("{:?}", decoder_output);
Ok(())
}

View File

@ -74,12 +74,14 @@ impl SelfAttention {
x.contiguous().view((dim_0, bs * self.num_heads, self.head_dim)).transpose(0, 1)
}
pub fn forward_t(&mut self, query: &Tensor, key: Option<&Tensor>, key_padding_mask: Option<&Tensor>,
attention_mask: Option<&Tensor>, train: bool) -> (Tensor, Option<Tensor>) {
pub fn forward_t(&mut self, query: &Tensor,
key: Option<&Tensor>,
key_padding_mask: Option<&Tensor>,
attention_mask: Option<&Tensor>,
train: bool) -> (Tensor, Option<Tensor>) {
let query_size = query.size();
let (target_sequence_length, bs) = (query_size[0], query_size[1]);
let q: Tensor = self.flatten(query.as_ref().apply(&self.q_proj) * self.scaling, target_sequence_length, bs);
let key = match &self.prev_state {
Some(prev_state) => {
if prev_state.prev_key.is_some() & self.encoder_decoder_attention {
@ -187,7 +189,13 @@ impl SelfAttention {
k.size()[1]);
(k, v, key_padding_mask)
}
None => (k.unwrap(), v.unwrap(), Some(key_padding_mask.as_ref().unwrap().copy()))
None => {
let key_padding_mask = match key_padding_mask {
Some(value) => Some(value.copy()),
None => None
};
(k.unwrap(), v.unwrap(), key_padding_mask)
}
}
}

View File

@ -165,7 +165,7 @@ impl BartModel {
encoder_outputs: Option<(Tensor, Option<Vec<Tensor>>, Option<Vec<Tensor>>)>,
decoder_attention_mask: Option<&Tensor>,
train: bool) ->
((Tensor, (Tensor, Option<Tensor>, Option<Vec<(&LayerState, &LayerState)>>), Option<Vec<Tensor>>, Option<Vec<Tensor>>),
((Tensor, (Option<Tensor>, Option<Vec<(&LayerState, &LayerState)>>), Option<Vec<Tensor>>, Option<Vec<Tensor>>),
(Tensor, Option<Vec<Tensor>>, Option<Vec<Tensor>>)) {
let (decoder_input_ids, decoder_padding_mask, causal_mask) = if self.generation_mode {
(decoder_input_ids.unwrap().copy(), None, None)

View File

@ -106,9 +106,8 @@ impl DecoderLayer {
let (output, attention_weights) = self.self_attention.forward_t(x, Some(x), decoder_padding_mask, causal_mask, train);
let output: Tensor = output.apply_t(&self.dropout, train) + x;
let output = output.apply(&self.self_attention_layer_norm);
let residual = output.copy();
let (output, _) = self.encoder_attention.forward_t(x, Some(encoder_hidden_states), encoder_attn_mask, None, train);
let (output, _) = self.encoder_attention.forward_t(&output, Some(encoder_hidden_states), encoder_attn_mask, None, train);
let output: Tensor = output.apply_t(&self.dropout, train) + residual;
let output = output.apply(&self.encoder_attention_layer_norm);
@ -195,7 +194,7 @@ impl BartDecoder {
decoder_causal_mask: Option<&Tensor>,
train: bool)
-> (Tensor,
(Tensor, Option<Tensor>, Option<Vec<(&LayerState, &LayerState)>>),
(Option<Tensor>, Option<Vec<(&LayerState, &LayerState)>>),
Option<Vec<Tensor>>,
Option<Vec<Tensor>>) {
let encoder_padding_mask = match encoder_padding_mask {
@ -203,15 +202,17 @@ impl BartDecoder {
None => None
};
let positions = &self.embed_positions.forward(input_ids, self.generation_mode);
let positions = self.embed_positions.forward(input_ids, self.generation_mode);
let (input_ids, positions) = if self.generation_mode {
let end = input_ids.size()[1];
(input_ids.slice(1, end - 1, end, 1), positions.slice(1, end - 1, end, 1))
} else {
(input_ids.copy(), positions.copy())
(input_ids.copy(), positions)
};
let x: Tensor = input_ids.as_ref().apply(&self.embed_tokens) + positions;
let x = x
.apply(&self.layer_norm_embedding)
.apply_t(&self.dropout, train)
@ -231,8 +232,9 @@ impl BartDecoder {
let temp = layer.forward_t(&hidden_state,
encoder_hidden_states,
encoder_padding_mask.as_ref(),
decoder_causal_mask,
decoder_padding_mask,
decoder_causal_mask, train);
train);
hidden_state = temp.0;
attention_weights = temp.1;
if let Some(hidden_states) = all_hidden_states.borrow_mut() {
@ -250,7 +252,7 @@ impl BartDecoder {
};
(hidden_state.transpose(0, 1),
(encoder_hidden_states.copy(), encoder_padding_mask, next_decoder_cache),
(encoder_padding_mask, next_decoder_cache),
all_hidden_states,
all_attentions)
}