diff --git a/model_zoo/ernie-gen/encode.py b/model_zoo/ernie-gen/encode.py
index 08bb5a740a59..dfdd0066f002 100644
--- a/model_zoo/ernie-gen/encode.py
+++ b/model_zoo/ernie-gen/encode.py
@@ -83,7 +83,6 @@ def gen_mask(batch_ids, mask_type='bidi', query_len=None, pad_value=0):
mask = np.tril(mask, -1)
elif mask_type == 'diag':
assert query_len == batch_ids.shape[1]
- # import pdb; pdb.set_trace()
mask = np.stack([np.diag(np.diag(m)) for m in mask], 0)
else:
diff --git a/paddlenlp/transformers/bart/modeling.py b/paddlenlp/transformers/bart/modeling.py
index b874e7449adb..7e560b461379 100644
--- a/paddlenlp/transformers/bart/modeling.py
+++ b/paddlenlp/transformers/bart/modeling.py
@@ -428,6 +428,12 @@ def get_encoder(self):
def get_decoder(self):
return self.decoder
+ def get_input_embeddings(self):
+ return self.shared
+
+ def set_input_embeddings(self, value):
+ self.shared = value
+
def forward(self,
input_ids,
attention_mask=None,
diff --git a/paddlenlp/transformers/bart/tokenizer.py b/paddlenlp/transformers/bart/tokenizer.py
index 591e56e0abac..f244e5a2ad26 100644
--- a/paddlenlp/transformers/bart/tokenizer.py
+++ b/paddlenlp/transformers/bart/tokenizer.py
@@ -13,13 +13,64 @@
# See the License for the specific language governing permissions and
# limitations under the License.
+import os
+from functools import lru_cache
+
+import json
+import shutil
from paddle.utils import try_import
-from .. import GPTTokenizer, AddedToken
+from .. import PretrainedTokenizer, AddedToken
__all__ = ['BartTokenizer']
+PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES = {
+ "bart-base": 1024,
+ "bart-large": 1024,
+}
+
+
+@lru_cache()
+def bytes_to_unicode():
+ """
+ Returns list of utf-8 byte and a corresponding list of unicode strings.
+ The reversible bpe codes work on unicode strings.
+ This means you need a large # of unicode characters in your vocab if you want to avoid UNKs.
+ When you're at something like a 10B token dataset you end up needing around 5K for decent coverage.
+ This is a signficant percentage of your normal, say, 32K bpe vocab.
+ To avoid that, we want lookup tables between utf-8 bytes and unicode strings.
+ And avoids mapping to whitespace/control characters the bpe code barfs on.
+ """
+ _chr = chr
+ bs = list(range(ord("!"),
+ ord("~") + 1)) + list(range(
+ ord("¡"),
+ ord("¬") + 1)) + list(range(ord("®"),
+ ord("ÿ") + 1))
+ cs = bs[:]
+ n = 0
+ for b in range(2**8):
+ if b not in bs:
+ bs.append(b)
+ cs.append(2**8 + n)
+ n += 1
+ cs = [_chr(n) for n in cs]
+ return dict(zip(bs, cs))
+
-class BartTokenizer(GPTTokenizer):
+def get_pairs(word):
+ """Return set of symbol pairs in a word.
+
+ Word is represented as tuple of symbols (symbols being variable-length strings).
+ """
+ pairs = set()
+ prev_char = word[0]
+ for char in word[1:]:
+ pairs.add((prev_char, char))
+ prev_char = char
+ return pairs
+
+
+class BartTokenizer(PretrainedTokenizer):
r"""
Construct a BART tokenizer based on byte-level Byte-Pair-Encoding.
@@ -100,12 +151,12 @@ class BartTokenizer(GPTTokenizer):
}
}
pretrained_init_configuration = {"bart-base": {}, "bart-large": {}}
+ max_model_input_sizes = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
def __init__(self,
vocab_file,
merges_file,
errors='replace',
- max_len=None,
bos_token="",
eos_token="",
cls_token="",
@@ -115,9 +166,6 @@ def __init__(self,
mask_token="",
**kwargs):
- super(BartTokenizer, self).__init__(vocab_file, merges_file, errors,
- max_len, pad_token, eos_token)
-
bos_token = AddedToken(bos_token,
lstrip=False, rstrip=False) if isinstance(
bos_token, str) else bos_token
@@ -150,6 +198,33 @@ def __init__(self,
pad_token=pad_token,
mask_token=mask_token)
+ self._vocab_file = vocab_file
+ self._merges_file = merges_file
+ self.num_command_tokens = 2
+ self.num_type_tokens = 2
+
+ with open(vocab_file, 'r', encoding='utf-8') as f:
+ self.encoder = json.load(f)
+
+ self.decoder = {v: k for k, v in self.encoder.items()}
+
+ self.num_tokens = len(self.encoder)
+ self.num_text_tokens = self.num_tokens - 1
+ self.errors = errors # how to handle errors in decoding
+ self.byte_encoder = bytes_to_unicode()
+ self.byte_decoder = {v: k for k, v in self.byte_encoder.items()}
+
+ with open(merges_file, encoding='utf-8') as f:
+ bpe_data = f.read().split('\n')[1:-1]
+
+ bpe_merges = [tuple(merge.split()) for merge in bpe_data]
+ self.bpe_ranks = dict(zip(bpe_merges, range(len(bpe_merges))))
+ self.cache = {}
+ re = try_import("regex")
+ self.pat = re.compile(
+ r"""'s|'t|'re|'ve|'m|'ll|'d| ?\p{L}+| ?\p{N}+| ?[^\s\p{L}\p{N}]+|\s+(?!\S)|\s+"""
+ )
+
def _bpe_encode(self, text):
bpe_tokens = []
re = try_import("regex")
@@ -200,3 +275,134 @@ def create_token_type_ids_from_sequences(self,
if token_ids_1 is None:
return len(cls + token_ids_0 + sep) * [0]
return len(cls + token_ids_0 + sep + sep + token_ids_1 + sep) * [0]
+
+ def get_vocab(self):
+ return dict(self.encoder, **self.added_tokens_encoder)
+
+ @property
+ def vocab_size(self):
+ """
+ Returns the size of vocabulary.
+
+ Returns:
+ int: The sum of size of vocabulary and the size of speical tokens.
+
+ """
+
+ return len(self.encoder)
+
+ @property
+ def eol_token_id(self):
+ if self.eol_token is None:
+ return None
+ return self.convert_tokens_to_ids(self.eol_token)
+
+ def bpe(self, token):
+ if token in self.cache:
+ return self.cache[token]
+ word = tuple(token)
+ pairs = get_pairs(word)
+
+ if not pairs:
+ return token
+
+ while True:
+ bigram = min(
+ pairs, key=lambda pair: self.bpe_ranks.get(pair, float('inf')))
+ if bigram not in self.bpe_ranks:
+ break
+ first, second = bigram
+ new_word = []
+ i = 0
+ while i < len(word):
+ try:
+ j = word.index(first, i)
+ new_word.extend(word[i:j])
+ i = j
+ except:
+ new_word.extend(word[i:])
+ break
+
+ if word[i] == first and i < len(word) - 1 and word[i +
+ 1] == second:
+ new_word.append(first + second)
+ i += 2
+ else:
+ new_word.append(word[i])
+ i += 1
+ new_word = tuple(new_word)
+ word = new_word
+ if len(word) == 1:
+ break
+ else:
+ pairs = get_pairs(word)
+ word = ' '.join(word)
+ self.cache[token] = word
+ return word
+
+ def _tokenize(self, text):
+ """ Tokenize a string. """
+ bpe_tokens = []
+ re = try_import("regex")
+ for token in re.findall(self.pat, text):
+ token = ''.join(self.byte_encoder[b] for b in token.encode('utf-8'))
+ bpe_tokens.extend(bpe_token
+ for bpe_token in self.bpe(token).split(' '))
+ return bpe_tokens
+
+ def _convert_token_to_id(self, token):
+ return self.encoder.get(token, self.encoder.get(self.unk_token))
+
+ def _convert_id_to_token(self, index):
+
+ return self.decoder[index]
+
+ def convert_ids_to_string(self, ids):
+ """
+ Converts a single index or a sequence of indices to texts.
+
+ Args:
+ ids (int|List[int]):
+ The token id (or token ids) to be converted to text.
+
+ Returns:
+ str: The decoded text.
+
+ Example:
+ .. code-block::
+
+ from paddlenlp.transformers import GPTTokenizer
+ tokenizer = GPTTokenizer.from_pretrained('gpt2-medium-en')
+ print(tokenizer.convert_ids_to_string(tokenizer.convert_ids_to_string([14618, 284, 779, 350, 37382, 47, 37382, 290, 350, 37382, 45, 19930]))
+ # 'Welcome to use PaddlePaddle and PaddleNLP'
+
+ """
+
+ text = ''.join([self.decoder[id] for id in ids])
+ text = bytearray([self.byte_decoder[c]
+ for c in text]).decode('utf-8', errors=self.errors)
+ return text
+
+ def save_resources(self, save_directory):
+ """
+ Saves `SentencePiece `__ file
+ (ends with '.spm') under `save_directory`.
+
+ Args:
+ save_directory (str): Directory to save files into.
+ """
+ for name, file_name in self.resource_files_names.items():
+ source_path = getattr(self, "_%s" % name)
+
+ save_path = os.path.join(save_directory, file_name)
+ if os.path.abspath(source_path) != os.path.abspath(save_path):
+ shutil.copyfile(source_path, save_path)
+
+ def convert_tokens_to_string(self, tokens):
+ """
+ Converts a sequence of tokens (string) in a single string.
+ """
+ text = "".join(tokens)
+ text = bytearray([self.byte_decoder[c]
+ for c in text]).decode('utf-8', errors=self.errors)
+ return text
diff --git a/paddlenlp/transformers/generation_utils.py b/paddlenlp/transformers/generation_utils.py
index a3d71f02898c..195efa6e107b 100644
--- a/paddlenlp/transformers/generation_utils.py
+++ b/paddlenlp/transformers/generation_utils.py
@@ -330,7 +330,8 @@ def get_logits_processor(self,
num_beams=1,
num_beam_groups=1,
diversity_rate=0.0,
- repetition_penalty=None):
+ repetition_penalty=None,
+ logits_processors=None):
processors = LogitsProcessorList()
if min_length is not None and eos_token_id is not None and min_length > -1:
@@ -354,7 +355,18 @@ def get_logits_processor(self,
# TODO
# Add more pre_processing for distribution
- return processors
+ if logits_processors is not None:
+ custom_processors = LogitsProcessorList()
+ custom_processors_type = [type(lp) for lp in logits_processors]
+
+ for processor in processors:
+ if type(processor) not in custom_processors_type:
+ custom_processors.append(processor)
+ custom_processors.extend(logits_processors)
+
+ return custom_processors
+ else:
+ return processors
@staticmethod
def expand_inputs_for_generation(input_ids,
@@ -502,6 +514,31 @@ def prepare_decoder_input_ids_for_generation(self,
return decoder_input_ids
+ def get_decoder_start_token_id(self,
+ decoder_start_token_id=None,
+ bos_token_id=None):
+ decoder_start_token_id = (
+ decoder_start_token_id if decoder_start_token_id is not None else
+ getattr(self, self.base_model_prefix).config.get(
+ "decoder_start_token_id", None))
+ bos_token_id = bos_token_id if bos_token_id is not None else getattr(
+ self, self.base_model_prefix).config["bos_token_id"]
+
+ if decoder_start_token_id is not None:
+ return decoder_start_token_id
+ elif getattr(self, self.base_model_prefix).config.get(
+ "decoder_start_token_id", None) is not None:
+ return getattr(
+ self, self.base_model_prefix).config["decoder_start_token_id"]
+ elif bos_token_id is not None:
+ return bos_token_id
+ elif getattr(self,
+ self.base_model_prefix).config["bos_token_id"] is not None:
+ return getattr(self, self.base_model_prefix).config["bos_token_id"]
+ raise ValueError(
+ "`decoder_start_token_id` or `bos_token_id` has to be defined for encoder-decoder generation."
+ )
+
def prepare_inputs_for_generation(self, input_ids, **kwargs):
# Implement in subclasses for custom behavior to prepare inputs in the
# generate method.
@@ -811,7 +848,6 @@ def generate(self,
else:
input_ids = self.prepare_decoder_input_ids_for_generation(
input_ids, decoder_start_token_id, bos_token_id)
-
if pad_token_id is None and eos_token_id is not None:
print("Setting `pad_token_id` to `eos_token_id`:{} for "
"open-end generation.".format(eos_token_id))
@@ -819,10 +855,11 @@ def generate(self,
model_kwargs["use_cache"] = use_cache
max_length += input_ids.shape[-1]
+ generate_min_length = min_length
min_length += input_ids.shape[-1]
logits_processors = self.get_logits_processor(
- min_length=min_length,
+ min_length=min_length if generate_min_length > 0 else None,
max_length=max_length,
eos_token_id=eos_token_id,
forced_bos_token_id=forced_bos_token_id,
@@ -830,7 +867,15 @@ def generate(self,
num_beams=num_beams,
num_beam_groups=num_beam_groups,
diversity_rate=diversity_rate,
- repetition_penalty=repetition_penalty)
+ repetition_penalty=repetition_penalty,
+ logits_processors=model_kwargs["logits_processors"]
+ if "logits_processors" in model_kwargs and isinstance(
+ model_kwargs["logits_processors"], LogitsProcessorList) else
+ None,
+ )
+
+ if "logits_processors" in model_kwargs:
+ model_kwargs.pop("logits_processors")
if decode_strategy == 'greedy_search':
if num_return_sequences > 1:
@@ -879,8 +924,8 @@ def generate(self,
return self.group_beam_search(input_ids, diverse_beam_scorer,
logits_processors, max_length,
- diversity_rate, pad_token_id,
- eos_token_id, **model_kwargs)
+ pad_token_id, eos_token_id,
+ **model_kwargs)
else:
beam_scorer = BeamSearchScorer(
batch_size=batch_size,
@@ -900,6 +945,9 @@ def generate(self,
def greedy_search(self, input_ids, logits_processors, max_length,
pad_token_id, eos_token_id, **model_kwargs):
+ logits_processors = logits_processors if logits_processors is not None else LogitsProcessorList(
+ )
+
batch_size, cur_len = input_ids.shape
origin_len = cur_len
unfinished_flag = paddle.full([batch_size, 1], True, dtype='bool')
@@ -962,41 +1010,8 @@ def sample(self,
min_tokens_to_keep=1,
**model_kwargs):
- def TopKProcess(probs, top_k, min_tokens_to_keep):
- top_k = min(max(top_k, min_tokens_to_keep), probs.shape[-1])
- # Remove all tokens with a probability less than the last token of the top-k
- topk_probs, _ = paddle.topk(probs, k=top_k)
- probs = paddle.where(probs >= topk_probs[:, -1:], probs,
- paddle.full_like(probs, 0.0))
- return probs
-
- def TopPProcess(probs, top_p, min_tokens_to_keep):
- sorted_probs = paddle.sort(probs, descending=True)
- sorted_indices = paddle.argsort(probs, descending=True)
- cumulative_probs = paddle.cumsum(sorted_probs, axis=-1)
-
- # Remove tokens with cumulative probs above the top_p, But keep at
- # least min_tokens_to_keep tokens
- sorted_indices_to_remove = cumulative_probs > top_p
- if min_tokens_to_keep > 1:
- # Set 'min_tokens_to_keep - 1' because the first token is kept
- sorted_indices_to_remove[:, :min_tokens_to_keep - 1] = 0
- # Keep the first token
- sorted_indices_to_remove = paddle.cast(sorted_indices_to_remove,
- dtype='int64')
- sorted_indices_to_remove[:, 1:] = (
- sorted_indices_to_remove[:, :-1].clone())
- sorted_indices_to_remove[:, 0] = 0
-
- # Scatter sorted tensors to original indexing
- sorted_indices = sorted_indices + paddle.arange(
- probs.shape[0]).unsqueeze(-1) * probs.shape[-1]
- condition = paddle.scatter(sorted_indices_to_remove.flatten(),
- sorted_indices.flatten(),
- sorted_indices_to_remove.flatten())
- condition = paddle.cast(condition, 'bool').reshape(probs.shape)
- probs = paddle.where(condition, paddle.full_like(probs, 0.0), probs)
- return probs
+ logits_processors = logits_processors if logits_processors is not None else LogitsProcessorList(
+ )
batch_size, cur_len = input_ids.shape
origin_len = cur_len
@@ -1059,6 +1074,9 @@ def TopPProcess(probs, top_p, min_tokens_to_keep):
def beam_search(self, input_ids, beam_scorer, logits_processors, max_length,
diversity_rate, pad_token_id, eos_token_id, **model_kwargs):
+ logits_processors = logits_processors if logits_processors is not None else LogitsProcessorList(
+ )
+
batch_size = len(beam_scorer._beam_hyps)
num_beams = beam_scorer.num_beams
batch_beam_size, cur_len = input_ids.shape
@@ -1183,8 +1201,10 @@ def beam_search(self, input_ids, beam_scorer, logits_processors, max_length,
return pred_ids[:, origin_len:], scores
def group_beam_search(self, input_ids, beam_scorer, logits_processors,
- max_length, diversity_rate, pad_token_id,
- eos_token_id, **model_kwargs):
+ max_length, pad_token_id, eos_token_id,
+ **model_kwargs):
+ logits_processors = logits_processors if logits_processors is not None else LogitsProcessorList(
+ )
batch_size = len(beam_scorer._beam_hyps)
num_beams = beam_scorer.num_beams
@@ -1503,3 +1523,40 @@ def __call__(self, input_ids, scores):
]] = -1e9 #TODO change back to -inf after paddle.topk is fixed
scores[:, self.forced_eos_token_id] = 0
return scores
+
+
+def TopKProcess(probs, top_k, min_tokens_to_keep):
+ top_k = min(max(top_k, min_tokens_to_keep), probs.shape[-1])
+ # Remove all tokens with a probability less than the last token of the top-k
+ topk_probs, _ = paddle.topk(probs, k=top_k)
+ probs = paddle.where(probs >= topk_probs[:, -1:], probs,
+ paddle.full_like(probs, 0.0))
+ return probs
+
+
+def TopPProcess(probs, top_p, min_tokens_to_keep):
+ sorted_probs = paddle.sort(probs, descending=True)
+ sorted_indices = paddle.argsort(probs, descending=True)
+ cumulative_probs = paddle.cumsum(sorted_probs, axis=-1)
+
+ # Remove tokens with cumulative probs above the top_p, But keep at
+ # least min_tokens_to_keep tokens
+ sorted_indices_to_remove = cumulative_probs > top_p
+ if min_tokens_to_keep > 1:
+ # Set 'min_tokens_to_keep - 1' because the first token is kept
+ sorted_indices_to_remove[:, :min_tokens_to_keep - 1] = 0
+ # Keep the first token
+ sorted_indices_to_remove = paddle.cast(sorted_indices_to_remove,
+ dtype='int64')
+ sorted_indices_to_remove[:, 1:] = (sorted_indices_to_remove[:, :-1].clone())
+ sorted_indices_to_remove[:, 0] = 0
+
+ # Scatter sorted tensors to original indexing
+ sorted_indices = sorted_indices + paddle.arange(
+ probs.shape[0]).unsqueeze(-1) * probs.shape[-1]
+ condition = paddle.scatter(sorted_indices_to_remove.flatten(),
+ sorted_indices.flatten(),
+ sorted_indices_to_remove.flatten())
+ condition = paddle.cast(condition, 'bool').reshape(probs.shape)
+ probs = paddle.where(condition, paddle.full_like(probs, 0.0), probs)
+ return probs
diff --git a/paddlenlp/transformers/gpt/tokenizer.py b/paddlenlp/transformers/gpt/tokenizer.py
index 6d963634a7c1..56ec8d0044ef 100644
--- a/paddlenlp/transformers/gpt/tokenizer.py
+++ b/paddlenlp/transformers/gpt/tokenizer.py
@@ -129,6 +129,7 @@ def __init__(
eol_token='\u2583',
**kwargs # The token of newline.
):
+
self._model_file = model_file
self.eol_token = eol_token
if not os.path.isfile(model_file):
@@ -370,6 +371,7 @@ def __init__(
add_prefix_space=False,
**kwargs # The token of newline.
):
+
pad_token = AddedToken(pad_token,
lstrip=False, rstrip=False) if isinstance(
pad_token, str) else pad_token
@@ -542,6 +544,9 @@ def convert_tokens_to_string(self, tokens):
for c in text]).decode('utf-8', errors=self.errors)
return text
+ def get_vocab(self):
+ return dict(self.encoder, **self.added_tokens_encoder)
+
def prepare_for_tokenization(self,
text,
is_split_into_words=False,
diff --git a/paddlenlp/transformers/model_utils.py b/paddlenlp/transformers/model_utils.py
index 33911d6b78d4..62e7074a7016 100644
--- a/paddlenlp/transformers/model_utils.py
+++ b/paddlenlp/transformers/model_utils.py
@@ -153,7 +153,7 @@ def get_input_embeddings(self):
return base_model.get_input_embeddings()
else:
raise NotImplementedError(
- f'model of {type(base_model)} has not implemented the `get_input_embedding`'
+ f'model of {type(base_model)} has not implemented the `get_input_embeddings`'
' or `set_input_embedding` method')
def set_input_embeddings(self, value):
@@ -162,7 +162,7 @@ def set_input_embeddings(self, value):
return base_model.set_input_embeddings(value)
else:
raise NotImplementedError(
- f'model of {type(base_model)} has not implemented the `get_input_embedding`'
+ f'model of {type(base_model)} has not implemented the `get_input_embeddings`'
' or `set_input_embedding` method')
def get_output_embeddings(self):
diff --git a/tests/transformers/bart/__init__.py b/tests/transformers/bart/__init__.py
new file mode 100644
index 000000000000..e69de29bb2d1
diff --git a/tests/transformers/bart/test_modeling.py b/tests/transformers/bart/test_modeling.py
new file mode 100644
index 000000000000..3402e43a0d0a
--- /dev/null
+++ b/tests/transformers/bart/test_modeling.py
@@ -0,0 +1,868 @@
+# coding=utf-8
+# Copyright (c) 2022 PaddlePaddle Authors. All Rights Reserved.
+# Copyright 2021, The HuggingFace Inc. team. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+import copy
+import tempfile
+import unittest
+
+from tests.testing_utils import slow
+
+from ..test_generation_utils import GenerationTesterMixin
+from ..test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor
+from paddlenlp.transformers.tokenizer_utils_base import PaddingStrategy, TruncationStrategy
+
+import paddle
+
+from paddlenlp.transformers import (
+ AutoModelForSequenceClassification,
+ BartForConditionalGeneration,
+ BartForQuestionAnswering,
+ BartForSequenceClassification,
+ BartModel,
+ BartTokenizer,
+)
+from paddlenlp.transformers.bart.modeling import BartDecoder, BartEncoder, shift_tokens_right
+
+
+def prepare_bart_inputs_dict(
+ config,
+ input_ids,
+ decoder_input_ids=None,
+ attention_mask=None,
+ decoder_attention_mask=None,
+ head_mask=None,
+ decoder_head_mask=None,
+ cross_attn_head_mask=None,
+):
+ if attention_mask is None:
+ attention_mask = paddle.cast(
+ input_ids == config["pad_token_id"],
+ dtype=paddle.get_default_dtype()).unsqueeze([1, 2]) * -1e4
+ if decoder_attention_mask is None:
+ decoder_attention_mask = paddle.cast(
+ decoder_input_ids == config["pad_token_id"],
+ dtype=paddle.get_default_dtype()).unsqueeze([1, 2]) * -1e4
+ return {
+ "input_ids": input_ids,
+ "decoder_input_ids": decoder_input_ids,
+ "attention_mask": attention_mask,
+ "decoder_attention_mask": attention_mask,
+ }
+
+
+class BartModelTester:
+
+ def __init__(
+ self,
+ parent,
+ batch_size=13,
+ seq_length=7,
+ is_training=True,
+ use_labels=False,
+ vocab_size=99,
+ hidden_size=16,
+ num_hidden_layers=2,
+ num_attention_heads=4,
+ intermediate_size=4,
+ hidden_act="gelu",
+ hidden_dropout_prob=0.1,
+ attention_probs_dropout_prob=0.1,
+ max_position_embeddings=20,
+ eos_token_id=2,
+ pad_token_id=1,
+ bos_token_id=0,
+ ):
+ self.parent = parent
+ self.batch_size = batch_size
+ self.seq_length = seq_length
+ self.is_training = is_training
+ self.use_labels = use_labels
+ self.vocab_size = vocab_size
+ self.hidden_size = hidden_size
+ self.num_hidden_layers = num_hidden_layers
+ self.num_attention_heads = num_attention_heads
+ self.intermediate_size = intermediate_size
+ self.hidden_act = hidden_act
+ self.hidden_dropout_prob = hidden_dropout_prob
+ self.attention_probs_dropout_prob = attention_probs_dropout_prob
+ self.max_position_embeddings = max_position_embeddings
+ self.eos_token_id = eos_token_id
+ self.pad_token_id = pad_token_id
+ self.bos_token_id = bos_token_id
+
+ # forcing a certain token to be generated, sets all other tokens to -inf
+ # if however the token to be generated is already at -inf then it can lead token
+ # `nan` values and thus break generation
+ self.forced_eos_token_id = None
+
+ def prepare_config_and_inputs(self):
+ input_ids = ids_tensor([self.batch_size, self.seq_length],
+ self.vocab_size,
+ dtype="int64")
+ input_ids = paddle.clip(
+ ids_tensor([self.batch_size, self.seq_length],
+ self.vocab_size,
+ dtype="int64"), 3)
+ input_ids[:, -1] = self.eos_token_id # Eos Token
+
+ decoder_input_ids = ids_tensor([self.batch_size, self.seq_length],
+ self.vocab_size,
+ dtype="int64")
+
+ config = self.get_config()
+ inputs_dict = prepare_bart_inputs_dict(config, input_ids,
+ decoder_input_ids)
+ return config, inputs_dict
+
+ def get_config(self):
+ return {
+ "vocab_size": self.vocab_size,
+ "d_model": self.hidden_size,
+ "num_encoder_layers": self.num_hidden_layers,
+ "num_decoder_layers": self.num_hidden_layers,
+ "encoder_attention_heads": self.num_attention_heads,
+ "decoder_attention_heads": self.num_attention_heads,
+ "encoder_ffn_dim": self.intermediate_size,
+ "decoder_ffn_dim": self.intermediate_size,
+ "dropout": self.hidden_dropout_prob,
+ "attention_dropout": self.attention_probs_dropout_prob,
+ "max_position_embeddings": self.max_position_embeddings,
+ "eos_token_id": self.eos_token_id,
+ "bos_token_id": self.bos_token_id,
+ "pad_token_id": self.pad_token_id,
+ "forced_eos_token_id": self.forced_eos_token_id,
+ }
+
+ def prepare_config_and_inputs_for_common(self):
+ config, inputs_dict = self.prepare_config_and_inputs()
+ return config, inputs_dict
+
+ def create_and_check_decoder_model_past_large_inputs(
+ self, config, inputs_dict):
+ encoder = BartModel(**config).get_encoder()
+ decoder = BartModel(**config).get_decoder()
+
+ encoder.eval()
+ decoder.eval()
+
+ input_ids = inputs_dict["input_ids"]
+ decoder_input_ids = paddle.zeros_like(
+ input_ids[:, :1],
+ dtype="int64") + BartModel(**config).decoder_start_token_id
+
+ attention_mask = inputs_dict["attention_mask"]
+ decoder_attention_mask = paddle.zeros([input_ids.shape[0], 1, 1, 1],
+ dtype=paddle.get_default_dtype())
+
+ encoder_output = encoder(input_ids, attention_mask)
+ origin_cache = decoder.decoder.gen_cache(encoder_output)
+ outputs = decoder(decoder_input_ids,
+ decoder_attention_mask,
+ encoder_output,
+ attention_mask,
+ cache=origin_cache)
+
+ output, cache = outputs
+
+ # create hypothetical multiple next token and extent to next_input_ids
+ next_tokens = ids_tensor((self.batch_size, 3),
+ config["vocab_size"],
+ dtype="int64")
+ next_attn_mask = paddle.zeros([self.batch_size, 1, 1, 3],
+ dtype=paddle.get_default_dtype())
+
+ # append to next input_ids and
+ next_input_ids = paddle.concat([decoder_input_ids, next_tokens],
+ axis=-1)
+ next_attention_mask = paddle.concat(
+ [decoder_attention_mask, next_attn_mask], axis=-1)
+
+ output_from_no_past, _ = decoder(next_input_ids,
+ next_attention_mask,
+ encoder_output,
+ attention_mask,
+ cache=origin_cache)
+ output_from_past, _ = decoder(next_tokens,
+ next_attention_mask,
+ encoder_output,
+ attention_mask,
+ cache=cache)
+
+ # select random slice
+ random_slice_idx = ids_tensor((1, ),
+ output_from_past.shape[-1],
+ dtype="int64").item()
+ output_from_no_past_slice = output_from_no_past[:, -3:,
+ random_slice_idx].detach(
+ )
+ output_from_past_slice = output_from_past[:, :,
+ random_slice_idx].detach()
+
+ self.parent.assertTrue(
+ output_from_past_slice.shape[1] == next_tokens.shape[1])
+
+ # test that outputs are equal for slice
+ self.parent.assertTrue(
+ paddle.allclose(output_from_past_slice,
+ output_from_no_past_slice,
+ atol=1e-3))
+
+
+class BartHeadTests(unittest.TestCase):
+ vocab_size = 99
+
+ def _get_config_and_data(self):
+ input_ids = paddle.to_tensor(
+ [
+ [71, 82, 18, 33, 46, 91, 2],
+ [68, 34, 26, 58, 30, 82, 2],
+ [5, 97, 17, 39, 94, 40, 2],
+ [76, 83, 94, 25, 70, 78, 2],
+ [87, 59, 41, 35, 48, 66, 2],
+ [55, 13, 16, 58, 5, 2, 1], # note padding
+ [64, 27, 31, 51, 12, 75, 2],
+ [52, 64, 86, 17, 83, 39, 2],
+ [48, 61, 9, 24, 71, 82, 2],
+ [26, 1, 60, 48, 22, 13, 2],
+ [21, 5, 62, 28, 14, 76, 2],
+ [45, 98, 37, 86, 59, 48, 2],
+ [70, 70, 50, 9, 28, 0, 2],
+ ],
+ dtype="int64",
+ )
+
+ batch_size = input_ids.shape[0]
+ config = {
+ "vocab_size": self.vocab_size,
+ "d_model": 24,
+ "num_encoder_layers": 2,
+ "num_decoder_layers": 2,
+ "encoder_attention_heads": 2,
+ "decoder_attention_heads": 2,
+ "encoder_ffn_dim": 32,
+ "decoder_ffn_dim": 32,
+ "max_position_embeddings": 48,
+ "eos_token_id": 2,
+ "pad_token_id": 1,
+ "bos_token_id": 0,
+ }
+ return config, input_ids, batch_size
+
+ def test_sequence_classification_forward(self):
+ config, input_ids, batch_size = self._get_config_and_data()
+ bart_model = BartModel(**config)
+ num_labels = 2
+ model = BartForSequenceClassification(bart_model, num_labels=num_labels)
+ outputs = model(input_ids=input_ids, decoder_input_ids=input_ids)
+ expected_shape = [batch_size, num_labels]
+ self.assertEqual(outputs.shape, expected_shape)
+
+ def test_question_answering_forward(self):
+ config, input_ids, batch_size = self._get_config_and_data()
+ bart_model = BartModel(**config)
+ model = BartForQuestionAnswering(bart_model)
+ start_logits, end_logits = model(input_ids=input_ids)
+
+ self.assertEqual(start_logits.shape, input_ids.shape)
+ self.assertEqual(end_logits.shape, input_ids.shape)
+
+ def test_lm_forward(self):
+ config, input_ids, batch_size = self._get_config_and_data()
+ bart_model = BartModel(**config)
+ lm_model = BartForConditionalGeneration(bart_model)
+ outputs = lm_model(input_ids=input_ids)
+ expected_shape = [batch_size, input_ids.shape[1], config["vocab_size"]]
+ self.assertEqual(outputs.shape, expected_shape)
+
+ def test_lm_uneven_forward(self):
+ config = {
+ "vocab_size": self.vocab_size,
+ "d_model": 14,
+ "num_encoder_layers": 2,
+ "num_decoder_layers": 2,
+ "encoder_attention_heads": 2,
+ "decoder_attention_heads": 2,
+ "encoder_ffn_dim": 8,
+ "decoder_ffn_dim": 8,
+ "max_position_embeddings": 48,
+ }
+ bart_model = BartModel(**config)
+ lm_model = BartForConditionalGeneration(bart_model)
+ context = paddle.to_tensor(
+ [[71, 82, 18, 33, 46, 91, 2], [68, 34, 26, 58, 30, 2, 1]],
+ dtype="int64")
+ summary = paddle.to_tensor([[82, 71, 82, 18, 2], [58, 68, 2, 1, 1]],
+ dtype="int64")
+ outputs = lm_model(input_ids=context, decoder_input_ids=summary)
+ expected_shape = summary.shape
+ expected_shape.append(config["vocab_size"])
+ self.assertEqual(outputs.shape, expected_shape)
+
+ def test_generate_beam_search(self):
+ input_ids = paddle.to_tensor([[71, 82, 2], [68, 34, 2]], dtype="int64")
+ config = {
+ "vocab_size": self.vocab_size,
+ "d_model": 24,
+ "num_encoder_layers": 2,
+ "num_decoder_layers": 2,
+ "encoder_attention_heads": 2,
+ "decoder_attention_heads": 2,
+ "encoder_ffn_dim": 32,
+ "decoder_ffn_dim": 32,
+ "max_position_embeddings": 48,
+ "eos_token_id": 2,
+ "pad_token_id": 1,
+ "bos_token_id": 0,
+ }
+ bart_model = BartModel(**config)
+ lm_model = BartForConditionalGeneration(bart_model)
+ lm_model.eval()
+
+ max_length = 5
+ generated_ids = lm_model.generate(
+ input_ids,
+ decode_strategy="sampling",
+ num_return_sequences=1,
+ max_length=max_length,
+ top_k=4,
+ )[0]
+ self.assertEqual(generated_ids.shape, [input_ids.shape[0], max_length])
+
+ def test_shift_tokens_right(self):
+ input_ids = paddle.to_tensor(
+ [[71, 82, 18, 33, 2, 1, 1], [68, 34, 26, 58, 30, 82, 2]],
+ dtype="int64")
+ shifted = shift_tokens_right(input_ids, 2)
+ n_pad_before = paddle.equal(input_ids, 1).sum().numpy()
+ n_pad_after = paddle.equal(shifted, 1).sum().numpy()
+ self.assertEqual(shifted.shape, input_ids.shape)
+ self.assertEqual(n_pad_after, n_pad_before - 1)
+ self.assertTrue(paddle.equal(shifted[:, 0], 2).all())
+
+ @slow
+ def test_tokenization(self):
+ tokenizer = BartTokenizer.from_pretrained("bart-large")
+ examples = [" Hello world",
+ " DomDramg"] # need leading spaces for equality
+ fairseq_results = [
+ paddle.to_tensor([0, 20920, 232, 2]),
+ paddle.to_tensor([0, 11349, 495, 4040, 571, 2]),
+ ]
+ for ex, desired_result in zip(examples, fairseq_results):
+ bart_toks = tokenizer.encode(ex, return_tensors="pd").squeeze()
+ assert_tensors_close(desired_result.long(), bart_toks, prefix=ex)
+
+
+class BartModelTest(ModelTesterMixin, GenerationTesterMixin, unittest.TestCase):
+ base_model_class = BartModel
+
+ all_model_classes = (BartModel, BartForConditionalGeneration,
+ BartForSequenceClassification,
+ BartForQuestionAnswering)
+ all_generative_model_classes = {
+ BartForConditionalGeneration: (BartModel, "bart")
+ }
+ is_encoder_decoder = True
+ fx_compatible = True
+ test_pruning = False
+ test_missing_keys = False
+
+ def setUp(self):
+ self.model_tester = BartModelTester(self)
+
+ def test_decoder_model_past_with_large_inputs(self):
+ config_and_inputs = self.model_tester.prepare_config_and_inputs()
+ self.model_tester.create_and_check_decoder_model_past_large_inputs(
+ *config_and_inputs)
+
+
+def assert_tensors_close(a, b, atol=1e-12, prefix=""):
+ """If tensors have different shapes, different values or a and b are not both tensors, raise a nice Assertion error."""
+ if a is None and b is None:
+ return True
+ try:
+ if paddle.allclose(a, b, atol=atol):
+ return True
+ raise
+ except Exception:
+ pct_different = (paddle.gt((a - b).abs(), atol)).float().mean().item()
+ if a.numel() > 100:
+ msg = f"tensor values are {pct_different:.1%} percent different."
+ else:
+ msg = f"{a} != {b}"
+ if prefix:
+ msg = prefix + ": " + msg
+ raise AssertionError(msg)
+
+
+def _long_tensor(tok_lst):
+ return paddle.to_tensor(tok_lst, dtype="int64")
+
+
+@slow
+class FastIntegrationTests(unittest.TestCase):
+ """These tests are useful for debugging since they operate on a model with 1 encoder layer and 1 decoder layer."""
+
+ def tok(self):
+ return BartTokenizer.from_pretrained("bart-large")
+
+ def bart_base(self):
+ return BartForConditionalGeneration.from_pretrained("bart-base")
+
+ def test_bart_base_generation(self):
+ model = self.bart_base
+ tok = self.tok
+ ARTICLE = (
+ "The Palestinian Authority officially became the 123rd member of the International Criminal Court on"
+ " Wednesday, a step that gives the court jurisdiction over alleged crimes in Palestinian territories. The"
+ " formal accession was marked with a ceremony at The Hague, in the Netherlands, where the court is based."
+ " The Palestinians signed the ICC's founding Rome Statute in January, when they also accepted its"
+ ' jurisdiction over alleged crimes committed "in the occupied Palestinian territory, including East'
+ ' Jerusalem, since June 13, 2014." Later that month, the ICC opened a preliminary examination into the'
+ " situation in Palestinian territories, paving the way for possible war crimes investigations against"
+ " Israelis. As members of the court, Palestinians may be subject to counter-charges as well. Israel and"
+ " the United States, neither of which is an ICC member, opposed the Palestinians' efforts to join the"
+ " body. But Palestinian Foreign Minister Riad al-Malki, speaking at Wednesday's ceremony, said it was a"
+ ' move toward greater justice. "As Palestine formally becomes a State Party to the Rome Statute today, the'
+ ' world is also a step closer to ending a long era of impunity and injustice," he said, according to an'
+ ' ICC news release. "Indeed, today brings us closer to our shared goals of justice and peace." Judge'
+ " Kuniko Ozaki, a vice president of the ICC, said acceding to the treaty was just the first step for the"
+ ' Palestinians. "As the Rome Statute today enters into force for the State of Palestine, Palestine'
+ " acquires all the rights as well as responsibilities that come with being a State Party to the Statute."
+ ' These are substantive commitments, which cannot be taken lightly," she said. Rights group Human Rights'
+ ' Watch welcomed the development. "Governments seeking to penalize Palestine for joining the ICC should'
+ " immediately end their pressure, and countries that support universal acceptance of the court's treaty"
+ ' should speak out to welcome its membership," said Balkees Jarrah, international justice counsel for the'
+ " group. \"What's objectionable is the attempts to undermine international justice, not Palestine's"
+ ' decision to join a treaty to which over 100 countries around the world are members." In January, when'
+ " the preliminary ICC examination was opened, Israeli Prime Minister Benjamin Netanyahu described it as an"
+ ' outrage, saying the court was overstepping its boundaries. The United States also said it "strongly"'
+ " disagreed with the court's decision. \"As we have said repeatedly, we do not believe that Palestine is a"
+ ' state and therefore we do not believe that it is eligible to join the ICC," the State Department said in'
+ ' a statement. It urged the warring sides to resolve their differences through direct negotiations. "We'
+ ' will continue to oppose actions against Israel at the ICC as counterproductive to the cause of peace,"'
+ " it said. But the ICC begs to differ with the definition of a state for its purposes and refers to the"
+ ' territories as "Palestine." While a preliminary examination is not a formal investigation, it allows the'
+ " court to review evidence and determine whether to investigate suspects on both sides. Prosecutor Fatou"
+ ' Bensouda said her office would "conduct its analysis in full independence and impartiality." The war'
+ " between Israel and Hamas militants in Gaza last summer left more than 2,000 people dead. The inquiry"
+ " will include alleged war crimes committed since June. The International Criminal Court was set up in"
+ " 2002 to prosecute genocide, crimes against humanity and war crimes."
+ )
+ EXPECTED = (
+ " The Palestinian Authority officially became the 123rd member of the International Criminal Court on Wednesday, a step that gives the court jurisdiction over alleged crimes in Palestinian territories. The formal accession was marked with a ceremony at The Hague, in the Netherlands, where the court is based. The Palestinians signed the ICC's founding Rome Statute in January, when they also accepted its jurisdiction over alleged crimes committed \"in the occupied Palestinian territory, including East Jerusalem, since June 13, 2014.\" Later that month, the ICC opened a preliminary examination into the situation in Palestinian territories, paving the way for possible war crimes investigations against Israelis. As members of the court, Palestinians may be subject to counter-charges as well. Israel and the United States, neither of which is an ICC member, opposed the Palestinians' efforts to join the body. But Palestinian Foreign Minister Riad al-Malki, speaking at Wednesday's ceremony said it was a move toward greater justice. \"As Palestine formally becomes a State Party to the Rome Statute today, the world is also a step closer to ending a long era of impunity and injustice,\" he said, according to an ICC news release. \"Indeed, today brings us closer to our shared goals of ending a long era of impunity and peace. \"Indeed, today brings us closer to our shared goals of justice and peace,\" he said, according to an ICC news release. \"The ICC is a step closer to ending a long era of impunity and injustice,\" he said, according to an ICC news release. \"Indeed, today brings us closer to our shared goals of justice and peace.\" Judge Kuniko Ozaki, a vice president of the ICC, said acceding to the treaty was just the first step for the Palestinians. \"As the Rome Statute today enters into force for the State of Palestine, Palestine acquires all the rights as well as responsibilities that come with being a State Party to the Statute. These are substantive commitments, which cannot be taken lightly,\" she said. Rights group Human Rights Watch said the development. \"Governments seeking to penalize Palestine for joining the ICC should immediately end their pressure, and countries that support universal acceptance of the court's treaty should speak out to welcome its membership. \"What's objectionable is the attempts to undermine international justice, not Palestine's decision to join a treaty to which over 100 countries around the world are members.\" In January, when the preliminary ICC examination was opened, Israeli Prime Minister Benjamin Netanyahu described it as an outrage, saying the court was overstepping its boundaries. \"As we have said repeatedly, we do not believe that Palestine is a state and therefore we do not believe that Palestine is eligible to join the ICC,\" the State Department said in a statement. It urged the warring sides to resolve their differences through direct negotiations. \"We will continue to support actions against Palestine,\" it said in a statement, it said. \"We will continue to support the court's decision. \"We will continue to fight against the ICC and the ICC. We will continue to fight for the rights of the Palestinians, and we will continue to fight for the cause of Palestine. We will continue to fight for justice and justice,\" it said in a statement. \"We will continue to fight against the ICC for its purposes and refers to the territories as \"Palestine.\" While a preliminary examination is not a formal investigation, it allows the court. The court is not a formal investigation, it allows the court to review evidence and determine whether to investigate suspects on both sides. Prosecutor Fatou Bensouda said her office would \"conduct its analysis in full independence and impartiality.\" The war between Israel and Hamas militants in Gaza last summer left more than 2,000 people dead. The inquiry will include alleged war crimes crimes committed since June. The International Criminal Court was set up in 2002 to prosecute genocide, crimes against humanity and war crimes. "
+ )
+
+ dct = tok(ARTICLE, return_tensors="pd")
+
+ dct.pop("token_type_ids")
+ generated_ids, _ = model.generate(**dct,
+ num_beams=4,
+ decode_strategy="beam_search",
+ max_length=1024)
+ result = tok.batch_decode(generated_ids, skip_special_tokens=True)[0]
+ assert EXPECTED == result
+
+ def test_xsum_1_1_batch_generation(self):
+ # test batch
+
+ batch = self.tok(
+ [
+ "The Palestinian Authority officially became the 123rd member of the International Criminal Court on"
+ " Wednesday, a step that gives the court jurisdiction over alleged crimes in Palestinian territories."
+ " The formal accession was marked with a ceremony at The Hague, in the Netherlands, where the court is"
+ " based. The Palestinians signed the ICC's founding Rome Statute in January, when they also accepted"
+ ' its jurisdiction over alleged crimes committed "in the occupied Palestinian territory, including'
+ ' East Jerusalem, since June 13, 2014." Later that month, the ICC opened a preliminary examination'
+ " into the situation in Palestinian territories, paving the way for possible war crimes investigations"
+ " against Israelis. As members of the court, Palestinians may be subject to counter-charges as well."
+ " Israel and the United States, neither of which is an ICC member, opposed the Palestinians' efforts"
+ " to join the body. But Palestinian Foreign Minister Riad al-Malki, speaking at Wednesday's ceremony,"
+ ' said it was a move toward greater justice. "As Palestine formally becomes a State Party to the Rome'
+ ' Statute today, the world is also a step closer to ending a long era of impunity and injustice," he'
+ ' said, according to an ICC news release. "Indeed, today brings us closer to our shared goals of'
+ ' justice and peace." Judge Kuniko Ozaki, a vice president of the ICC, said acceding to the treaty was'
+ ' just the first step for the Palestinians. "As the Rome Statute today enters into force for the State'
+ " of Palestine, Palestine acquires all the rights as well as responsibilities that come with being a"
+ ' State Party to the Statute. These are substantive commitments, which cannot be taken lightly," she'
+ ' said. Rights group Human Rights Watch welcomed the development. "Governments seeking to penalize'
+ " Palestine for joining the ICC should immediately end their pressure, and countries that support"
+ " universal acceptance of the court's treaty should speak out to welcome its membership,\" said"
+ " Balkees Jarrah, international justice counsel for the group. \"What's objectionable is the attempts"
+ " to undermine international justice, not Palestine's decision to join a treaty to which over 100"
+ ' countries around the world are members." In January, when the preliminary ICC examination was'
+ " opened, Israeli Prime Minister Benjamin Netanyahu described it as an outrage, saying the court was"
+ ' overstepping its boundaries. The United States also said it "strongly" disagreed with the court\'s'
+ ' decision. "As we have said repeatedly, we do not believe that Palestine is a state and therefore we'
+ ' do not believe that it is eligible to join the ICC," the State Department said in a statement. It'
+ ' urged the warring sides to resolve their differences through direct negotiations. "We will continue'
+ ' to oppose actions against Israel at the ICC as counterproductive to the cause of peace," it said.'
+ " But the ICC begs to differ with the definition of a state for its purposes and refers to the"
+ ' territories as "Palestine." While a preliminary examination is not a formal investigation, it allows'
+ " the court to review evidence and determine whether to investigate suspects on both sides. Prosecutor"
+ ' Fatou Bensouda said her office would "conduct its analysis in full independence and impartiality."'
+ " The war between Israel and Hamas militants in Gaza last summer left more than 2,000 people dead. The"
+ " inquiry will include alleged war crimes committed since June. The International Criminal Court was"
+ " set up in 2002 to prosecute genocide, crimes against humanity and war crimes.",
+ "The French prosecutor leading an investigation into the crash of Germanwings Flight 9525 insisted"
+ " Wednesday that he was not aware of any video footage from on board the plane. Marseille prosecutor"
+ ' Brice Robin told CNN that "so far no videos were used in the crash investigation." He added, "A'
+ " person who has such a video needs to immediately give it to the investigators.\" Robin's comments"
+ " follow claims by two magazines, German daily Bild and French Paris Match, of a cell phone video"
+ " showing the harrowing final seconds from on board Germanwings Flight 9525 as it crashed into the"
+ " French Alps. All 150 on board were killed. Paris Match and Bild reported that the video was"
+ " recovered from a phone at the wreckage site. The two publications described the supposed video, but"
+ " did not post it on their websites. The publications said that they watched the video, which was"
+ " found by a source close to the investigation. \"One can hear cries of 'My God' in several"
+ ' languages," Paris Match reported. "Metallic banging can also be heard more than three times, perhaps'
+ " of the pilot trying to open the cockpit door with a heavy object. Towards the end, after a heavy"
+ ' shake, stronger than the others, the screaming intensifies. Then nothing." "It is a very disturbing'
+ " scene,\" said Julian Reichelt, editor-in-chief of Bild online. An official with France's accident"
+ " investigation agency, the BEA, said the agency is not aware of any such video. Lt. Col. Jean-Marc"
+ " Menichini, a French Gendarmerie spokesman in charge of communications on rescue efforts around the"
+ ' Germanwings crash site, told CNN that the reports were "completely wrong" and "unwarranted." Cell'
+ ' phones have been collected at the site, he said, but that they "hadn\'t been exploited yet."'
+ " Menichini said he believed the cell phones would need to be sent to the Criminal Research Institute"
+ " in Rosny sous-Bois, near Paris, in order to be analyzed by specialized technicians working"
+ " hand-in-hand with investigators. But none of the cell phones found so far have been sent to the"
+ " institute, Menichini said. Asked whether staff involved in the search could have leaked a memory"
+ ' card to the media, Menichini answered with a categorical "no." Reichelt told "Erin Burnett:'
+ ' Outfront" that he had watched the video and stood by the report, saying Bild and Paris Match are'
+ ' "very confident" that the clip is real. He noted that investigators only revealed they\'d recovered'
+ ' cell phones from the crash site after Bild and Paris Match published their reports. "That is'
+ " something we did not know before. ... Overall we can say many things of the investigation weren't"
+ ' revealed by the investigation at the beginning," he said. What was mental state of Germanwings'
+ " co-pilot? German airline Lufthansa confirmed Tuesday that co-pilot Andreas Lubitz had battled"
+ " depression years before he took the controls of Germanwings Flight 9525, which he's accused of"
+ " deliberately crashing last week in the French Alps. Lubitz told his Lufthansa flight training school"
+ ' in 2009 that he had a "previous episode of severe depression," the airline said Tuesday. Email'
+ " correspondence between Lubitz and the school discovered in an internal investigation, Lufthansa"
+ " said, included medical documents he submitted in connection with resuming his flight training. The"
+ " announcement indicates that Lufthansa, the parent company of Germanwings, knew of Lubitz's battle"
+ " with depression, allowed him to continue training and ultimately put him in the cockpit. Lufthansa,"
+ " whose CEO Carsten Spohr previously said Lubitz was 100% fit to fly, described its statement Tuesday"
+ ' as a "swift and seamless clarification" and said it was sharing the information and documents --'
+ " including training and medical records -- with public prosecutors. Spohr traveled to the crash site"
+ " Wednesday, where recovery teams have been working for the past week to recover human remains and"
+ " plane debris scattered across a steep mountainside. He saw the crisis center set up in"
+ " Seyne-les-Alpes, laid a wreath in the village of Le Vernet, closer to the crash site, where grieving"
+ " families have left flowers at a simple stone memorial. Menichini told CNN late Tuesday that no"
+ " visible human remains were left at the site but recovery teams would keep searching. French"
+ " President Francois Hollande, speaking Tuesday, said that it should be possible to identify all the"
+ " victims using DNA analysis by the end of the week, sooner than authorities had previously suggested."
+ " In the meantime, the recovery of the victims' personal belongings will start Wednesday, Menichini"
+ " said. Among those personal belongings could be more cell phones belonging to the 144 passengers and"
+ " six crew on board. Check out the latest from our correspondents . The details about Lubitz's"
+ " correspondence with the flight school during his training were among several developments as"
+ " investigators continued to delve into what caused the crash and Lubitz's possible motive for"
+ " downing the jet. A Lufthansa spokesperson told CNN on Tuesday that Lubitz had a valid medical"
+ ' certificate, had passed all his examinations and "held all the licenses required." Earlier, a'
+ " spokesman for the prosecutor's office in Dusseldorf, Christoph Kumpa, said medical records reveal"
+ " Lubitz suffered from suicidal tendencies at some point before his aviation career and underwent"
+ " psychotherapy before he got his pilot's license. Kumpa emphasized there's no evidence suggesting"
+ " Lubitz was suicidal or acting aggressively before the crash. Investigators are looking into whether"
+ " Lubitz feared his medical condition would cause him to lose his pilot's license, a European"
+ ' government official briefed on the investigation told CNN on Tuesday. While flying was "a big part'
+ " of his life,\" the source said, it's only one theory being considered. Another source, a law"
+ " enforcement official briefed on the investigation, also told CNN that authorities believe the"
+ " primary motive for Lubitz to bring down the plane was that he feared he would not be allowed to fly"
+ " because of his medical problems. Lubitz's girlfriend told investigators he had seen an eye doctor"
+ " and a neuropsychologist, both of whom deemed him unfit to work recently and concluded he had"
+ " psychological issues, the European government official said. But no matter what details emerge about"
+ " his previous mental health struggles, there's more to the story, said Brian Russell, a forensic"
+ ' psychologist. "Psychology can explain why somebody would turn rage inward on themselves about the'
+ " fact that maybe they weren't going to keep doing their job and they're upset about that and so"
+ ' they\'re suicidal," he said. "But there is no mental illness that explains why somebody then feels'
+ " entitled to also take that rage and turn it outward on 149 other people who had nothing to do with"
+ " the person's problems.\" Germanwings crash compensation: What we know . Who was the captain of"
+ " Germanwings Flight 9525? CNN's Margot Haddad reported from Marseille and Pamela Brown from"
+ " Dusseldorf, while Laura Smith-Spark wrote from London. CNN's Frederik Pleitgen, Pamela Boykoff,"
+ " Antonia Mortensen, Sandrine Amiel and Anna-Maja Rappard contributed to this report.",
+ ],
+ return_tensors="pd",
+ padding="longest",
+ truncation=True,
+ )
+ generated_ids = self.xsum_1_1_model.generate(**batch, num_beams=4)
+ result = self.tok.batch_decode(generated_ids, skip_special_tokens=True)
+ assert (
+ result[0] ==
+ " The International Criminal Court (ICC) has announced that it has been announced by the International"
+ " Criminal court.")
+ assert (
+ result[1] ==
+ " An investigation into the crash that killed at least 10 people in the French capital has been"
+ " released by the French police investigating the crash.")
+
+
+class BartModelIntegrationTests(unittest.TestCase):
+
+ def default_tokenizer(self):
+ return BartTokenizer.from_pretrained("bart-large")
+
+ @slow
+ def test_inference_no_head(self):
+ model = BartModel.from_pretrained("bart-large")
+ model.eval()
+ input_ids = paddle.to_tensor(
+ [[0, 31414, 232, 328, 740, 1140, 12695, 69, 46078, 1588, 2]],
+ dtype="int64")
+
+ attention_mask = paddle.cast(
+ input_ids == model.config["pad_token_id"],
+ dtype=paddle.get_default_dtype()).unsqueeze([1, 2]) * -1e4
+ with paddle.no_grad():
+ output = model(input_ids=input_ids, attention_mask=attention_mask)
+ expected_shape = [1, 11, 1024]
+ self.assertEqual(output.shape, expected_shape)
+
+ @slow
+ def test_cnn_summarization_same_as_fairseq(self):
+
+ model = BartForConditionalGeneration.from_pretrained("bart-large")
+ model.eval()
+ tok = BartTokenizer.from_pretrained("bart-large")
+
+ FRANCE_ARTICLE = ( # @noq
+ " Marseille, France (CNN)The French prosecutor leading an investigation into the crash of Germanwings"
+ " Flight 9525 insisted Wednesday that he was not aware of any video footage from on board the plane."
+ ' Marseille prosecutor Brice Robin told CNN that "so far no videos were used in the crash investigation."'
+ ' He added, "A person who has such a video needs to immediately give it to the investigators." Robin\'s'
+ " comments follow claims by two magazines, German daily Bild and French Paris Match, of a cell phone video"
+ " showing the harrowing final seconds from on board Germanwings Flight 9525 as it crashed into the French"
+ " Alps. All 150 on board were killed. Paris Match and Bild reported that the video was recovered from a"
+ " phone at the wreckage site. The two publications described the supposed video, but did not post it on"
+ " their websites. The publications said that they watched the video, which was found by a source close to"
+ " the investigation. \"One can hear cries of 'My God' in several languages,\" Paris Match reported."
+ ' "Metallic banging can also be heard more than three times, perhaps of the pilot trying to open the'
+ " cockpit door with a heavy object. Towards the end, after a heavy shake, stronger than the others, the"
+ ' screaming intensifies. Then nothing." "It is a very disturbing scene," said Julian Reichelt,'
+ " editor-in-chief of Bild online. An official with France's accident investigation agency, the BEA, said"
+ " the agency is not aware of any such video. Lt. Col. Jean-Marc Menichini, a French Gendarmerie spokesman"
+ " in charge of communications on rescue efforts around the Germanwings crash site, told CNN that the"
+ ' reports were "completely wrong" and "unwarranted." Cell phones have been collected at the site, he said,'
+ ' but that they "hadn\'t been exploited yet." Menichini said he believed the cell phones would need to be'
+ " sent to the Criminal Research Institute in Rosny sous-Bois, near Paris, in order to be analyzed by"
+ " specialized technicians working hand-in-hand with investigators. But none of the cell phones found so"
+ " far have been sent to the institute, Menichini said. Asked whether staff involved in the search could"
+ ' have leaked a memory card to the media, Menichini answered with a categorical "no." Reichelt told "Erin'
+ ' Burnett: Outfront" that he had watched the video and stood by the report, saying Bild and Paris Match'
+ ' are "very confident" that the clip is real. He noted that investigators only revealed they\'d recovered'
+ ' cell phones from the crash site after Bild and Paris Match published their reports. "That is something'
+ " we did not know before. ... Overall we can say many things of the investigation weren't revealed by the"
+ ' investigation at the beginning," he said. What was mental state of Germanwings co-pilot? German airline'
+ " Lufthansa confirmed Tuesday that co-pilot Andreas Lubitz had battled depression years before he took the"
+ " controls of Germanwings Flight 9525, which he's accused of deliberately crashing last week in the"
+ ' French Alps. Lubitz told his Lufthansa flight training school in 2009 that he had a "previous episode of'
+ ' severe depression," the airline said Tuesday. Email correspondence between Lubitz and the school'
+ " discovered in an internal investigation, Lufthansa said, included medical documents he submitted in"
+ " connection with resuming his flight training. The announcement indicates that Lufthansa, the parent"
+ " company of Germanwings, knew of Lubitz's battle with depression, allowed him to continue training and"
+ " ultimately put him in the cockpit. Lufthansa, whose CEO Carsten Spohr previously said Lubitz was 100%"
+ ' fit to fly, described its statement Tuesday as a "swift and seamless clarification" and said it was'
+ " sharing the information and documents -- including training and medical records -- with public"
+ " prosecutors. Spohr traveled to the crash site Wednesday, where recovery teams have been working for the"
+ " past week to recover human remains and plane debris scattered across a steep mountainside. He saw the"
+ " crisis center set up in Seyne-les-Alpes, laid a wreath in the village of Le Vernet, closer to the crash"
+ " site, where grieving families have left flowers at a simple stone memorial. Menichini told CNN late"
+ " Tuesday that no visible human remains were left at the site but recovery teams would keep searching."
+ " French President Francois Hollande, speaking Tuesday, said that it should be possible to identify all"
+ " the victims using DNA analysis by the end of the week, sooner than authorities had previously suggested."
+ " In the meantime, the recovery of the victims' personal belongings will start Wednesday, Menichini said."
+ " Among those personal belongings could be more cell phones belonging to the 144 passengers and six crew"
+ " on board. Check out the latest from our correspondents . The details about Lubitz's correspondence with"
+ " the flight school during his training were among several developments as investigators continued to"
+ " delve into what caused the crash and Lubitz's possible motive for downing the jet. A Lufthansa"
+ " spokesperson told CNN on Tuesday that Lubitz had a valid medical certificate, had passed all his"
+ ' examinations and "held all the licenses required." Earlier, a spokesman for the prosecutor\'s office in'
+ " Dusseldorf, Christoph Kumpa, said medical records reveal Lubitz suffered from suicidal tendencies at"
+ " some point before his aviation career and underwent psychotherapy before he got his pilot's license."
+ " Kumpa emphasized there's no evidence suggesting Lubitz was suicidal or acting aggressively before the"
+ " crash. Investigators are looking into whether Lubitz feared his medical condition would cause him to"
+ " lose his pilot's license, a European government official briefed on the investigation told CNN on"
+ ' Tuesday. While flying was "a big part of his life," the source said, it\'s only one theory being'
+ " considered. Another source, a law enforcement official briefed on the investigation, also told CNN that"
+ " authorities believe the primary motive for Lubitz to bring down the plane was that he feared he would"
+ " not be allowed to fly because of his medical problems. Lubitz's girlfriend told investigators he had"
+ " seen an eye doctor and a neuropsychologist, both of whom deemed him unfit to work recently and concluded"
+ " he had psychological issues, the European government official said. But no matter what details emerge"
+ " about his previous mental health struggles, there's more to the story, said Brian Russell, a forensic"
+ ' psychologist. "Psychology can explain why somebody would turn rage inward on themselves about the fact'
+ " that maybe they weren't going to keep doing their job and they're upset about that and so they're"
+ ' suicidal," he said. "But there is no mental illness that explains why somebody then feels entitled to'
+ " also take that rage and turn it outward on 149 other people who had nothing to do with the person's"
+ ' problems." Germanwings crash compensation: What we know . Who was the captain of Germanwings Flight'
+ " 9525? CNN's Margot Haddad reported from Marseille and Pamela Brown from Dusseldorf, while Laura"
+ " Smith-Spark wrote from London. CNN's Frederik Pleitgen, Pamela Boykoff, Antonia Mortensen, Sandrine"
+ " Amiel and Anna-Maja Rappard contributed to this report.")
+
+ SHORTER_ARTICLE = (
+ " (CNN)The Palestinian Authority officially became the 123rd member of the International Criminal Court on"
+ " Wednesday, a step that gives the court jurisdiction over alleged crimes in Palestinian territories. The"
+ " formal accession was marked with a ceremony at The Hague, in the Netherlands, where the court is based."
+ " The Palestinians signed the ICC's founding Rome Statute in January, when they also accepted its"
+ ' jurisdiction over alleged crimes committed "in the occupied Palestinian territory, including East'
+ ' Jerusalem, since June 13, 2014." Later that month, the ICC opened a preliminary examination into the'
+ " situation in Palestinian territories, paving the way for possible war crimes investigations against"
+ " Israelis. As members of the court, Palestinians may be subject to counter-charges as well. Israel and"
+ " the United States, neither of which is an ICC member, opposed the Palestinians' efforts to join the"
+ " body. But Palestinian Foreign Minister Riad al-Malki, speaking at Wednesday's ceremony, said it was a"
+ ' move toward greater justice. "As Palestine formally becomes a State Party to the Rome Statute today, the'
+ ' world is also a step closer to ending a long era of impunity and injustice," he said, according to an'
+ ' ICC news release. "Indeed, today brings us closer to our shared goals of justice and peace." Judge'
+ " Kuniko Ozaki, a vice president of the ICC, said acceding to the treaty was just the first step for the"
+ ' Palestinians. "As the Rome Statute today enters into force for the State of Palestine, Palestine'
+ " acquires all the rights as well as responsibilities that come with being a State Party to the Statute."
+ ' These are substantive commitments, which cannot be taken lightly," she said. Rights group Human Rights'
+ ' Watch welcomed the development. "Governments seeking to penalize Palestine for joining the ICC should'
+ " immediately end their pressure, and countries that support universal acceptance of the court's treaty"
+ ' should speak out to welcome its membership," said Balkees Jarrah, international justice counsel for the'
+ " group. \"What's objectionable is the attempts to undermine international justice, not Palestine's"
+ ' decision to join a treaty to which over 100 countries around the world are members." In January, when'
+ " the preliminary ICC examination was opened, Israeli Prime Minister Benjamin Netanyahu described it as an"
+ ' outrage, saying the court was overstepping its boundaries. The United States also said it "strongly"'
+ " disagreed with the court's decision. \"As we have said repeatedly, we do not believe that Palestine is a"
+ ' state and therefore we do not believe that it is eligible to join the ICC," the State Department said in'
+ ' a statement. It urged the warring sides to resolve their differences through direct negotiations. "We'
+ ' will continue to oppose actions against Israel at the ICC as counterproductive to the cause of peace,"'
+ " it said. But the ICC begs to differ with the definition of a state for its purposes and refers to the"
+ ' territories as "Palestine." While a preliminary examination is not a formal investigation, it allows the'
+ " court to review evidence and determine whether to investigate suspects on both sides. Prosecutor Fatou"
+ ' Bensouda said her office would "conduct its analysis in full independence and impartiality." The war'
+ " between Israel and Hamas militants in Gaza last summer left more than 2,000 people dead. The inquiry"
+ " will include alleged war crimes committed since June. The International Criminal Court was set up in"
+ " 2002 to prosecute genocide, crimes against humanity and war crimes. CNN's Vasco Cotovio, Kareem Khadder"
+ " and Faith Karimi contributed to this report.")
+
+ # The below article tests that we don't add any hypotheses outside of the top n_beams
+ IRAN_ARTICLE = (
+ " (CNN)The United States and its negotiating partners reached a very strong framework agreement with Iran"
+ " in Lausanne, Switzerland, on Thursday that limits Iran's nuclear program in such a way as to effectively"
+ " block it from building a nuclear weapon. Expect pushback anyway, if the recent past is any harbinger."
+ " Just last month, in an attempt to head off such an agreement, House Speaker John Boehner invited Israeli"
+ " Prime Minister Benjamin Netanyahu to preemptively blast it before Congress, and 47 senators sent a"
+ " letter to the Iranian leadership warning them away from a deal. The debate that has already begun since"
+ " the announcement of the new framework will likely result in more heat than light. It will not be helped"
+ " by the gathering swirl of dubious assumptions and doubtful assertions. Let us address some of these: ."
+ " The most misleading assertion, despite universal rejection by experts, is that the negotiations'"
+ " objective at the outset was the total elimination of any nuclear program in Iran. That is the position"
+ " of Netanyahu and his acolytes in the U.S. Congress. But that is not and never was the objective. If it"
+ " had been, there would have been no Iranian team at the negotiating table. Rather, the objective has"
+ " always been to structure an agreement or series of agreements so that Iran could not covertly develop a"
+ " nuclear arsenal before the United States and its allies could respond. The new framework has exceeded"
+ " expectations in achieving that goal. It would reduce Iran's low-enriched uranium stockpile, cut by"
+ " two-thirds its number of installed centrifuges and implement a rigorous inspection regime. Another"
+ " dubious assumption of opponents is that the Iranian nuclear program is a covert weapons program. Despite"
+ " sharp accusations by some in the United States and its allies, Iran denies having such a program, and"
+ " U.S. intelligence contends that Iran has not yet made the decision to build a nuclear weapon. Iran's"
+ " continued cooperation with International Atomic Energy Agency inspections is further evidence on this"
+ " point, and we'll know even more about Iran's program in the coming months and years because of the deal."
+ " In fact, the inspections provisions that are part of this agreement are designed to protect against any"
+ " covert action by the Iranians. What's more, the rhetoric of some members of Congress has implied that"
+ " the negotiations have been between only the United States and Iran (i.e., the 47 senators' letter"
+ " warning that a deal might be killed by Congress or a future president). This of course is not the case."
+ " The talks were between Iran and the five permanent members of the U.N. Security Council (United States,"
+ " United Kingdom, France, China and Russia) plus Germany, dubbed the P5+1. While the United States has"
+ " played a leading role in the effort, it negotiated the terms alongside its partners. If the agreement"
+ " reached by the P5+1 is rejected by Congress, it could result in an unraveling of the sanctions on Iran"
+ " and threaten NATO cohesion in other areas. Another questionable assertion is that this agreement"
+ " contains a sunset clause, after which Iran will be free to do as it pleases. Again, this is not the"
+ " case. Some of the restrictions on Iran's nuclear activities, such as uranium enrichment, will be eased"
+ " or eliminated over time, as long as 15 years. But most importantly, the framework agreement includes"
+ " Iran's ratification of the Additional Protocol, which allows IAEA inspectors expanded access to nuclear"
+ " sites both declared and nondeclared. This provision will be permanent. It does not sunset. Thus, going"
+ " forward, if Iran decides to enrich uranium to weapons-grade levels, monitors will be able to detect such"
+ " a move in a matter of days and alert the U.N. Security Council. Many in Congress have said that the"
+ ' agreement should be a formal treaty requiring the Senate to "advise and consent." But the issue is not'
+ " suited for a treaty. Treaties impose equivalent obligations on all signatories. For example, the New"
+ " START treaty limits Russia and the United States to 1,550 deployed strategic warheads. But any agreement"
+ " with Iran will not be so balanced. The restrictions and obligations in the final framework agreement"
+ " will be imposed almost exclusively on Iran. The P5+1 are obligated only to ease and eventually remove"
+ " most but not all economic sanctions, which were imposed as leverage to gain this final deal. Finally"
+ " some insist that any agreement must address Iranian missile programs, human rights violations or support"
+ " for Hamas or Hezbollah. As important as these issues are, and they must indeed be addressed, they are"
+ " unrelated to the most important aim of a nuclear deal: preventing a nuclear Iran. To include them in"
+ " the negotiations would be a poison pill. This agreement should be judged on its merits and on how it"
+ " affects the security of our negotiating partners and allies, including Israel. Those judgments should be"
+ " fact-based, not based on questionable assertions or dubious assumptions."
+ )
+
+ ARTICLE_SUBWAY = (
+ " 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."
+ )
+
+ dct = tok._batch_encode_plus(
+ [FRANCE_ARTICLE, SHORTER_ARTICLE, IRAN_ARTICLE, ARTICLE_SUBWAY],
+ max_length=1024,
+ padding_strategy=PaddingStrategy("max_length"),
+ truncation_strategy=TruncationStrategy("only_first"),
+ return_tensors="pd",
+ return_attention_mask=True,
+ )
+
+ self.assertEqual(1024, dct["input_ids"].shape[1])
+ hypotheses_batch, _ = model.generate(
+ input_ids=dct["input_ids"],
+ attention_mask=dct["attention_mask"],
+ num_beams=2,
+ decode_strategy="beam_search",
+ max_length=1024,
+ )
+
+ EXPECTED = [
+ "A French prosecutor says he is not aware of any video footage from on board the plane. Two German "
+ "magazines claim to have found a cell phone video showing the crash. The publications say they watched "
+ "the video, which was found by a source close to the investigation. All 150 on board Germanwings Flight "
+ "9525 were killed.",
+ "Palestinian Authority becomes 123rd member of the International Criminal Court. The move gives the court "
+ "jurisdiction over alleged crimes in Palestinian territories. Israel and the United States opposed the "
+ "Palestinians' efforts to join the body. But Palestinian Foreign Minister Riad al-Malki said it was a "
+ "move toward greater justice.",
+ "U.S. and its negotiating partners reached a strong framework agreement with Iran. Peter Bergen: The "
+ "debate that has already begun will likely result in more heat than light. He says critics have made "
+ "dubious assumptions and doubtful assertions. Bergen says the goal was to block Iran from building a "
+ "nuclear weapon.",
+ "Liana Barrientos, 39, has been married 10 times, sometimes within two weeks of each other. Prosecutors "
+ "say the marriages were part of an immigration scam. She pleaded not guilty at State Supreme Court in the "
+ "Bronx on Friday. If convicted, she faces up to four years in prison.",
+ ]
+
+ generated_summaries = tok.batch_decode(
+ hypotheses_batch.tolist(),
+ clean_up_tokenization_spaces=True,
+ skip_special_tokens=True)
diff --git a/tests/transformers/bart/test_tokenizer.py b/tests/transformers/bart/test_tokenizer.py
new file mode 100644
index 000000000000..79a94f3da984
--- /dev/null
+++ b/tests/transformers/bart/test_tokenizer.py
@@ -0,0 +1,181 @@
+# Copyright (c) 2022 PaddlePaddle Authors. All Rights Reserved.
+# Copyright 2020 The HuggingFace Team. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+import json
+import os
+import unittest
+import tempfile
+import shutil
+
+from paddlenlp.transformers import BartTokenizer
+
+from ..test_tokenizer_common import TokenizerTesterMixin, filter_roberta_detectors
+
+VOCAB_FILES_NAMES = {
+ "vocab_file": "vocab.json",
+ "merges_file": "merges.txt",
+}
+
+
+class TestTokenizationBart(TokenizerTesterMixin, unittest.TestCase):
+ tokenizer_class = BartTokenizer
+ test_rust_tokenizer = False
+ from_pretrained_filter = filter_roberta_detectors
+
+ # from_pretrained_kwargs = {'add_prefix_space': True}
+
+ def setUp(self):
+ super().setUp()
+ vocab = [
+ "l",
+ "o",
+ "w",
+ "e",
+ "r",
+ "s",
+ "t",
+ "i",
+ "d",
+ "n",
+ "\u0120",
+ "\u0120l",
+ "\u0120n",
+ "\u0120lo",
+ "\u0120low",
+ "er",
+ "\u0120lowest",
+ "\u0120newer",
+ "\u0120wider",
+ "",
+ "",
+ "",
+ "",
+ "",
+ ]
+ vocab_tokens = dict(zip(vocab, range(len(vocab))))
+ merges = [
+ "#version: 0.2", "\u0120 l", "\u0120l o", "\u0120lo w", "e r", ""
+ ]
+ self.special_tokens_map = {
+ "bos_token": "",
+ "eos_token": "",
+ "cls_token": "",
+ "sep_token": "",
+ "unk_token": "",
+ "pad_token": "",
+ "mask_token": ""
+ }
+
+ self.vocab_file = os.path.join(self.tmpdirname,
+ VOCAB_FILES_NAMES["vocab_file"])
+ self.merges_file = os.path.join(self.tmpdirname,
+ VOCAB_FILES_NAMES["merges_file"])
+ with open(self.vocab_file, "w", encoding="utf-8") as fp:
+ fp.write(json.dumps(vocab_tokens) + "\n")
+ with open(self.merges_file, "w", encoding="utf-8") as fp:
+ fp.write("\n".join(merges))
+
+ def get_tokenizer(self, **kwargs):
+ kwargs.update(self.special_tokens_map)
+ return self.tokenizer_class.from_pretrained(self.tmpdirname, **kwargs)
+
+ def get_input_output_texts(self, tokenizer):
+ return "lower newer", "lower newer"
+
+ def default_tokenizer(self):
+ return BartTokenizer.from_pretrained("bart-large")
+
+ def test_prepare_batch(self):
+ src_text = [
+ "A long paragraph for summarization.",
+ "Another paragraph for summarization."
+ ]
+ expected_src_tokens = [0, 250, 251, 17818, 13, 39186, 1938, 4, 2]
+
+ for tokenizer in [BartTokenizer.from_pretrained("bart-large")]:
+ batch = tokenizer(text=src_text,
+ max_length=len(expected_src_tokens),
+ padding=True,
+ return_attention_mask=True,
+ return_tensors="pd")
+ self.assertEqual([2, 9], batch.input_ids.shape)
+ self.assertEqual([2, 9], batch.attention_mask.shape)
+ result = batch.input_ids.tolist()[0]
+ self.assertListEqual(expected_src_tokens, result)
+ # Test that special tokens are reset
+
+ def test_prepare_batch_empty_target_text(self):
+ src_text = [
+ "A long paragraph for summarization.",
+ "Another paragraph for summarization."
+ ]
+ for tokenizer in [BartTokenizer.from_pretrained("bart-large")]:
+ batch = tokenizer(text=src_text,
+ padding=True,
+ return_tensors="pd",
+ return_attention_mask=True)
+ # check if input_ids are returned and no labels
+ self.assertIn("input_ids", batch)
+ self.assertIn("attention_mask", batch)
+ self.assertNotIn("labels", batch)
+ self.assertNotIn("decoder_attention_mask", batch)
+
+ def test_tokenizer_as_target_length(self):
+ tgt_text = [
+ "Summary of the text.",
+ "Another summary.",
+ ]
+ for tokenizer in [BartTokenizer.from_pretrained("bart-large")]:
+ targets = tokenizer(text=tgt_text,
+ max_length=32,
+ padding="max_length",
+ return_tensors="pd")
+ self.assertEqual(32, targets["input_ids"].shape[1])
+
+ def test_prepare_batch_not_longer_than_maxlen(self):
+ for tokenizer in [
+ BartTokenizer.from_pretrained("bart-large", max_len=1024)
+ ]:
+ batch = tokenizer(
+ text=["I am a small frog" * 1024, "I am a small frog"],
+ padding=True,
+ truncation=True,
+ return_tensors="pd")
+ self.assertEqual(batch.input_ids.shape, [2, 1024])
+
+ def test_special_tokens(self):
+
+ src_text = ["A long paragraph for summarization."]
+ tgt_text = [
+ "Summary of the text.",
+ ]
+ for tokenizer in [BartTokenizer.from_pretrained("bart-large")]:
+ inputs = tokenizer(text=src_text, return_tensors="pd")
+ targets = tokenizer(text=tgt_text, return_tensors="pd")
+ input_ids = inputs["input_ids"]
+ labels = targets["input_ids"]
+ self.assertTrue(
+ (input_ids[:, 0] == tokenizer.bos_token_id).all().item())
+ self.assertTrue((labels[:,
+ 0] == tokenizer.bos_token_id).all().item())
+ self.assertTrue(
+ (input_ids[:, -1] == tokenizer.eos_token_id).all().item())
+ self.assertTrue((labels[:,
+ -1] == tokenizer.eos_token_id).all().item())
+
+ def test_pretokenized_inputs(self):
+ pass
+
+ def test_offsets_mapping(self):
+ pass
diff --git a/tests/transformers/bert/test_tokenizer.py b/tests/transformers/bert/test_tokenizer.py
index 5e9a5aca110e..ab4a05a9ff9c 100644
--- a/tests/transformers/bert/test_tokenizer.py
+++ b/tests/transformers/bert/test_tokenizer.py
@@ -34,7 +34,7 @@ class BertTokenizationTest(TokenizerTesterMixin, unittest.TestCase):
tokenizer_class = BertTokenizer
space_between_special_tokens = True
from_pretrained_filter = filter_non_english
- test_seq2seq = True
+ test_seq2seq = False
def setUp(self):
super().setUp()
diff --git a/tests/transformers/test_generation_utils.py b/tests/transformers/test_generation_utils.py
new file mode 100644
index 000000000000..bcf91c33ba42
--- /dev/null
+++ b/tests/transformers/test_generation_utils.py
@@ -0,0 +1,1088 @@
+# Copyright (c) 2022 PaddlePaddle Authors. All Rights Reserved.
+# Copyright 2021, The HuggingFace Inc. team. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+import inspect
+import unittest
+import numpy as np
+import random
+
+from tests.testing_utils import slow
+
+from .test_modeling_common import floats_tensor, ids_tensor
+
+import paddle
+from paddlenlp.transformers import (
+ BartForConditionalGeneration,
+ BartTokenizer,
+)
+from paddlenlp.transformers.generation_utils import (
+ BeamSearchScorer, MinLengthLogitsProcessor,
+ RepetitionPenaltyLogitsProcessor, HammingDiversityLogitsProcessor,
+ ForcedBOSTokenLogitsProcessor, ForcedEOSTokenLogitsProcessor, TopKProcess,
+ TopPProcess, LogitsProcessorList)
+
+
+def top_k_top_p_filtering(
+ logits,
+ top_k=0,
+ top_p=1.0,
+ min_tokens_to_keep=1,
+):
+ if top_k > 0:
+ logits = TopKProcess(logits, top_k, min_tokens_to_keep)
+
+ if 0 <= top_p <= 1.0:
+ logits = TopPProcess(logits, top_p, min_tokens_to_keep)
+
+ return logits
+
+
+class GenerationTesterMixin:
+ model_tester = None
+ # all_pretrained_model = []
+ # all_pretrained_model_name = []
+ all_generative_model_classes = {}
+ input_name = "input_ids"
+ is_encoder_decoder = False
+
+ def _get_input_ids_and_config(self):
+ config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common(
+ )
+
+ input_ids = inputs_dict[self.input_name]
+ attention_mask = paddle.zeros_like(input_ids, dtype=paddle.int64)
+
+ max_batch_size = 2
+ sequence_length = input_ids.shape[-1] // 2
+ input_ids = input_ids[:max_batch_size, :sequence_length]
+ attention_mask = attention_mask[:max_batch_size, :
+ sequence_length].unsqueeze([1, 2])
+
+ # generate max 3 tokens
+ max_length = 3
+ if config["eos_token_id"] is not None and config["pad_token_id"] is None:
+ # hack to allow generate for models such as GPT2 as is done in `generate()`
+ config["pad_token_id"] = config["eos_token_id"]
+ return config, input_ids, attention_mask, max_length
+
+ @staticmethod
+ def _get_logits_processor_and_kwargs(
+ eos_token_id,
+ forced_bos_token_id=None,
+ forced_eos_token_id=None,
+ max_length=None,
+ diversity_penalty=None,
+ ):
+ process_kwargs = {
+ "min_length": 1 if max_length is None else max_length - 1,
+ "repetition_penalty": 1.2,
+ }
+
+ if diversity_penalty is not None:
+ process_kwargs["diversity_rate"] = diversity_penalty
+ logits_processor = LogitsProcessorList(([
+ HammingDiversityLogitsProcessor(
+ diversity_penalty, num_beams=2, num_beam_groups=2),
+ ] if diversity_penalty is not None else []) + ([
+ MinLengthLogitsProcessor(process_kwargs["min_length"], eos_token_id
+ ),
+ ] if eos_token_id is not None else []) + ([
+ ForcedBOSTokenLogitsProcessor(forced_bos_token_id),
+ ] if forced_bos_token_id is not None else []) + (
+ [ForcedEOSTokenLogitsProcessor(max_length, forced_eos_token_id)]
+ if forced_eos_token_id is not None else []) + [
+ RepetitionPenaltyLogitsProcessor(
+ process_kwargs["repetition_penalty"]),
+ ])
+ return process_kwargs, logits_processor
+
+ @staticmethod
+ def _get_warper_and_kwargs():
+ warp_kwargs = {"top_k": 10, "top_p": 0.7, "temperature": 0.7}
+ return warp_kwargs
+
+ @staticmethod
+ def _get_beam_scorer_and_kwargs(batch_size,
+ max_length,
+ num_return_sequences=1):
+ beam_kwargs = {
+ "early_stopping": False,
+ "length_penalty": 2.0,
+ "num_beams": 2,
+ "num_return_sequences": num_return_sequences,
+ }
+ beam_scorer = BeamSearchScorer(
+ batch_size=batch_size,
+ max_length=max_length,
+ num_beams=beam_kwargs["num_beams"],
+ length_penalty=beam_kwargs["length_penalty"],
+ do_early_stopping=beam_kwargs["early_stopping"],
+ num_beam_hyps_to_keep=num_return_sequences,
+ )
+ return beam_kwargs, beam_scorer
+
+ @staticmethod
+ def _get_diverse_beam_scorer_and_kwargs(batch_size,
+ max_length,
+ num_return_sequences=1):
+ beam_kwargs = {
+ "early_stopping": False,
+ "length_penalty": 2.0,
+ "num_beams": 2,
+ "num_return_sequences": num_return_sequences,
+ "num_beam_groups": 2, # one beam per group
+ "diversity_penalty": 2.0,
+ }
+ beam_scorer = BeamSearchScorer(
+ batch_size=batch_size,
+ max_length=max_length,
+ num_beams=beam_kwargs["num_beams"],
+ length_penalty=beam_kwargs["length_penalty"],
+ do_early_stopping=beam_kwargs["early_stopping"],
+ num_beam_hyps_to_keep=num_return_sequences,
+ num_beam_groups=beam_kwargs["num_beam_groups"],
+ )
+ return beam_kwargs, beam_scorer
+
+ @staticmethod
+ def _get_encoder_outputs(
+ model,
+ input_ids,
+ attention_mask,
+ output_attentions=None,
+ output_hidden_states=None,
+ num_interleave=1,
+ ):
+ model.eval()
+ encoder = model.get_encoder()
+ encoder_outputs = encoder(
+ input_ids,
+ attention_mask=attention_mask,
+ )
+ encoder_outputs = encoder_outputs.repeat_interleave(num_interleave,
+ axis=0)
+
+ input_ids = paddle.zeros_like(
+ input_ids[:, :1],
+ dtype="int64") + model.get_decoder_start_token_id()
+ # attention_mask = None
+ return encoder_outputs, input_ids, attention_mask
+
+ def _greedy_generate(
+ self,
+ model,
+ input_ids,
+ attention_mask,
+ max_length,
+ ):
+ if self.is_encoder_decoder:
+ max_length = 4
+ logits_process_kwargs, logits_processor = self._get_logits_processor_and_kwargs(
+ eos_token_id=getattr(
+ model, model.base_model_prefix).config["eos_token_id"],
+ forced_bos_token_id=getattr(
+ getattr(model, model.base_model_prefix).config,
+ "forced_bos_token_id", None),
+ forced_eos_token_id=getattr(
+ getattr(model, model.base_model_prefix).config,
+ "forced_eos_token_id", None),
+ max_length=max_length,
+ )
+
+ kwargs = {}
+
+ with paddle.no_grad():
+ output_generate = model.generate(
+ input_ids,
+ max_length=max_length,
+ decode_strategy='greedy_search',
+ attention_mask=attention_mask,
+ **logits_process_kwargs,
+ )
+
+ if self.is_encoder_decoder:
+ encoder_outputs, input_ids, attention_mask = self._get_encoder_outputs(
+ model,
+ input_ids,
+ attention_mask,
+ )
+ kwargs["encoder_output"] = encoder_outputs
+
+ with paddle.no_grad():
+ output_greedy = model.greedy_search(
+ input_ids,
+ max_length=max_length + 1,
+ attention_mask=attention_mask,
+ logits_processors=logits_processor,
+ pad_token_id=getattr(
+ model, model.base_model_prefix).config["pad_token_id"],
+ eos_token_id=getattr(
+ model, model.base_model_prefix).config["eos_token_id"],
+ **kwargs,
+ )
+ return output_greedy, output_generate
+
+ def _sample_generate(
+ self,
+ model,
+ input_ids,
+ attention_mask,
+ max_length,
+ num_return_sequences,
+ logits_processors,
+ logits_warper,
+ process_kwargs,
+ ):
+ with paddle.no_grad():
+ output_generate = model.generate(
+ input_ids,
+ max_length=max_length,
+ decode_strategy='sampling',
+ num_return_sequences=num_return_sequences,
+ attention_mask=attention_mask,
+ top_k=1,
+ **process_kwargs,
+ )
+
+ kwargs = {}
+ if self.is_encoder_decoder:
+ encoder_outputs, input_ids_clone, attention_mask_clone = self._get_encoder_outputs(
+ model,
+ input_ids,
+ attention_mask,
+ num_interleave=num_return_sequences,
+ )
+ kwargs["encoder_output"] = encoder_outputs
+ input_ids_clone = input_ids_clone.repeat_interleave(
+ num_return_sequences, axis=0)
+ attention_mask_clone = attention_mask_clone.repeat_interleave(
+ num_return_sequences, axis=0)
+ else:
+ attention_mask_clone = attention_mask.repeat_interleave(
+ num_return_sequences, axis=0)
+ input_ids_clone = input_ids.repeat_interleave(num_return_sequences,
+ axis=0)
+
+ with paddle.no_grad():
+ output_sample = model.sample(
+ input_ids_clone,
+ attention_mask=attention_mask_clone,
+ max_length=max_length +
+ 1 if self.is_encoder_decoder else max_length +
+ input_ids.shape[0],
+ logits_processors=logits_processors,
+ pad_token_id=getattr(
+ model, model.base_model_prefix).config["pad_token_id"],
+ eos_token_id=getattr(
+ model, model.base_model_prefix).config["eos_token_id"],
+ top_k=1,
+ **process_kwargs,
+ **kwargs,
+ )
+ return output_sample, output_generate
+
+ def _beam_search_generate(
+ self,
+ model,
+ input_ids,
+ attention_mask,
+ max_length,
+ beam_scorer,
+ beam_kwargs,
+ logits_processor,
+ logits_process_kwargs,
+ ):
+ with paddle.no_grad():
+ output_generate = model.generate(
+ input_ids,
+ decode_strategy='beam_search',
+ attention_mask=attention_mask,
+ max_length=max_length,
+ **beam_kwargs,
+ **logits_process_kwargs,
+ )
+
+ # beam_search does not automatically interleave `batch_size` dim for `num_beams`
+ kwargs = {}
+ if self.is_encoder_decoder:
+ encoder_outputs, input_ids_clone, attention_mask_clone = self._get_encoder_outputs(
+ model,
+ input_ids,
+ attention_mask,
+ num_interleave=beam_scorer.num_beams,
+ )
+ kwargs["encoder_output"] = encoder_outputs
+ input_ids_clone = input_ids_clone.repeat_interleave(
+ beam_scorer.num_beams, axis=0)
+ attention_mask_clone = attention_mask_clone.repeat_interleave(
+ beam_scorer.num_beams, axis=0)
+ else:
+ attention_mask_clone = attention_mask.repeat_interleave(
+ beam_scorer.num_beams, axis=0)
+ input_ids_clone = input_ids.repeat_interleave(beam_scorer.num_beams,
+ axis=0)
+
+ kwargs["use_cache"] = True
+
+ with paddle.no_grad():
+ output_beam_search = model.beam_search(
+ input_ids_clone,
+ beam_scorer,
+ max_length=max_length + 1,
+ attention_mask=attention_mask_clone,
+ logits_processors=logits_processor,
+ diversity_rate=getattr(logits_process_kwargs, "diversity_rate",
+ 0.0),
+ pad_token_id=getattr(
+ model, model.base_model_prefix).config["pad_token_id"],
+ eos_token_id=getattr(
+ model, model.base_model_prefix).config["eos_token_id"],
+ **kwargs,
+ )
+ return output_generate, output_beam_search
+
+ def _group_beam_search_generate(
+ self,
+ model,
+ input_ids,
+ attention_mask,
+ max_length,
+ beam_scorer,
+ beam_kwargs,
+ logits_processor,
+ logits_process_kwargs,
+ ):
+ model.eval()
+ with paddle.no_grad():
+ output_generate = model.generate(
+ input_ids,
+ decode_strategy='beam_search',
+ attention_mask=attention_mask,
+ max_length=max_length,
+ **beam_kwargs,
+ **logits_process_kwargs,
+ )
+
+ # group_beam_search does not automatically interleave `batch_size` dim for `num_beams`
+ kwargs = {}
+ if self.is_encoder_decoder:
+ encoder_outputs, input_ids_clone, attention_mask_clone = self._get_encoder_outputs(
+ model,
+ input_ids,
+ attention_mask,
+ num_interleave=beam_scorer.num_beams,
+ )
+ kwargs["encoder_output"] = encoder_outputs
+ input_ids_clone = input_ids_clone.repeat_interleave(
+ beam_scorer.num_beams, axis=0)
+ attention_mask_clone = attention_mask_clone.repeat_interleave(
+ beam_scorer.num_beams, axis=0)
+ else:
+ attention_mask_clone = attention_mask.repeat_interleave(
+ beam_scorer.num_beams, axis=0)
+ input_ids_clone = input_ids.repeat_interleave(beam_scorer.num_beams,
+ axis=0)
+
+ kwargs["use_cache"] = True
+
+ with paddle.no_grad():
+ output_group_beam_search = model.group_beam_search(
+ input_ids_clone,
+ beam_scorer,
+ max_length=max_length + 1,
+ attention_mask=attention_mask_clone,
+ logits_processors=logits_processor,
+ pad_token_id=getattr(
+ model, model.base_model_prefix).config["pad_token_id"],
+ eos_token_id=getattr(
+ model, model.base_model_prefix).config["eos_token_id"],
+ **kwargs,
+ )
+ return output_generate, output_group_beam_search
+
+ def test_greedy_generate(self):
+ # check `generate()` and `greedy_search()` are equal
+ for model_class in self.all_generative_model_classes.keys():
+ config, input_ids, attention_mask, max_length = self._get_input_ids_and_config(
+ )
+ pretrained_model = self.all_generative_model_classes[model_class][
+ 0](**config)
+ model = model_class(pretrained_model)
+ model.eval()
+
+ output_greedy, output_generate = self._greedy_generate(
+ model=model,
+ input_ids=input_ids,
+ attention_mask=attention_mask,
+ max_length=max_length)
+
+ self.assertListEqual(output_greedy[0].tolist(),
+ output_generate[0].tolist())
+
+ def test_sample_generate(self):
+ random.seed(128)
+ np.random.seed(128)
+ paddle.seed(128)
+
+ for model_class in self.all_generative_model_classes.keys():
+ config, input_ids, attention_mask, max_length = self._get_input_ids_and_config(
+ )
+ pretrained_model = self.all_generative_model_classes[model_class][
+ 0](**config)
+ model = model_class(pretrained_model)
+ model.eval()
+
+ if self.is_encoder_decoder:
+ max_length = 4
+
+ process_kwargs, logits_processor = self._get_logits_processor_and_kwargs(
+ getattr(model, model.base_model_prefix).config["eos_token_id"],
+ forced_bos_token_id=getattr(
+ getattr(model, model.base_model_prefix).config,
+ "forced_bos_token_id", None),
+ forced_eos_token_id=getattr(
+ getattr(model, model.base_model_prefix).config,
+ "forced_eos_token_id", None),
+ max_length=max_length,
+ )
+ logits_warper = self._get_warper_and_kwargs()
+
+ # check `generate()` and `sample()` are equal
+ output_sample, output_generate = self._sample_generate(
+ model=model,
+ input_ids=input_ids,
+ attention_mask=attention_mask,
+ max_length=max_length,
+ num_return_sequences=1,
+ logits_processors=logits_processor,
+ logits_warper=logits_warper,
+ process_kwargs=process_kwargs,
+ )
+ self.assertListEqual(output_sample[0].tolist(),
+ output_generate[0].tolist())
+
+ # check `generate()` and `sample()` yield equal results for `num_return_sequences`
+ output_sample, output_generate = self._sample_generate(
+ model=model,
+ input_ids=input_ids,
+ attention_mask=attention_mask,
+ max_length=max_length,
+ num_return_sequences=3,
+ logits_processors=logits_processor,
+ logits_warper=logits_warper,
+ process_kwargs=process_kwargs,
+ )
+ self.assertListEqual(output_sample[0].tolist(),
+ output_generate[0].tolist())
+
+ def test_beam_search_generate(self):
+ for model_class in self.all_generative_model_classes.keys():
+ config, input_ids, attention_mask, max_length = self._get_input_ids_and_config(
+ )
+
+ # It is important set set the eos_token_id to None to ensure that no sequences
+ # shorter than `max_length` can be generated which could lead to flaky circle ci
+ # failures if the top `num_return_sequences` beams are all shorter than the longest beam
+ config["eos_token_id"] = None
+ config["forced_eos_token_id"] = None
+
+ pretrained_model = self.all_generative_model_classes[model_class][
+ 0](**config)
+ model = model_class(pretrained_model)
+ model.eval()
+
+ if self.is_encoder_decoder:
+ max_length = 4
+
+ logits_process_kwargs, logits_processor = self._get_logits_processor_and_kwargs(
+ config["eos_token_id"],
+ getattr(config, "forced_bos_token_id", None),
+ getattr(config, "forced_eos_token_id", None),
+ max_length,
+ )
+ beam_kwargs, beam_scorer = self._get_beam_scorer_and_kwargs(
+ input_ids.shape[0],
+ max_length + 1 if self.is_encoder_decoder else max_length +
+ input_ids.shape[-1])
+
+ # check `generate()` and `beam_search()` are equal
+ output_generate, output_beam_search = self._beam_search_generate(
+ model=model,
+ input_ids=input_ids,
+ attention_mask=attention_mask,
+ max_length=max_length,
+ beam_scorer=beam_scorer,
+ beam_kwargs=beam_kwargs,
+ logits_process_kwargs=logits_process_kwargs,
+ logits_processor=logits_processor,
+ )
+
+ self.assertListEqual(output_generate[0].tolist(),
+ output_beam_search[0].tolist())
+
+ # check `generate()` and `beam_search()` are equal for `num_return_sequences`
+ num_return_sequences = 2
+ if self.is_encoder_decoder:
+ max_length = 4
+ beam_kwargs, beam_scorer = self._get_beam_scorer_and_kwargs(
+ input_ids.shape[0],
+ max_length + 1 if self.is_encoder_decoder else max_length +
+ input_ids.shape[-1],
+ num_return_sequences=num_return_sequences)
+
+ output_generate, output_beam_search = self._beam_search_generate(
+ model=model,
+ input_ids=input_ids,
+ attention_mask=attention_mask,
+ max_length=max_length,
+ beam_scorer=beam_scorer,
+ beam_kwargs=beam_kwargs,
+ logits_process_kwargs=logits_process_kwargs,
+ logits_processor=logits_processor,
+ )
+ self.assertListEqual(output_generate[0].tolist(),
+ output_beam_search[0].tolist())
+
+ def test_generate_without_input_ids(self):
+ config, _, _, max_length = self._get_input_ids_and_config()
+
+ # if no bos token id => cannot generate from None
+ if config["bos_token_id"] is None:
+ return
+
+ for model_class in self.all_generative_model_classes.keys():
+ pretrained_model = self.all_generative_model_classes[model_class][
+ 0](**config)
+ model = model_class(pretrained_model)
+ model.eval()
+
+ output_ids_generate = model.generate(
+ decode_strategy='greedy_search',
+ max_length=max_length,
+ )
+
+ self.assertIsNotNone(output_ids_generate)
+
+ def test_group_beam_search_generate(self):
+ for model_class in self.all_generative_model_classes.keys():
+ config, input_ids, attention_mask, max_length = self._get_input_ids_and_config(
+ )
+
+ # It is important set set the eos_token_id to None to ensure that no sequences
+ # shorter than `max_length` can be generated which could lead to flaky circle ci
+ # failures if the top `num_return_sequences` beams are all shorter than the longest beam
+ config["eos_token_id"] = None
+ config["forced_eos_token_id"] = None
+
+ pretrained_model = self.all_generative_model_classes[model_class][
+ 0](**config)
+ model = model_class(pretrained_model)
+ model.eval()
+
+ if self.is_encoder_decoder:
+ max_length = 4
+
+ logits_process_kwargs, logits_processor = self._get_logits_processor_and_kwargs(
+ config["eos_token_id"],
+ getattr(config, "forced_bos_token_id", None),
+ getattr(config, "forced_eos_token_id", None),
+ max_length,
+ diversity_penalty=2.0,
+ )
+
+ # check `generate()` and `group_beam_search()` are equal
+ beam_kwargs, beam_scorer = self._get_diverse_beam_scorer_and_kwargs(
+ input_ids.shape[0],
+ max_length + 1 if self.is_encoder_decoder else max_length +
+ input_ids.shape[-1])
+ output_generate, output_group_beam_search = self._group_beam_search_generate(
+ model=model,
+ input_ids=input_ids,
+ attention_mask=attention_mask,
+ max_length=max_length,
+ beam_scorer=beam_scorer,
+ beam_kwargs=beam_kwargs,
+ logits_processor=logits_processor,
+ logits_process_kwargs=logits_process_kwargs,
+ )
+ self.assertListEqual(output_generate[0].tolist(),
+ output_group_beam_search[0].tolist())
+
+ # check `generate()` and `group_beam_search()` are equal for `num_return_sequences`
+ num_return_sequences = 2
+ if self.is_encoder_decoder:
+ max_length = 4
+ beam_kwargs, beam_scorer = self._get_diverse_beam_scorer_and_kwargs(
+ input_ids.shape[0],
+ max_length + 1 if self.is_encoder_decoder else max_length +
+ input_ids.shape[-1],
+ num_return_sequences=num_return_sequences)
+ output_generate, output_group_beam_search = self._group_beam_search_generate(
+ model=model,
+ input_ids=input_ids,
+ attention_mask=attention_mask,
+ max_length=max_length,
+ beam_scorer=beam_scorer,
+ beam_kwargs=beam_kwargs,
+ logits_processor=logits_processor,
+ logits_process_kwargs=logits_process_kwargs,
+ )
+ self.assertListEqual(output_generate[0].tolist(),
+ output_group_beam_search[0].tolist())
+
+ def _check_sequence_inside_sequence(self, tensor_1, tensor_2):
+ # check if tensor_1 inside tensor_2 or tensor_2 inside tensor_1.
+ # set to same device. we don't care what device.
+
+ if not isinstance(tensor_1, list):
+ tensor_1 = tensor_1.cpu().tolist()
+ if not isinstance(tensor_2, list):
+ tensor_2 = tensor_2.cpu().tolist()
+
+ in_order = len(tensor_1) <= len(tensor_2)
+ longer = tensor_2 if in_order else tensor_1
+ shorter = tensor_1 if in_order else tensor_2
+
+ flag = False
+ chunk_size = len(shorter)
+ for chunk_idx in range(len(longer) - chunk_size + 1):
+ subseq = longer[chunk_idx:chunk_idx + chunk_size]
+ if subseq == shorter:
+ flag = True
+ break
+
+ self.assertTrue(flag)
+
+
+class UtilsFunctionsTest(unittest.TestCase):
+
+ # tests whether the top_k_top_p function behaves as expected
+ def test_top_k_top_p_filtering(self):
+ logits = paddle.to_tensor(
+ [
+ [
+ 8.2220991, # 3rd highest value; idx. 0
+ -0.5620044,
+ 5.23229752,
+ 4.0386393,
+ -6.8798378,
+ -0.54785802,
+ -3.2012153,
+ 2.92777176,
+ 1.88171953,
+ 7.35341276,
+ 8.43207833, # 2nd highest value; idx. 10
+ -9.85711836,
+ -5.96209236,
+ -1.13039161,
+ -7.1115294,
+ -0.8369633,
+ -5.3186408,
+ 7.06427407,
+ 0.81369344,
+ -0.82023817,
+ -5.9179796,
+ 0.58813443,
+ -6.99778438,
+ 4.71551189,
+ -0.18771637,
+ 7.44020759, # 4th highest value; idx. 25
+ 9.38450987, # 1st highest value; idx. 26
+ 2.12662941,
+ -9.32562038,
+ 2.35652522,
+ ], # cummulative prob of 4 highest values <= 0.6
+ [
+ 0.58425518,
+ 4.53139238,
+ -5.57510464,
+ -6.28030699,
+ -7.19529503,
+ -4.02122551,
+ 1.39337037,
+ -6.06707057,
+ 1.59480517,
+ -9.643119,
+ 0.03907799,
+ 0.67231762,
+ -8.88206726,
+ 6.27115922, # 4th highest value; idx. 13
+ 2.28520723,
+ 4.82767506,
+ 4.30421368,
+ 8.8275313, # 2nd highest value; idx. 17
+ 5.44029958,
+ -4.4735794,
+ 7.38579536, # 3rd highest value; idx. 20
+ -2.91051663,
+ 2.61946077,
+ -2.5674762,
+ -9.48959302,
+ -4.02922645,
+ -1.35416918,
+ 9.67702323, # 1st highest value; idx. 27
+ -5.89478553,
+ 1.85370467,
+ ], # cummulative prob of 4 highest values <= 0.6
+ ],
+ dtype="float32",
+ )
+
+ non_inf_expected_idx = paddle.to_tensor(
+ [[0, 0], [0, 10], [0, 25], [0, 26], [1, 13], [1, 17], [1, 20],
+ [1, 27]],
+ dtype="int64",
+ ) # expected non filtered idx as noted above
+
+ non_inf_expected_output = paddle.to_tensor(
+ [
+ 8.2221,
+ 8.4321,
+ 7.4402,
+ 9.3845,
+ 6.2712,
+ 8.8275,
+ 7.3858,
+ 9.6770,
+ ], # expected non filtered values as noted above
+ dtype="float32",
+ )
+
+ output = top_k_top_p_filtering(logits,
+ top_k=10,
+ top_p=0.6,
+ min_tokens_to_keep=4)
+ non_inf_output = output[output >= -10000]
+ non_inf_idx = (output >= -10000).nonzero()
+
+ self.assertTrue(
+ paddle.allclose(non_inf_expected_output, non_inf_output,
+ atol=1e-12))
+ self.assertTrue(paddle.all(paddle.eq(non_inf_expected_idx,
+ non_inf_idx)))
+
+
+class GenerationIntegrationTests(unittest.TestCase):
+
+ @slow
+ def test_diverse_beam_search(self):
+ article = """Justin Timberlake and Jessica Biel, welcome to parenthood.
+ The celebrity couple announced the arrival of their son, Silas Randall Timberlake, in statements to People.
+ "Silas was the middle name of Timberlake's maternal grandfather Bill Bomar, who died in 2012, while Randall is the musician's own middle name, as well as his father's first," People reports.
+ The couple announced the pregnancy in January, with an Instagram post. It is the first baby for both."""
+
+ bart_tokenizer = BartTokenizer.from_pretrained("bart-base")
+ bart_model = BartForConditionalGeneration.from_pretrained("bart-base")
+ input_ids = paddle.to_tensor(
+ bart_tokenizer(article)["input_ids"]).unsqueeze([0])
+
+ bart_model.eval()
+
+ outputs = bart_model.generate(
+ input_ids,
+ decode_strategy="beam_search",
+ num_beams=4,
+ num_return_sequences=3,
+ num_beam_groups=4,
+ diversity_penalty=2.0,
+ )
+
+ generated_text = bart_tokenizer.batch_decode(outputs,
+ skip_special_tokens=True)
+
+ def test_max_length_backward_compat_greedy(self):
+ article = """Justin Timberlake and Jessica Biel, welcome to parenthood."""
+
+ bart_tokenizer = BartTokenizer.from_pretrained("bart-base")
+ bart_model = BartForConditionalGeneration.from_pretrained("bart-base")
+ input_ids = paddle.to_tensor(
+ bart_tokenizer(article)["input_ids"]).unsqueeze([0])
+
+ bart_model.eval()
+
+ max_length = 5
+ input_ids = paddle.tile(input_ids, [2, 1])
+
+ bos_token_id = getattr(bart_model, 'bos_token_id', None)
+ eos_token_id = getattr(bart_model, 'eos_token_id', None)
+ pad_token_id = getattr(bart_model, 'pad_token_id', None)
+ decoder_start_token_id = getattr(bart_model, 'decoder_start_token_id',
+ None)
+
+ model_kwargs = {}
+
+ model_kwargs[
+ "attention_mask"] = bart_model.prepare_attention_mask_for_generation(
+ input_ids, pad_token_id, eos_token_id)
+
+ bart_model.is_encoder_decoder = hasattr(
+ bart_model, 'encoder') and hasattr(bart_model, 'decoder')
+
+ model_kwargs = bart_model.prepare_encoder_decoder_kwargs_for_generation(
+ input_ids, model_kwargs)
+
+ if "decoder_input_ids" in model_kwargs:
+ input_ids = model_kwargs.pop("decoder_input_ids")
+ else:
+ input_ids = bart_model.prepare_decoder_input_ids_for_generation(
+ input_ids, decoder_start_token_id, bos_token_id)
+
+ model_kwargs["use_cache"] = True
+ max_length += input_ids.shape[-1]
+
+ bart_model.greedy_search(
+ input_ids,
+ max_length=max_length,
+ pad_token_id=bart_model.bart.config["pad_token_id"],
+ eos_token_id=bart_model.bart.config["eos_token_id"],
+ logits_processors=None,
+ **model_kwargs,
+ )
+
+ def test_max_length_backward_compat_sample(self):
+ article = """Justin Timberlake and Jessica Biel, welcome to parenthood."""
+
+ bart_tokenizer = BartTokenizer.from_pretrained("bart-base")
+ bart_model = BartForConditionalGeneration.from_pretrained("bart-base")
+ input_ids = paddle.to_tensor(
+ bart_tokenizer(article)["input_ids"]).unsqueeze([0])
+
+ bart_model.eval()
+
+ max_length = 5
+ input_ids = paddle.tile(input_ids, [2, 1])
+
+ bos_token_id = getattr(bart_model, 'bos_token_id', None)
+ eos_token_id = getattr(bart_model, 'eos_token_id', None)
+ pad_token_id = getattr(bart_model, 'pad_token_id', None)
+ decoder_start_token_id = getattr(bart_model, 'decoder_start_token_id',
+ None)
+
+ model_kwargs = {}
+
+ model_kwargs[
+ "attention_mask"] = bart_model.prepare_attention_mask_for_generation(
+ input_ids, pad_token_id, eos_token_id)
+
+ bart_model.is_encoder_decoder = hasattr(
+ bart_model, 'encoder') and hasattr(bart_model, 'decoder')
+
+ model_kwargs = bart_model.prepare_encoder_decoder_kwargs_for_generation(
+ input_ids, model_kwargs)
+
+ if "decoder_input_ids" in model_kwargs:
+ input_ids = model_kwargs.pop("decoder_input_ids")
+ else:
+ input_ids = bart_model.prepare_decoder_input_ids_for_generation(
+ input_ids, decoder_start_token_id, bos_token_id)
+
+ model_kwargs["use_cache"] = True
+ max_length += input_ids.shape[-1]
+
+ bart_model.sample(
+ input_ids,
+ max_length=max_length,
+ pad_token_id=bart_model.bart.config["pad_token_id"],
+ eos_token_id=bart_model.bart.config["eos_token_id"],
+ logits_processors=None,
+ top_k=4,
+ **model_kwargs,
+ )
+
+ def test_max_length_backward_compat_beam_search(self):
+ article = """Justin Timberlake and Jessica Biel, welcome to parenthood."""
+
+ bart_tokenizer = BartTokenizer.from_pretrained("bart-base")
+ bart_model = BartForConditionalGeneration.from_pretrained("bart-base")
+ input_ids = paddle.to_tensor(
+ bart_tokenizer(article)["input_ids"]).unsqueeze([0])
+
+ bart_model.eval()
+
+ max_length = 5
+ input_ids = paddle.tile(input_ids, [2, 1])
+
+ bos_token_id = getattr(bart_model, 'bos_token_id', None)
+ eos_token_id = getattr(bart_model, 'eos_token_id', None)
+ pad_token_id = getattr(bart_model, 'pad_token_id', None)
+ decoder_start_token_id = getattr(bart_model, 'decoder_start_token_id',
+ None)
+
+ model_kwargs = {}
+
+ model_kwargs[
+ "attention_mask"] = bart_model.prepare_attention_mask_for_generation(
+ input_ids, pad_token_id, eos_token_id)
+
+ bart_model.is_encoder_decoder = hasattr(
+ bart_model, 'encoder') and hasattr(bart_model, 'decoder')
+
+ model_kwargs = bart_model.prepare_encoder_decoder_kwargs_for_generation(
+ input_ids, model_kwargs)
+
+ if "decoder_input_ids" in model_kwargs:
+ input_ids = model_kwargs.pop("decoder_input_ids")
+ else:
+ input_ids = bart_model.prepare_decoder_input_ids_for_generation(
+ input_ids, decoder_start_token_id, bos_token_id)
+
+ model_kwargs["use_cache"] = True
+ max_length += input_ids.shape[-1]
+
+ beam_scorer = BeamSearchScorer(batch_size=2,
+ max_length=max_length,
+ num_beams=2)
+
+ input_ids, model_kwargs = bart_model.expand_inputs_for_generation(
+ input_ids, expand_size=2, **model_kwargs)
+
+ bart_model.beam_search(
+ input_ids,
+ num_beams=2,
+ max_length=max_length,
+ beam_scorer=beam_scorer,
+ logits_processors=None,
+ diversity_rate=0.0,
+ pad_token_id=bart_model.bart.config["pad_token_id"],
+ eos_token_id=bart_model.bart.config["eos_token_id"],
+ **model_kwargs)
+
+ def test_max_length_backward_compat_group_beam_search(self):
+ article = """Justin Timberlake and Jessica Biel, welcome to parenthood."""
+
+ bart_tokenizer = BartTokenizer.from_pretrained("bart-base")
+ bart_model = BartForConditionalGeneration.from_pretrained("bart-base")
+ input_ids = paddle.to_tensor(
+ bart_tokenizer(article)["input_ids"]).unsqueeze([0])
+
+ bart_model.eval()
+
+ max_length = 5
+ input_ids = paddle.tile(input_ids, [2, 1])
+
+ bos_token_id = getattr(bart_model, 'bos_token_id', None)
+ eos_token_id = getattr(bart_model, 'eos_token_id', None)
+ pad_token_id = getattr(bart_model, 'pad_token_id', None)
+ decoder_start_token_id = getattr(bart_model, 'decoder_start_token_id',
+ None)
+
+ model_kwargs = {}
+
+ model_kwargs[
+ "attention_mask"] = bart_model.prepare_attention_mask_for_generation(
+ input_ids, pad_token_id, eos_token_id)
+
+ bart_model.is_encoder_decoder = hasattr(
+ bart_model, 'encoder') and hasattr(bart_model, 'decoder')
+
+ model_kwargs = bart_model.prepare_encoder_decoder_kwargs_for_generation(
+ input_ids, model_kwargs)
+
+ if "decoder_input_ids" in model_kwargs:
+ input_ids = model_kwargs.pop("decoder_input_ids")
+ else:
+ input_ids = bart_model.prepare_decoder_input_ids_for_generation(
+ input_ids, decoder_start_token_id, bos_token_id)
+
+ model_kwargs["use_cache"] = True
+ max_length += input_ids.shape[-1]
+
+ diverse_beam_scorer = BeamSearchScorer(batch_size=2,
+ max_length=max_length,
+ num_beams=2,
+ num_beam_groups=2)
+
+ input_ids, model_kwargs = bart_model.expand_inputs_for_generation(
+ input_ids, expand_size=2, **model_kwargs)
+
+ bart_model.group_beam_search(
+ input_ids,
+ num_beams=2,
+ max_length=max_length,
+ beam_scorer=diverse_beam_scorer,
+ logits_processors=None,
+ pad_token_id=bart_model.bart.config["pad_token_id"],
+ eos_token_id=bart_model.bart.config["eos_token_id"],
+ **model_kwargs)
+
+ def test_custom_logits_processor(self):
+ article = """Justin Timberlake and Jessica Biel, welcome to parenthood."""
+
+ bart_tokenizer = BartTokenizer.from_pretrained("bart-base")
+ bart_model = BartForConditionalGeneration.from_pretrained("bart-base")
+ input_ids = paddle.to_tensor(
+ bart_tokenizer(article)["input_ids"]).unsqueeze([0])
+
+ bart_model.eval()
+
+ logits_processor = LogitsProcessorList()
+ # 1 means decoder_start_token.
+ logits_processor.append(
+ MinLengthLogitsProcessor(
+ min_length=25 + 1,
+ eos_token_id=bart_model.bart.config["forced_eos_token_id"]))
+
+ bart_model.generate(input_ids,
+ decode_strategy="sampling",
+ top_k=1,
+ max_length=30,
+ logits_processors=logits_processor)
+
+ bart_model.generate(input_ids,
+ decode_strategy="sampling",
+ top_k=1,
+ max_length=30,
+ min_length=25)
+
+ # BART supports inputs_embeds
+ # def test_encoder_decoder_generate_with_inputs_embeds(self):
+ # article = """Justin Timberlake and Jessica Biel, welcome to parenthood."""
+ # bart_tokenizer = BartTokenizer.from_pretrained("bart-base")
+ # bart_model = BartForConditionalGeneration.from_pretrained("bart-base")
+ # bart_model.eval()
+
+ # bart_model.bart.config["eos_token_id"] = None
+ # input_ids = paddle.to_tensor(bart_tokenizer(articles[0])["input_ids"]).unsqueeze([0])
+ # inputs_embeds = bart_model.get_input_embeddings()(input_ids)
+
+ # output_sequences = bart_model.generate(inputs_embeds=inputs_embeds)
+
+ # self.assertEqual(output_sequences.shape, (1, 5))
+
+ def test_encoder_decoder_generate_attention_mask(self):
+ articles = [
+ "Timberlake",
+ "Jessica Biel, welcome to parenthood among other things"
+ ]
+ bart_tokenizer = BartTokenizer.from_pretrained("bart-base")
+ bart_model = BartForConditionalGeneration.from_pretrained("bart-base")
+ bart_model.eval()
+
+ input_ids = paddle.to_tensor(bart_tokenizer(
+ articles[0])["input_ids"]).unsqueeze([0])
+ input_ids_batched = paddle.to_tensor(
+ bart_tokenizer(articles, padding=True)["input_ids"])
+
+ output_sequences_batched = bart_model.generate(
+ input_ids=input_ids_batched, decode_strategy="greedy_search")
+ output_sequences = bart_model.generate(input_ids=input_ids,
+ decode_strategy="greedy_search")
+
+ batched_out = output_sequences_batched[1]
+ out = output_sequences[1]
+
+ diff = (batched_out - out).abs()
+
+ self.assertTrue(diff.numpy() < 1e-6)
diff --git a/tests/transformers/test_modeling_common.py b/tests/transformers/test_modeling_common.py
index ad88983cab9d..1864ebc2e59e 100644
--- a/tests/transformers/test_modeling_common.py
+++ b/tests/transformers/test_modeling_common.py
@@ -24,9 +24,9 @@
global_rng = random.Random()
-def ids_tensor(shape, vocab_size):
+def ids_tensor(shape, vocab_size, dtype="int32"):
# Creates a random int32 tensor of the shape within the vocab size
- return paddle.randint(low=0, high=vocab_size, dtype="int32", shape=shape)
+ return paddle.randint(low=0, high=vocab_size, dtype=dtype, shape=shape)
def random_attention_mask(shape):
diff --git a/tests/transformers/test_tokenizer_common.py b/tests/transformers/test_tokenizer_common.py
index 94517f3cc035..3316d91df773 100644
--- a/tests/transformers/test_tokenizer_common.py
+++ b/tests/transformers/test_tokenizer_common.py
@@ -54,6 +54,10 @@ def filter_non_english(_, pretrained_name: str):
return not any([lang in pretrained_name for lang in NON_ENGLISH_TAGS])
+def filter_roberta_detectors(_, pretrained_name: str):
+ return "detector" not in pretrained_name
+
+
class TokenizerTesterMixin:
tokenizer_class = None
@@ -501,8 +505,6 @@ def test_save_and_load_tokenizer(self):
after_tokens = after_tokenizer.encode(sample_text,
add_special_tokens=False)
after_vocab = after_tokenizer.get_vocab()
- # after_vocab = dict(after_tokenizer.vocab._token_to_idx,
- # **after_tokenizer.added_tokens_encoder)
self.assertListEqual(before_tokens["input_ids"],
after_tokens["input_ids"])
self.assertDictEqual(before_vocab, after_vocab)