From 651117e6e56649910c3861362c17c6cd9c7ea36e Mon Sep 17 00:00:00 2001 From: FrostML <380185688@qq.com> Date: Thu, 11 Aug 2022 06:32:17 +0000 Subject: [PATCH 01/15] unittests --- paddlenlp/transformers/generation_utils.py | 144 ++- tests/transformers/bart/__init__.py | 0 tests/transformers/bart/test_modeling.py | 840 +++++++++++++++ tests/transformers/bart/test_tokenizer.py | 215 ++++ tests/transformers/test_generation_utils.py | 1041 +++++++++++++++++++ tests/transformers/test_tokenizer_common.py | 4 + 6 files changed, 2200 insertions(+), 44 deletions(-) create mode 100644 tests/transformers/bart/__init__.py create mode 100644 tests/transformers/bart/test_modeling.py create mode 100644 tests/transformers/bart/test_tokenizer.py create mode 100644 tests/transformers/test_generation_utils.py diff --git a/paddlenlp/transformers/generation_utils.py b/paddlenlp/transformers/generation_utils.py index a3d71f02898c..bd542f13502e 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, @@ -514,6 +526,30 @@ def adjust_logits_during_generation(self, logits): return logits + 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 + self.config.decoder_start_token_id) + bos_token_id = bos_token_id if bos_token_id is not None else self.config.bos_token_id + + if decoder_start_token_id is not None: + return decoder_start_token_id + elif (hasattr(self.config, "decoder") + and hasattr(self.config.decoder, "decoder_start_token_id") + and self.config.decoder.decoder_start_token_id is not None): + return self.config.decoder.decoder_start_token_id + elif bos_token_id is not None: + return bos_token_id + elif (hasattr(self.config, "decoder") + and hasattr(self.config.decoder, "bos_token_id") + and self.config.decoder.bos_token_id is not None): + return self.config.decoder.bos_token_id + raise ValueError( + "`decoder_start_token_id` or `bos_token_id` has to be defined for encoder-decoder generation." + ) + def prepare_faster_entry(self, kwargs): return False @@ -811,7 +847,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 +854,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 +866,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 +923,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 +944,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 +1009,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 +1073,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 +1200,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 +1522,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/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..ee4351ba0966 --- /dev/null +++ b/tests/transformers/bart/test_modeling.py @@ -0,0 +1,840 @@ +# 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. +""" Testing suite for the PyTorch BART model. """ + +import copy +import tempfile +import unittest + +import timeout_decorator # noqa + +from util import slow + +from ...test_generation_utils import GenerationTesterMixin +from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor + +import paddle + +from paddlenlp.transformers import ( + AutoModelForSequenceClassification, + BartForConditionalGeneration, + BartForQuestionAnswering, + BartForSequenceClassification, + BartModel, + BartTokenizer, +) +from paddlenlp.transformers 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_bos_token_id = None + 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) + input_ids = paddle.clip( + ids_tensor([self.batch_size, self.seq_length], self.vocab_size), 3) + input_ids[:, -1] = self.eos_token_id # Eos Token + + decoder_input_ids = ids_tensor([self.batch_size, self.seq_length], + self.vocab_size) + + 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, + "encoder_layers": self.num_hidden_layers, + "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_bos_token_id": self.forced_bos_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): + model = BartModel(**config).get_decoder().eval() + input_ids = inputs_dict["input_ids"] + attention_mask = inputs_dict["attention_mask"] + + # first forward pass + output = model(input_ids, attention_mask=attention_mask, use_cache=True) + + # create hypothetical multiple next token and extent to next_input_ids + next_tokens = ids_tensor((self.batch_size, 3), config["vocab_size"]) + next_attn_mask = ids_tensor((self.batch_size, 3), 2) + + # append to next input_ids and + next_input_ids = paddle.concat([input_ids, next_tokens], dim=-1) + next_attention_mask = paddle.concat([attention_mask, next_attn_mask], + dim=-1) + + output_from_no_past = model(next_input_ids, + attention_mask=next_attention_mask) + + # select random slice + random_slice_idx = ids_tensor((1, ), output_from_past.shape[-1]).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( + torch.allclose(output_from_past_slice, + output_from_no_past_slice, + atol=1e-3)) + + +@require_torch +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, + "encoder_layers": 2, + "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() + labels = _long_tensor([2] * batch_size) + model = BartForSequenceClassification(**config) + outputs = model(input_ids=input_ids, + decoder_input_ids=input_ids, + labels=labels) + expected_shape = [batch_size, config["num_labels"]] + self.assertEqual(outputs.shape, expected_shape) + + def test_question_answering_forward(self): + config, input_ids, batch_size = self._get_config_and_data() + sequence_labels = ids_tensor([batch_size], 2) + model = BartForQuestionAnswering(**config) + start_logits, end_logits = model( + input_ids=input_ids, + start_positions=sequence_labels, + end_positions=sequence_labels, + ) + + self.assertEqual(start_logits.shape, input_ids.shape) + self.assertEqual(end_logits.shape, input_ids.shape) + + @timeout_decorator.timeout(1) + def test_lm_forward(self): + config, input_ids, batch_size = self._get_config_and_data() + lm_labels = ids_tensor([batch_size, input_ids.shape[1]], + self.vocab_size) + lm_model = BartForConditionalGeneration(**config) + outputs = lm_model(input_ids=input_ids, labels=lm_labels) + 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, + "encoder_layers": 2, + "decoder_layers": 2, + "encoder_attention_heads": 2, + "decoder_attention_heads": 2, + "encoder_ffn_dim": 8, + "decoder_ffn_dim": 8, + "max_position_embeddings": 48, + } + lm_model = BartForConditionalGeneration(**config) + 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, + labels=summary) + expected_shape = [*summary.shape, 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, + "encoder_layers": 2, + "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, + } + lm_model = BartForConditionalGeneration(**config) + 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, + ) + 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, 1, 2) + n_pad_before = input_ids.eq(1).float().sum() + n_pad_after = shifted.eq(1).float().sum() + self.assertEqual(shifted.shape, input_ids.shape) + self.assertEqual(n_pad_after, n_pad_before - 1) + self.assertTrue(torch.eq(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): + all_model_classes = ((BartModel, BartForConditionalGeneration, + BartForSequenceClassification, + BartForQuestionAnswering)) + all_generative_model_classes = (BartForConditionalGeneration) + 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 test_encoder_decoder_model_standalone(self): + config_and_inputs = self.model_tester.prepare_config_and_inputs_for_common( + ) + self.model_tester.check_encoder_decoder_model_standalone( + *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 torch.allclose(a, b, atol=atol): + return True + raise + except Exception: + pct_different = (torch.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 xsum_1_1_model(self): + return BartForConditionalGeneration.from_pretrained( + "sshleifer/distilbart-xsum-1-1") + + def test_xsum_1_1_generation(self): + hf = self.xsum_1_1_model + 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 International Criminal Court (ICC) has announced that it has been announced by the International" + " Criminal court.") + + dct = tok(ARTICLE, return_tensors="pt") + generated_ids = hf.generate(**dct, num_beams=4) + 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): + + @cached_property + def default_tokenizer(self): + return BartTokenizer.from_pretrained("bart-large") + + @slow + def test_inference_no_head(self): + model = BartModel.from_pretrained("bart-large").eval() + input_ids = _long_tensor( + [[0, 31414, 232, 328, 740, 1140, 12695, 69, 46078, 1588, 2]]) + + attention_mask = paddle.cast( + input_ids == model.bart.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 = torch.Size((1, 11, 1024)) + self.assertEqual(output.shape, expected_shape) + + @slow + def test_cnn_summarization_same_as_fairseq(self): + model = BartForConditionalGeneration.from_pretrained( + "facebook/bart-large").eval() + tok = BartTokenizer.from_pretrained("facebook/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="max_length", + truncation_strategy="only_first", + truncation=True, + return_tensors="pt", + ) + + 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", + ) + assert hypotheses_batch[:, 1].eq(0).all().item() + + 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) + assert generated_summaries == EXPECTED diff --git a/tests/transformers/bart/test_tokenizer.py b/tests/transformers/bart/test_tokenizer.py new file mode 100644 index 000000000000..6feee47da85b --- /dev/null +++ b/tests/transformers/bart/test_tokenizer.py @@ -0,0 +1,215 @@ +# 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 + +from paddlenlp.transformers import BartTokenizer, BartTokenizerFast, BatchEncoding +from paddlenlp.transformers.models.roberta.tokenization_roberta import VOCAB_FILES_NAMES + +from ...test_tokenization_common import TokenizerTesterMixin, filter_roberta_detectors + + +class TestTokenizationBart(TokenizerTesterMixin, unittest.TestCase): + tokenizer_class = BartTokenizer + rust_tokenizer_class = BartTokenizerFast + test_rust_tokenizer = True + 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 = {"unk_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_rust_tokenizer(self, **kwargs): + kwargs.update(self.special_tokens_map) + return self.rust_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 default_tokenizer_fast(self): + return BartTokenizerFast.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 [self.default_tokenizer, self.default_tokenizer_fast]: + batch = tokenizer(src_text, + max_length=len(expected_src_tokens), + padding=True, + return_tensors="pt") + self.assertIsInstance(batch, BatchEncoding) + + 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 [self.default_tokenizer, self.default_tokenizer_fast]: + batch = tokenizer(src_text, padding=True, return_tensors="pt") + # 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 [self.default_tokenizer, self.default_tokenizer_fast]: + targets = tokenizer(text_target=tgt_text, + max_length=32, + padding="max_length", + return_tensors="pt") + self.assertEqual(32, targets["input_ids"].shape[1]) + + def test_prepare_batch_not_longer_than_maxlen(self): + for tokenizer in [self.default_tokenizer, self.default_tokenizer_fast]: + batch = tokenizer(["I am a small frog" * 1024, "I am a small frog"], + padding=True, + truncation=True, + return_tensors="pt") + self.assertIsInstance(batch, BatchEncoding) + 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 [self.default_tokenizer, self.default_tokenizer_fast]: + inputs = tokenizer(src_text, return_tensors="pt") + targets = tokenizer(text_target=tgt_text, return_tensors="pt") + 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_embeded_special_tokens(self): + for tokenizer, pretrained_name, kwargs in self.tokenizers_list: + with self.subTest( + f"{tokenizer.__class__.__name__} ({pretrained_name})"): + tokenizer_r = self.rust_tokenizer_class.from_pretrained( + pretrained_name, **kwargs) + tokenizer_p = self.tokenizer_class.from_pretrained( + pretrained_name, **kwargs) + sentence = "A, AllenNLP sentence." + tokens_r = tokenizer_r.encode_plus(sentence, + add_special_tokens=True, + return_token_type_ids=True) + tokens_p = tokenizer_p.encode_plus(sentence, + add_special_tokens=True, + return_token_type_ids=True) + + # token_type_ids should put 0 everywhere + self.assertEqual(sum(tokens_r["token_type_ids"]), + sum(tokens_p["token_type_ids"])) + + # attention_mask should put 1 everywhere, so sum over length should be 1 + self.assertEqual( + sum(tokens_r["attention_mask"]) / + len(tokens_r["attention_mask"]), + sum(tokens_p["attention_mask"]) / + len(tokens_p["attention_mask"]), + ) + + tokens_r_str = tokenizer_r.convert_ids_to_tokens( + tokens_r["input_ids"]) + tokens_p_str = tokenizer_p.convert_ids_to_tokens( + tokens_p["input_ids"]) + + # Rust correctly handles the space before the mask while python doesnt + self.assertSequenceEqual( + tokens_p["input_ids"], + [0, 250, 6, 50264, 3823, 487, 21992, 3645, 4, 2]) + self.assertSequenceEqual( + tokens_r["input_ids"], + [0, 250, 6, 50264, 3823, 487, 21992, 3645, 4, 2]) + + self.assertSequenceEqual(tokens_p_str, [ + "", "A", ",", "", "ĠAllen", "N", "LP", "Ġsentence", + ".", "" + ]) + self.assertSequenceEqual(tokens_r_str, [ + "", "A", ",", "", "ĠAllen", "N", "LP", "Ġsentence", + ".", "" + ]) diff --git a/tests/transformers/test_generation_utils.py b/tests/transformers/test_generation_utils.py new file mode 100644 index 000000000000..241fb8b0ae27 --- /dev/null +++ b/tests/transformers/test_generation_utils.py @@ -0,0 +1,1041 @@ +# 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) + + +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_generative_model_classes = () + input_name = "input_ids" + + 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, + # output_attentions=output_attentions, + # output_hidden_states=output_hidden_states, + ) + encoder_outputs[ + "last_hidden_state"] = encoder_outputs.last_hidden_state.repeat_interleave( + num_interleave, dim=0) + + input_ids = 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, + ): + model.eval() + if model.config.is_encoder_decoder: + max_length = 4 + logits_process_kwargs, logits_processor = self._get_logits_processor_and_kwargs( + eos_token_id=model.config.eos_token_id, + forced_bos_token_id=model.config.forced_bos_token_id, + forced_eos_token_id=model.config.forced_eos_token_id, + 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 model.config.is_encoder_decoder: + encoder_outputs, input_ids, attention_mask = self._get_encoder_outputs( + model, + input_ids, + attention_mask, + ) + kwargs["encoder_outputs"] = encoder_outputs + + with paddle.no_grad(): + output_greedy = model.greedy_search( + input_ids, + max_length=max_length, + attention_mask=attention_mask, + logits_processors=logits_processor, + pad_token_id=model.config.pad_token_id, + eos_token_id=model.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_processor, + logits_warper, + process_kwargs, + ): + random.seed(128) + np.random.seed(128) + paddle.seed(128) + + model.eval() + + 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, + **process_kwargs, + ) + + kwargs = {} + if model.config.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_outputs"] = encoder_outputs + input_ids_clone = input_ids_clone.repeat_interleave( + num_return_sequences, dim=0) + else: + attention_mask_clone = attention_mask.repeat_interleave( + num_return_sequences, dim=0) + input_ids_clone = input_ids.repeat_interleave(num_return_sequences, + dim=0) + + # prevent flaky generation test failures + # logits_processor.append(InfNanRemoveLogitsProcessor()) + + with paddle.no_grad(): + output_sample = model.sample( + input_ids_clone, + attention_mask=attention_mask_clone, + max_length=max_length, + logits_processors=logits_processor, + **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, + ): + 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, + ) + + # beam_search does not automatically interleave `batch_size` dim for `num_beams` + kwargs = {} + if model.config.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_outputs"] = encoder_outputs + input_ids_clone = input_ids_clone.repeat_interleave( + beam_scorer.num_beams, dim=0) + else: + attention_mask_clone = attention_mask.repeat_interleave( + beam_scorer.num_beams, dim=0) + input_ids_clone = input_ids.repeat_interleave(beam_scorer.num_beams, + dim=0) + + with paddle.no_grad(): + output_beam_search = model.beam_search( + input_ids_clone, + beam_scorer, + max_length=max_length, + attention_mask=attention_mask_clone, + logits_processors=logits_processor, + diversity_rate=logits_process_kwargs["diversity_rate"], + pad_token_id=model.config.pad_token_id, + eos_token_id=model.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 model.config.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_outputs"] = encoder_outputs + input_ids_clone = input_ids_clone.repeat_interleave( + beam_scorer.num_beams, dim=0) + else: + attention_mask_clone = attention_mask.repeat_interleave( + beam_scorer.num_beams, dim=0) + input_ids_clone = input_ids.repeat_interleave(beam_scorer.num_beams, + dim=0) + + with paddle.no_grad(): + output_group_beam_search = model.group_beam_search( + input_ids_clone, + beam_scorer, + max_length=max_length, + attention_mask=attention_mask_clone, + logits_processors=logits_processor, + pad_token_id=model.config.pad_token_id, + eos_token_id=model.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: + config, input_ids, attention_mask, max_length = self._get_input_ids_and_config( + ) + model = model_class(config) + 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.tolist(), + output_generate.tolist()) + + def test_sample_generate(self): + for model_class in self.all_generative_model_classes: + config, input_ids, attention_mask, max_length = self._get_input_ids_and_config( + ) + model = model_class(config) + model.eval() + + if model.config.is_encoder_decoder: + max_length = 4 + + process_kwargs, logits_processor = self._get_logits_processor_and_kwargs( + input_ids.shape[-1], + model.config.eos_token_id, + forced_bos_token_id=model.config.forced_bos_token_id, + forced_eos_token_id=model.config.forced_eos_token_id, + max_length=max_length, + ) + logits_warper_kwargs, logits_warper = self._get_warper_and_kwargs( + num_beams=1) + + # 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, + logits_warper_kwargs=logits_warper_kwargs, + process_kwargs=process_kwargs, + ) + self.assertListEqual(output_sample.tolist(), + output_generate.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, + logits_warper_kwargs=logits_warper_kwargs, + process_kwargs=process_kwargs, + ) + self.assertListEqual(output_sample.tolist(), + output_generate.tolist()) + + def test_beam_search_generate(self): + for model_class in self.all_generative_model_classes: + 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 + + model = model_class(config) + model.eval() + if model.config.is_encoder_decoder: + max_length = 4 + + logits_process_kwargs, logits_processor = self._get_logits_processor_and_kwargs( + input_ids.shape[-1], + config.eos_token_id, + config.forced_bos_token_id, + config.forced_eos_token_id, + max_length, + ) + beam_kwargs, beam_scorer = self._get_beam_scorer_and_kwargs( + input_ids.shape[0], max_length) + + # 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_processors=logits_processor, + ) + + self.assertListEqual(output_generate.tolist(), + output_beam_search.tolist()) + + # check `generate()` and `beam_search()` are equal for `num_return_sequences` + num_return_sequences = 2 + if model.config.is_encoder_decoder: + max_length = 4 + beam_kwargs, beam_scorer = self._get_beam_scorer_and_kwargs( + input_ids.shape[0], + max_length, + 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_processors=logits_processor, + ) + self.assertListEqual(output_generate.tolist(), + output_beam_search.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: + model = model_class(config) + 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: + 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 + + model = model_class(config) + model.eval() + if model.config.is_encoder_decoder: + max_length = 4 + + logits_process_kwargs, logits_processor = self._get_logits_processor_and_kwargs( + input_ids.shape[-1], + config.eos_token_id, + config.forced_bos_token_id, + config.forced_eos_token_id, + 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) + 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_processors=logits_processor, + logits_process_kwargs=logits_process_kwargs, + ) + self.assertListEqual(output_generate.tolist(), + output_group_beam_search.tolist()) + + # check `generate()` and `group_beam_search()` are equal for `num_return_sequences` + num_return_sequences = 2 + if model.config.is_encoder_decoder: + max_length = 4 + beam_kwargs, beam_scorer = self._get_diverse_beam_scorer_and_kwargs( + input_ids.shape[0], + max_length, + 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_processors=logits_processor, + logits_process_kwargs=logits_process_kwargs, + ) + self.assertListEqual(output_generate.tolist(), + output_group_beam_search.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.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_tokenizer_common.py b/tests/transformers/test_tokenizer_common.py index 5fafe4c9de16..f4e721c6be1e 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 From 3c1f4e087d180fb30b87fb3054f3069b50dc962c Mon Sep 17 00:00:00 2001 From: FrostML <380185688@qq.com> Date: Mon, 15 Aug 2022 03:18:45 +0000 Subject: [PATCH 02/15] update --- paddlenlp/transformers/generation_utils.py | 24 --- tests/transformers/bart/test_modeling.py | 145 +++++++------- tests/transformers/bert/test_tokenizer.py | 2 +- tests/transformers/test_generation_utils.py | 204 ++++++++++++-------- tests/transformers/test_modeling_common.py | 5 - 5 files changed, 206 insertions(+), 174 deletions(-) diff --git a/paddlenlp/transformers/generation_utils.py b/paddlenlp/transformers/generation_utils.py index bd542f13502e..ed04677d8e21 100644 --- a/paddlenlp/transformers/generation_utils.py +++ b/paddlenlp/transformers/generation_utils.py @@ -526,30 +526,6 @@ def adjust_logits_during_generation(self, logits): return logits - 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 - self.config.decoder_start_token_id) - bos_token_id = bos_token_id if bos_token_id is not None else self.config.bos_token_id - - if decoder_start_token_id is not None: - return decoder_start_token_id - elif (hasattr(self.config, "decoder") - and hasattr(self.config.decoder, "decoder_start_token_id") - and self.config.decoder.decoder_start_token_id is not None): - return self.config.decoder.decoder_start_token_id - elif bos_token_id is not None: - return bos_token_id - elif (hasattr(self.config, "decoder") - and hasattr(self.config.decoder, "bos_token_id") - and self.config.decoder.bos_token_id is not None): - return self.config.decoder.bos_token_id - raise ValueError( - "`decoder_start_token_id` or `bos_token_id` has to be defined for encoder-decoder generation." - ) - def prepare_faster_entry(self, kwargs): return False diff --git a/tests/transformers/bart/test_modeling.py b/tests/transformers/bart/test_modeling.py index ee4351ba0966..8f4ec9110764 100644 --- a/tests/transformers/bart/test_modeling.py +++ b/tests/transformers/bart/test_modeling.py @@ -21,10 +21,10 @@ import timeout_decorator # noqa -from util import slow +from tests.testing_utils import slow -from ...test_generation_utils import GenerationTesterMixin -from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor +from ..test_generation_utils import GenerationTesterMixin +from ..test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor import paddle @@ -36,7 +36,7 @@ BartModel, BartTokenizer, ) -from paddlenlp.transformers import BartDecoder, BartEncoder, shift_tokens_right +from paddlenlp.transformers.bart.modeling import BartDecoder, BartEncoder, shift_tokens_right def prepare_bart_inputs_dict( @@ -108,7 +108,6 @@ def __init__( # 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_bos_token_id = None self.forced_eos_token_id = None def prepare_config_and_inputs(self): @@ -130,8 +129,8 @@ def get_config(self): return { "vocab_size": self.vocab_size, "d_model": self.hidden_size, - "encoder_layers": self.num_hidden_layers, - "decoder_layers": self.num_hidden_layers, + "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, @@ -142,7 +141,6 @@ def get_config(self): "eos_token_id": self.eos_token_id, "bos_token_id": self.bos_token_id, "pad_token_id": self.pad_token_id, - "forced_bos_token_id": self.forced_bos_token_id, "forced_eos_token_id": self.forced_eos_token_id, } @@ -152,24 +150,27 @@ def prepare_config_and_inputs_for_common(self): def create_and_check_decoder_model_past_large_inputs( self, config, inputs_dict): - model = BartModel(**config).get_decoder().eval() + model = BartModel(**config).get_decoder() + model.eval() input_ids = inputs_dict["input_ids"] attention_mask = inputs_dict["attention_mask"] # first forward pass - output = model(input_ids, attention_mask=attention_mask, use_cache=True) + output = model(input_ids, + decoder_attention_mask=attention_mask, + cache=True) # create hypothetical multiple next token and extent to next_input_ids next_tokens = ids_tensor((self.batch_size, 3), config["vocab_size"]) next_attn_mask = ids_tensor((self.batch_size, 3), 2) # append to next input_ids and - next_input_ids = paddle.concat([input_ids, next_tokens], dim=-1) + next_input_ids = paddle.concat([input_ids, next_tokens], axis=-1) next_attention_mask = paddle.concat([attention_mask, next_attn_mask], - dim=-1) + axis=-1) output_from_no_past = model(next_input_ids, - attention_mask=next_attention_mask) + decoder_attention_mask=next_attention_mask) # select random slice random_slice_idx = ids_tensor((1, ), output_from_past.shape[-1]).item() @@ -184,12 +185,11 @@ def create_and_check_decoder_model_past_large_inputs( # test that outputs are equal for slice self.parent.assertTrue( - torch.allclose(output_from_past_slice, - output_from_no_past_slice, - atol=1e-3)) + paddle.allclose(output_from_past_slice, + output_from_no_past_slice, + atol=1e-3)) -@require_torch class BartHeadTests(unittest.TestCase): vocab_size = 99 @@ -217,8 +217,8 @@ def _get_config_and_data(self): config = { "vocab_size": self.vocab_size, "d_model": 24, - "encoder_layers": 2, - "decoder_layers": 2, + "num_encoder_layers": 2, + "num_decoder_layers": 2, "encoder_attention_heads": 2, "decoder_attention_heads": 2, "encoder_ffn_dim": 32, @@ -232,23 +232,18 @@ def _get_config_and_data(self): def test_sequence_classification_forward(self): config, input_ids, batch_size = self._get_config_and_data() - labels = _long_tensor([2] * batch_size) - model = BartForSequenceClassification(**config) - outputs = model(input_ids=input_ids, - decoder_input_ids=input_ids, - labels=labels) - expected_shape = [batch_size, config["num_labels"]] + 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() - sequence_labels = ids_tensor([batch_size], 2) - model = BartForQuestionAnswering(**config) - start_logits, end_logits = model( - input_ids=input_ids, - start_positions=sequence_labels, - end_positions=sequence_labels, - ) + 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) @@ -256,35 +251,34 @@ def test_question_answering_forward(self): @timeout_decorator.timeout(1) def test_lm_forward(self): config, input_ids, batch_size = self._get_config_and_data() - lm_labels = ids_tensor([batch_size, input_ids.shape[1]], - self.vocab_size) - lm_model = BartForConditionalGeneration(**config) - outputs = lm_model(input_ids=input_ids, labels=lm_labels) - expected_shape = [batch_size, input_ids.shape[1], config.vocab_size] + 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, - "encoder_layers": 2, - "decoder_layers": 2, + "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, } - lm_model = BartForConditionalGeneration(**config) + 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, - labels=summary) - expected_shape = [*summary.shape, config["vocab_size"]] + 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): @@ -292,8 +286,8 @@ def test_generate_beam_search(self): config = { "vocab_size": self.vocab_size, "d_model": 24, - "encoder_layers": 2, - "decoder_layers": 2, + "num_encoder_layers": 2, + "num_decoder_layers": 2, "encoder_attention_heads": 2, "decoder_attention_heads": 2, "encoder_ffn_dim": 32, @@ -303,7 +297,8 @@ def test_generate_beam_search(self): "pad_token_id": 1, "bos_token_id": 0, } - lm_model = BartForConditionalGeneration(**config) + bart_model = BartModel(**config) + lm_model = BartForConditionalGeneration(bart_model) lm_model.eval() max_length = 5 @@ -313,19 +308,19 @@ def test_generate_beam_search(self): num_return_sequences=1, max_length=max_length, top_k=4, - ) - self.assertEqual(generated_ids.shape, (input_ids.shape[0], max_length)) + )[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, 1, 2) - n_pad_before = input_ids.eq(1).float().sum() - n_pad_after = shifted.eq(1).float().sum() + 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(torch.eq(shifted[:, 0], 2).all()) + self.assertTrue(paddle.equal(shifted[:, 0], 2).all()) @slow def test_tokenization(self): @@ -342,10 +337,14 @@ def test_tokenization(self): class BartModelTest(ModelTesterMixin, GenerationTesterMixin, unittest.TestCase): - all_model_classes = ((BartModel, BartForConditionalGeneration, - BartForSequenceClassification, - BartForQuestionAnswering)) - all_generative_model_classes = (BartForConditionalGeneration) + all_model_classes = (BartModel, BartForConditionalGeneration, + BartForSequenceClassification, + BartForQuestionAnswering) + # all_pretrained_model = [BartModel] + # all_pretrained_model_name = ["bart"] + all_generative_model_classes = { + BartForConditionalGeneration: (BartModel, "bart") + } is_encoder_decoder = True fx_compatible = True test_pruning = False @@ -359,11 +358,27 @@ def test_decoder_model_past_with_large_inputs(self): self.model_tester.create_and_check_decoder_model_past_large_inputs( *config_and_inputs) - def test_encoder_decoder_model_standalone(self): - config_and_inputs = self.model_tester.prepare_config_and_inputs_for_common( + def get_decoder_start_token_id(self, + model, + 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 + model.bart.config["decoder_start_token_id"]) + bos_token_id = bos_token_id if bos_token_id is not None else model.bart.config[ + "bos_token_id"] + + if decoder_start_token_id is not None: + return decoder_start_token_id + elif model.bart.config["decoder_start_token_id"] is not None: + return model.bart.config["decoder.decoder_start_token_id"] + elif bos_token_id is not None: + return bos_token_id + elif model.bart.config["bos_token_id"] is not None: + return model.bart.config["bos_token_id"] + raise ValueError( + "`decoder_start_token_id` or `bos_token_id` has to be defined for encoder-decoder generation." ) - self.model_tester.check_encoder_decoder_model_standalone( - *config_and_inputs) def assert_tensors_close(a, b, atol=1e-12, prefix=""): @@ -371,11 +386,11 @@ def assert_tensors_close(a, b, atol=1e-12, prefix=""): if a is None and b is None: return True try: - if torch.allclose(a, b, atol=atol): + if paddle.allclose(a, b, atol=atol): return True raise except Exception: - pct_different = (torch.gt((a - b).abs(), atol)).float().mean().item() + 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: @@ -583,13 +598,13 @@ def test_xsum_1_1_batch_generation(self): class BartModelIntegrationTests(unittest.TestCase): - @cached_property def default_tokenizer(self): return BartTokenizer.from_pretrained("bart-large") @slow def test_inference_no_head(self): - model = BartModel.from_pretrained("bart-large").eval() + model = BartModel.from_pretrained("bart-large") + model.eval() input_ids = _long_tensor( [[0, 31414, 232, 328, 740, 1140, 12695, 69, 46078, 1588, 2]]) diff --git a/tests/transformers/bert/test_tokenizer.py b/tests/transformers/bert/test_tokenizer.py index 11e376e47cba..c19ec6bf722e 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 index 241fb8b0ae27..d0892eb4c202 100644 --- a/tests/transformers/test_generation_utils.py +++ b/tests/transformers/test_generation_utils.py @@ -31,7 +31,7 @@ BeamSearchScorer, MinLengthLogitsProcessor, RepetitionPenaltyLogitsProcessor, HammingDiversityLogitsProcessor, ForcedBOSTokenLogitsProcessor, ForcedEOSTokenLogitsProcessor, TopKProcess, - TopPProcess) + TopPProcess, LogitsProcessorList) def top_k_top_p_filtering( @@ -51,8 +51,19 @@ def top_k_top_p_filtering( class GenerationTesterMixin: model_tester = None - all_generative_model_classes = () + # all_pretrained_model = [] + # all_pretrained_model_name = [] + all_generative_model_classes = {} input_name = "input_ids" + is_encoder_decoder = False + + @classmethod + def get_decoder_start_token_id(self, + model, + decoder_start_token_id=None, + bos_token_id=None): + raise NotImplementedError( + "get_decoder_start_token_id is NOT implemented. ") def _get_input_ids_and_config(self): config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common( @@ -69,9 +80,9 @@ def _get_input_ids_and_config(self): # generate max 3 tokens max_length = 3 - if config.eos_token_id is not None and config.pad_token_id is None: + 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 + config["pad_token_id"] = config["eos_token_id"] return config, input_ids, attention_mask, max_length @staticmethod @@ -86,6 +97,7 @@ def _get_logits_processor_and_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(([ @@ -164,14 +176,11 @@ def _get_encoder_outputs(model, encoder_outputs = encoder( input_ids, attention_mask=attention_mask, - # output_attentions=output_attentions, - # output_hidden_states=output_hidden_states, ) - encoder_outputs[ - "last_hidden_state"] = encoder_outputs.last_hidden_state.repeat_interleave( - num_interleave, dim=0) + encoder_outputs = encoder_outputs.repeat_interleave(num_interleave, + axis=0) - input_ids = model.get_decoder_start_token_id() + input_ids = cls.get_decoder_start_token_id(model) attention_mask = None return encoder_outputs, input_ids, attention_mask @@ -181,14 +190,20 @@ def _greedy_generate( input_ids, attention_mask, max_length, + pretrained_model_name, ): model.eval() - if model.config.is_encoder_decoder: + if self.is_encoder_decoder: max_length = 4 logits_process_kwargs, logits_processor = self._get_logits_processor_and_kwargs( - eos_token_id=model.config.eos_token_id, - forced_bos_token_id=model.config.forced_bos_token_id, - forced_eos_token_id=model.config.forced_eos_token_id, + eos_token_id=getattr(model, + pretrained_model_name).config["eos_token_id"], + forced_bos_token_id=getattr( + getattr(model, pretrained_model_name).config, + "forced_bos_token_id", None), + forced_eos_token_id=getattr( + getattr(model, pretrained_model_name).config, + "forced_eos_token_id", None), max_length=max_length, ) @@ -203,7 +218,7 @@ def _greedy_generate( **logits_process_kwargs, ) - if model.config.is_encoder_decoder: + if self.is_encoder_decoder: encoder_outputs, input_ids, attention_mask = self._get_encoder_outputs( model, input_ids, @@ -217,8 +232,10 @@ def _greedy_generate( max_length=max_length, attention_mask=attention_mask, logits_processors=logits_processor, - pad_token_id=model.config.pad_token_id, - eos_token_id=model.config.eos_token_id, + pad_token_id=getattr( + model, pretrained_model_name).config["pad_token_id"], + eos_token_id=getattr( + model, pretrained_model_name).config["eos_token_id"], **kwargs, ) return output_greedy, output_generate @@ -230,7 +247,7 @@ def _sample_generate( attention_mask, max_length, num_return_sequences, - logits_processor, + logits_processors, logits_warper, process_kwargs, ): @@ -251,7 +268,7 @@ def _sample_generate( ) kwargs = {} - if model.config.is_encoder_decoder: + if self.is_encoder_decoder: encoder_outputs, input_ids_clone, attention_mask_clone = self._get_encoder_outputs( model, input_ids, @@ -260,22 +277,22 @@ def _sample_generate( ) kwargs["encoder_outputs"] = encoder_outputs input_ids_clone = input_ids_clone.repeat_interleave( - num_return_sequences, dim=0) + num_return_sequences, axis=0) else: attention_mask_clone = attention_mask.repeat_interleave( - num_return_sequences, dim=0) + num_return_sequences, axis=0) input_ids_clone = input_ids.repeat_interleave(num_return_sequences, - dim=0) + axis=0) # prevent flaky generation test failures - # logits_processor.append(InfNanRemoveLogitsProcessor()) + # logits_processors.append(InfNanRemoveLogitsProcessor()) with paddle.no_grad(): output_sample = model.sample( input_ids_clone, attention_mask=attention_mask_clone, max_length=max_length, - logits_processors=logits_processor, + logits_processors=logits_processors, **process_kwargs**kwargs, ) return output_sample, output_generate @@ -290,6 +307,7 @@ def _beam_search_generate( beam_kwargs, logits_processor, logits_process_kwargs, + pretrained_model_name, ): model.eval() with paddle.no_grad(): @@ -304,7 +322,7 @@ def _beam_search_generate( # beam_search does not automatically interleave `batch_size` dim for `num_beams` kwargs = {} - if model.config.is_encoder_decoder: + if self.is_encoder_decoder: encoder_outputs, input_ids_clone, attention_mask_clone = self._get_encoder_outputs( model, input_ids, @@ -313,12 +331,12 @@ def _beam_search_generate( ) kwargs["encoder_outputs"] = encoder_outputs input_ids_clone = input_ids_clone.repeat_interleave( - beam_scorer.num_beams, dim=0) + beam_scorer.num_beams, axis=0) else: attention_mask_clone = attention_mask.repeat_interleave( - beam_scorer.num_beams, dim=0) + beam_scorer.num_beams, axis=0) input_ids_clone = input_ids.repeat_interleave(beam_scorer.num_beams, - dim=0) + axis=0) with paddle.no_grad(): output_beam_search = model.beam_search( @@ -328,8 +346,10 @@ def _beam_search_generate( attention_mask=attention_mask_clone, logits_processors=logits_processor, diversity_rate=logits_process_kwargs["diversity_rate"], - pad_token_id=model.config.pad_token_id, - eos_token_id=model.config.eos_token_id, + pad_token_id=getattr( + model, pretrained_model_name).config["pad_token_id"], + eos_token_id=getattr( + model, pretrained_model_name).config["eos_token_id"], **kwargs, ) return output_generate, output_beam_search @@ -344,6 +364,7 @@ def _group_beam_search_generate( beam_kwargs, logits_processor, logits_process_kwargs, + pretrained_model_name, ): model.eval() with paddle.no_grad(): @@ -358,7 +379,7 @@ def _group_beam_search_generate( # group_beam_search does not automatically interleave `batch_size` dim for `num_beams` kwargs = {} - if model.config.is_encoder_decoder: + if self.is_encoder_decoder: encoder_outputs, input_ids_clone, attention_mask_clone = self._get_encoder_outputs( model, input_ids, @@ -367,12 +388,12 @@ def _group_beam_search_generate( ) kwargs["encoder_outputs"] = encoder_outputs input_ids_clone = input_ids_clone.repeat_interleave( - beam_scorer.num_beams, dim=0) + beam_scorer.num_beams, axis=0) else: attention_mask_clone = attention_mask.repeat_interleave( - beam_scorer.num_beams, dim=0) + beam_scorer.num_beams, axis=0) input_ids_clone = input_ids.repeat_interleave(beam_scorer.num_beams, - dim=0) + axis=0) with paddle.no_grad(): output_group_beam_search = model.group_beam_search( @@ -381,46 +402,59 @@ def _group_beam_search_generate( max_length=max_length, attention_mask=attention_mask_clone, logits_processors=logits_processor, - pad_token_id=model.config.pad_token_id, - eos_token_id=model.config.eos_token_id, + pad_token_id=getattr( + model, pretrained_model_name).config["pad_token_id"], + eos_token_id=getattr( + model, pretrained_model_name).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: + for model_class in self.all_generative_model_classes.keys(): config, input_ids, attention_mask, max_length = self._get_input_ids_and_config( ) - model = model_class(config) + pretrained_model = self.all_generative_model_classes[model_class][ + 0](**config) + pretrained_model_name = self.all_generative_model_classes[ + model_class][1] + 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) + max_length=max_length, + pretrained_model_name=pretrained_model_name) self.assertListEqual(output_greedy.tolist(), output_generate.tolist()) def test_sample_generate(self): - for model_class in self.all_generative_model_classes: + for model_class in self.all_generative_model_classes.keys(): config, input_ids, attention_mask, max_length = self._get_input_ids_and_config( ) - model = model_class(config) + pretrained_model = self.all_generative_model_classes[model_class][ + 0](**config) + pretrained_model_name = self.all_generative_model_classes[ + model_class][1] + model = model_class(pretrained_model) model.eval() - if model.config.is_encoder_decoder: + if self.is_encoder_decoder: max_length = 4 process_kwargs, logits_processor = self._get_logits_processor_and_kwargs( - input_ids.shape[-1], - model.config.eos_token_id, - forced_bos_token_id=model.config.forced_bos_token_id, - forced_eos_token_id=model.config.forced_eos_token_id, + getattr(model, pretrained_model_name).config["eos_token_id"], + forced_bos_token_id=getattr( + getattr(model, pretrained_model_name).config, + "forced_bos_token_id", None), + forced_eos_token_id=getattr( + getattr(model, pretrained_model_name).config, + "forced_eos_token_id", None), max_length=max_length, ) - logits_warper_kwargs, logits_warper = self._get_warper_and_kwargs( - num_beams=1) + logits_warper = self._get_warper_and_kwargs() # check `generate()` and `sample()` are equal output_sample, output_generate = self._sample_generate( @@ -431,7 +465,6 @@ def test_sample_generate(self): num_return_sequences=1, logits_processors=logits_processor, logits_warper=logits_warper, - logits_warper_kwargs=logits_warper_kwargs, process_kwargs=process_kwargs, ) self.assertListEqual(output_sample.tolist(), @@ -446,33 +479,35 @@ def test_sample_generate(self): num_return_sequences=3, logits_processors=logits_processor, logits_warper=logits_warper, - logits_warper_kwargs=logits_warper_kwargs, process_kwargs=process_kwargs, ) self.assertListEqual(output_sample.tolist(), output_generate.tolist()) def test_beam_search_generate(self): - for model_class in self.all_generative_model_classes: + 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 - - model = model_class(config) + config["eos_token_id"] = None + config["forced_eos_token_id"] = None + + pretrained_model = self.all_generative_model_classes[model_class][ + 0](**config) + pretrained_model_name = self.all_generative_model_classes[ + model_class][1] + model = model_class(pretrained_model) model.eval() - if model.config.is_encoder_decoder: + if self.is_encoder_decoder: max_length = 4 logits_process_kwargs, logits_processor = self._get_logits_processor_and_kwargs( - input_ids.shape[-1], - config.eos_token_id, - config.forced_bos_token_id, - config.forced_eos_token_id, + 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( @@ -487,7 +522,8 @@ def test_beam_search_generate(self): beam_scorer=beam_scorer, beam_kwargs=beam_kwargs, logits_process_kwargs=logits_process_kwargs, - logits_processors=logits_processor, + logits_processor=logits_processor, + pretrained_model_name=pretrained_model_name, ) self.assertListEqual(output_generate.tolist(), @@ -495,7 +531,7 @@ def test_beam_search_generate(self): # check `generate()` and `beam_search()` are equal for `num_return_sequences` num_return_sequences = 2 - if model.config.is_encoder_decoder: + if self.is_encoder_decoder: max_length = 4 beam_kwargs, beam_scorer = self._get_beam_scorer_and_kwargs( input_ids.shape[0], @@ -510,7 +546,8 @@ def test_beam_search_generate(self): beam_scorer=beam_scorer, beam_kwargs=beam_kwargs, logits_process_kwargs=logits_process_kwargs, - logits_processors=logits_processor, + logits_processor=logits_processor, + pretrained_model_name=pretrained_model_name, ) self.assertListEqual(output_generate.tolist(), output_beam_search.tolist()) @@ -519,11 +556,15 @@ 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: + if config["bos_token_id"] is None: return - for model_class in self.all_generative_model_classes: - model = model_class(config) + for model_class in self.all_generative_model_classes.keys(): + pretrained_model = self.all_generative_model_classes[model_class][ + 0](**config) + pretrained_model_name = self.all_generative_model_classes[ + model_class][1] + model = model_class(pretrained_model) model.eval() output_ids_generate = model.generate( @@ -534,26 +575,29 @@ def test_generate_without_input_ids(self): self.assertIsNotNone(output_ids_generate) def test_group_beam_search_generate(self): - for model_class in self.all_generative_model_classes: + 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 - - model = model_class(config) + config["eos_token_id"] = None + config["forced_eos_token_id"] = None + + pretrained_model = self.all_generative_model_classes[model_class][ + 0](**config) + pretrained_model_name = self.all_generative_model_classes[ + model_class][1] + model = model_class(pretrained_model) model.eval() - if model.config.is_encoder_decoder: + if self.is_encoder_decoder: max_length = 4 logits_process_kwargs, logits_processor = self._get_logits_processor_and_kwargs( - input_ids.shape[-1], - config.eos_token_id, - config.forced_bos_token_id, - config.forced_eos_token_id, + config["eos_token_id"], + getattr(config, "forced_bos_token_id", None), + getattr(config, "forced_eos_token_id", None), max_length, diversity_penalty=2.0, ) @@ -568,15 +612,16 @@ def test_group_beam_search_generate(self): max_length=max_length, beam_scorer=beam_scorer, beam_kwargs=beam_kwargs, - logits_processors=logits_processor, + logits_processor=logits_processor, logits_process_kwargs=logits_process_kwargs, + pretrained_model_name=pretrained_model_name, ) self.assertListEqual(output_generate.tolist(), output_group_beam_search.tolist()) # check `generate()` and `group_beam_search()` are equal for `num_return_sequences` num_return_sequences = 2 - if model.config.is_encoder_decoder: + if self.is_encoder_decoder: max_length = 4 beam_kwargs, beam_scorer = self._get_diverse_beam_scorer_and_kwargs( input_ids.shape[0], @@ -591,6 +636,7 @@ def test_group_beam_search_generate(self): beam_kwargs=beam_kwargs, logits_processors=logits_processor, logits_process_kwargs=logits_process_kwargs, + pretrained_model_name=pretrained_model_name, ) self.assertListEqual(output_generate.tolist(), output_group_beam_search.tolist()) @@ -1006,7 +1052,7 @@ def test_custom_logits_processor(self): # bart_model = BartForConditionalGeneration.from_pretrained("bart-base") # bart_model.eval() - # bart_model.config.eos_token_id = None + # 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) diff --git a/tests/transformers/test_modeling_common.py b/tests/transformers/test_modeling_common.py index 49ca37e45011..504bb53aa95d 100644 --- a/tests/transformers/test_modeling_common.py +++ b/tests/transformers/test_modeling_common.py @@ -67,11 +67,6 @@ def _prepare_for_class(self, inputs_dict, model_class): def test_save_load(self): config, input_ids, token_type_ids, input_mask = self.model_tester.prepare_config_and_inputs( ) - inputs_dict = { - "input_ids": input_ids, - "token_type_ids": token_type_ids, - "attention_mask": input_mask, - } for model_class in self.all_model_classes: if model_class == self.base_model_class: model = model_class(**config) From 0d9bbc66ace11c89c78021d4e0a08e0fab9a9136 Mon Sep 17 00:00:00 2001 From: FrostML <380185688@qq.com> Date: Mon, 15 Aug 2022 03:19:01 +0000 Subject: [PATCH 03/15] update --- tests/transformers/test_modeling_common.py | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/tests/transformers/test_modeling_common.py b/tests/transformers/test_modeling_common.py index 504bb53aa95d..49ca37e45011 100644 --- a/tests/transformers/test_modeling_common.py +++ b/tests/transformers/test_modeling_common.py @@ -67,6 +67,11 @@ def _prepare_for_class(self, inputs_dict, model_class): def test_save_load(self): config, input_ids, token_type_ids, input_mask = self.model_tester.prepare_config_and_inputs( ) + inputs_dict = { + "input_ids": input_ids, + "token_type_ids": token_type_ids, + "attention_mask": input_mask, + } for model_class in self.all_model_classes: if model_class == self.base_model_class: model = model_class(**config) From 3b4d5545af965faad4a16a20429c917f55d08dbc Mon Sep 17 00:00:00 2001 From: FrostML <380185688@qq.com> Date: Tue, 16 Aug 2022 03:10:45 +0000 Subject: [PATCH 04/15] update bart --- paddlenlp/transformers/bart/modeling.py | 6 + paddlenlp/transformers/generation_utils.py | 32 +++++ paddlenlp/transformers/model_utils.py | 4 +- tests/transformers/bart/test_modeling.py | 79 +++++------ tests/transformers/test_generation_utils.py | 139 ++++++++++++-------- tests/transformers/test_modeling_common.py | 2 +- 6 files changed, 165 insertions(+), 97 deletions(-) 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/generation_utils.py b/paddlenlp/transformers/generation_utils.py index ed04677d8e21..53261002c0ce 100644 --- a/paddlenlp/transformers/generation_utils.py +++ b/paddlenlp/transformers/generation_utils.py @@ -514,6 +514,38 @@ 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, + pretrained_model_name=None): + if type(pretrained_model_name) is not type(""): + raise ValueError( + "The parameter pretrained_model_name should be str. but recieved {}" + .format(type(pretrained_model_name))) + + decoder_start_token_id = ( + decoder_start_token_id + if decoder_start_token_id is not None else getattr( + self, pretrained_model_name).config["decoder_start_token_id"]) + bos_token_id = bos_token_id if bos_token_id is not None else getattr( + self, pretrained_model_name).config["bos_token_id"] + + if decoder_start_token_id is not None: + return decoder_start_token_id + elif getattr(self, pretrained_model_name + ).config["decoder_start_token_id"] is not None: + return getattr( + self, + pretrained_model_name).config["decoder.decoder_start_token_id"] + elif bos_token_id is not None: + return bos_token_id + elif getattr(self, + pretrained_model_name).config["bos_token_id"] is not None: + return getattr(self, pretrained_model_name).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. diff --git a/paddlenlp/transformers/model_utils.py b/paddlenlp/transformers/model_utils.py index 1cda7095cb52..f3e538b8fdb0 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/test_modeling.py b/tests/transformers/bart/test_modeling.py index 8f4ec9110764..01693d83dffc 100644 --- a/tests/transformers/bart/test_modeling.py +++ b/tests/transformers/bart/test_modeling.py @@ -150,27 +150,52 @@ def prepare_config_and_inputs_for_common(self): def create_and_check_decoder_model_past_large_inputs( self, config, inputs_dict): - model = BartModel(**config).get_decoder() - model.eval() + 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) - # first forward pass - output = model(input_ids, - decoder_attention_mask=attention_mask, - cache=True) + 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"]) - next_attn_mask = ids_tensor((self.batch_size, 3), 2) + 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([input_ids, next_tokens], axis=-1) - next_attention_mask = paddle.concat([attention_mask, next_attn_mask], - axis=-1) - - output_from_no_past = model(next_input_ids, - decoder_attention_mask=next_attention_mask) + 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]).item() @@ -337,11 +362,11 @@ def test_tokenization(self): class BartModelTest(ModelTesterMixin, GenerationTesterMixin, unittest.TestCase): + base_model_class = BartModel + all_model_classes = (BartModel, BartForConditionalGeneration, BartForSequenceClassification, BartForQuestionAnswering) - # all_pretrained_model = [BartModel] - # all_pretrained_model_name = ["bart"] all_generative_model_classes = { BartForConditionalGeneration: (BartModel, "bart") } @@ -358,28 +383,6 @@ def test_decoder_model_past_with_large_inputs(self): self.model_tester.create_and_check_decoder_model_past_large_inputs( *config_and_inputs) - def get_decoder_start_token_id(self, - model, - 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 - model.bart.config["decoder_start_token_id"]) - bos_token_id = bos_token_id if bos_token_id is not None else model.bart.config[ - "bos_token_id"] - - if decoder_start_token_id is not None: - return decoder_start_token_id - elif model.bart.config["decoder_start_token_id"] is not None: - return model.bart.config["decoder.decoder_start_token_id"] - elif bos_token_id is not None: - return bos_token_id - elif model.bart.config["bos_token_id"] is not None: - return model.bart.config["bos_token_id"] - raise ValueError( - "`decoder_start_token_id` or `bos_token_id` has to be defined for encoder-decoder generation." - ) - 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.""" @@ -613,7 +616,7 @@ def test_inference_no_head(self): 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 = torch.Size((1, 11, 1024)) + expected_shape = [1, 11, 1024] self.assertEqual(output.shape, expected_shape) @slow diff --git a/tests/transformers/test_generation_utils.py b/tests/transformers/test_generation_utils.py index d0892eb4c202..c6a4fed063f2 100644 --- a/tests/transformers/test_generation_utils.py +++ b/tests/transformers/test_generation_utils.py @@ -57,14 +57,6 @@ class GenerationTesterMixin: input_name = "input_ids" is_encoder_decoder = False - @classmethod - def get_decoder_start_token_id(self, - model, - decoder_start_token_id=None, - bos_token_id=None): - raise NotImplementedError( - "get_decoder_start_token_id is NOT implemented. ") - def _get_input_ids_and_config(self): config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common( ) @@ -165,12 +157,15 @@ def _get_diverse_beam_scorer_and_kwargs(batch_size, 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): + def _get_encoder_outputs( + model, + input_ids, + attention_mask, + output_attentions=None, + output_hidden_states=None, + num_interleave=1, + pretrained_model_name=None, + ): model.eval() encoder = model.get_encoder() encoder_outputs = encoder( @@ -180,8 +175,10 @@ def _get_encoder_outputs(model, encoder_outputs = encoder_outputs.repeat_interleave(num_interleave, axis=0) - input_ids = cls.get_decoder_start_token_id(model) - attention_mask = None + input_ids = paddle.zeros_like( + input_ids[:, :1], dtype="int64") + model.get_decoder_start_token_id( + pretrained_model_name=pretrained_model_name) + # attention_mask = None return encoder_outputs, input_ids, attention_mask def _greedy_generate( @@ -192,7 +189,6 @@ def _greedy_generate( max_length, pretrained_model_name, ): - model.eval() if self.is_encoder_decoder: max_length = 4 logits_process_kwargs, logits_processor = self._get_logits_processor_and_kwargs( @@ -223,13 +219,14 @@ def _greedy_generate( model, input_ids, attention_mask, + pretrained_model_name=pretrained_model_name, ) - kwargs["encoder_outputs"] = encoder_outputs + kwargs["encoder_output"] = encoder_outputs with paddle.no_grad(): output_greedy = model.greedy_search( input_ids, - max_length=max_length, + max_length=max_length + 1, attention_mask=attention_mask, logits_processors=logits_processor, pad_token_id=getattr( @@ -250,13 +247,8 @@ def _sample_generate( logits_processors, logits_warper, process_kwargs, + pretrained_model_name, ): - random.seed(128) - np.random.seed(128) - paddle.seed(128) - - model.eval() - with paddle.no_grad(): output_generate = model.generate( input_ids, @@ -264,6 +256,7 @@ def _sample_generate( decode_strategy='sampling', num_return_sequences=num_return_sequences, attention_mask=attention_mask, + top_k=1, **process_kwargs, ) @@ -274,26 +267,34 @@ def _sample_generate( input_ids, attention_mask, num_interleave=num_return_sequences, + pretrained_model_name=pretrained_model_name, ) - kwargs["encoder_outputs"] = encoder_outputs + 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) - # prevent flaky generation test failures - # logits_processors.append(InfNanRemoveLogitsProcessor()) - with paddle.no_grad(): output_sample = model.sample( input_ids_clone, attention_mask=attention_mask_clone, - max_length=max_length, + max_length=max_length + + 1 if self.is_encoder_decoder else max_length + + input_ids.shape[0], logits_processors=logits_processors, - **process_kwargs**kwargs, + pad_token_id=getattr( + model, pretrained_model_name).config["pad_token_id"], + eos_token_id=getattr( + model, pretrained_model_name).config["eos_token_id"], + top_k=1, + **process_kwargs, + **kwargs, ) return output_sample, output_generate @@ -309,7 +310,6 @@ def _beam_search_generate( logits_process_kwargs, pretrained_model_name, ): - model.eval() with paddle.no_grad(): output_generate = model.generate( input_ids, @@ -328,24 +328,30 @@ def _beam_search_generate( input_ids, attention_mask, num_interleave=beam_scorer.num_beams, + pretrained_model_name=pretrained_model_name, ) - kwargs["encoder_outputs"] = encoder_outputs + 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, + max_length=max_length + 1, attention_mask=attention_mask_clone, logits_processors=logits_processor, - diversity_rate=logits_process_kwargs["diversity_rate"], + diversity_rate=getattr(logits_process_kwargs, "diversity_rate", + 0.0), pad_token_id=getattr( model, pretrained_model_name).config["pad_token_id"], eos_token_id=getattr( @@ -385,21 +391,26 @@ def _group_beam_search_generate( input_ids, attention_mask, num_interleave=beam_scorer.num_beams, + pretrained_model_name=pretrained_model_name, ) - kwargs["encoder_outputs"] = encoder_outputs + 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, + max_length=max_length + 1, attention_mask=attention_mask_clone, logits_processors=logits_processor, pad_token_id=getattr( @@ -421,16 +432,22 @@ def test_greedy_generate(self): model_class][1] 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, pretrained_model_name=pretrained_model_name) - self.assertListEqual(output_greedy.tolist(), - output_generate.tolist()) + + 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( ) @@ -466,9 +483,10 @@ def test_sample_generate(self): logits_processors=logits_processor, logits_warper=logits_warper, process_kwargs=process_kwargs, + pretrained_model_name=pretrained_model_name, ) - self.assertListEqual(output_sample.tolist(), - output_generate.tolist()) + 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( @@ -480,9 +498,10 @@ def test_sample_generate(self): logits_processors=logits_processor, logits_warper=logits_warper, process_kwargs=process_kwargs, + pretrained_model_name=pretrained_model_name, ) - self.assertListEqual(output_sample.tolist(), - output_generate.tolist()) + 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(): @@ -501,6 +520,7 @@ def test_beam_search_generate(self): model_class][1] model = model_class(pretrained_model) model.eval() + if self.is_encoder_decoder: max_length = 4 @@ -511,7 +531,9 @@ def test_beam_search_generate(self): max_length, ) beam_kwargs, beam_scorer = self._get_beam_scorer_and_kwargs( - input_ids.shape[0], max_length) + 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( @@ -526,8 +548,8 @@ def test_beam_search_generate(self): pretrained_model_name=pretrained_model_name, ) - self.assertListEqual(output_generate.tolist(), - output_beam_search.tolist()) + 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 @@ -535,7 +557,8 @@ def test_beam_search_generate(self): max_length = 4 beam_kwargs, beam_scorer = self._get_beam_scorer_and_kwargs( input_ids.shape[0], - max_length, + 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( @@ -549,8 +572,8 @@ def test_beam_search_generate(self): logits_processor=logits_processor, pretrained_model_name=pretrained_model_name, ) - self.assertListEqual(output_generate.tolist(), - output_beam_search.tolist()) + 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() @@ -591,6 +614,7 @@ def test_group_beam_search_generate(self): model_class][1] model = model_class(pretrained_model) model.eval() + if self.is_encoder_decoder: max_length = 4 @@ -604,7 +628,9 @@ def test_group_beam_search_generate(self): # 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) + 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, @@ -616,8 +642,8 @@ def test_group_beam_search_generate(self): logits_process_kwargs=logits_process_kwargs, pretrained_model_name=pretrained_model_name, ) - self.assertListEqual(output_generate.tolist(), - output_group_beam_search.tolist()) + 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 @@ -625,7 +651,8 @@ def test_group_beam_search_generate(self): max_length = 4 beam_kwargs, beam_scorer = self._get_diverse_beam_scorer_and_kwargs( input_ids.shape[0], - max_length, + 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, @@ -634,12 +661,12 @@ def test_group_beam_search_generate(self): max_length=max_length, beam_scorer=beam_scorer, beam_kwargs=beam_kwargs, - logits_processors=logits_processor, + logits_processor=logits_processor, logits_process_kwargs=logits_process_kwargs, pretrained_model_name=pretrained_model_name, ) - self.assertListEqual(output_generate.tolist(), - output_group_beam_search.tolist()) + 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. diff --git a/tests/transformers/test_modeling_common.py b/tests/transformers/test_modeling_common.py index d823ca23ec74..5d69dd26094b 100644 --- a/tests/transformers/test_modeling_common.py +++ b/tests/transformers/test_modeling_common.py @@ -26,7 +26,7 @@ def ids_tensor(shape, vocab_size): # 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="int64", shape=shape) def random_attention_mask(shape): From 54f316b8063888810e457de19f00abe991ee415e Mon Sep 17 00:00:00 2001 From: FrostML <380185688@qq.com> Date: Tue, 16 Aug 2022 12:22:08 +0000 Subject: [PATCH 05/15] bart tokenizer --- model_zoo/ernie-gen/encode.py | 1 - paddlenlp/transformers/bart/tokenizer.py | 232 +++++++++++++++++++- paddlenlp/transformers/gpt/tokenizer.py | 18 ++ tests/transformers/bart/test_modeling.py | 18 +- tests/transformers/bart/test_tokenizer.py | 136 +++++------- tests/transformers/test_modeling_common.py | 4 +- tests/transformers/test_tokenizer_common.py | 39 +--- 7 files changed, 321 insertions(+), 127 deletions(-) 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/tokenizer.py b/paddlenlp/transformers/bart/tokenizer.py index ad93d0a0355b..fad4ef4780a5 100644 --- a/paddlenlp/transformers/bart/tokenizer.py +++ b/paddlenlp/transformers/bart/tokenizer.py @@ -13,13 +13,66 @@ # See the License for the specific language governing permissions and # limitations under the License. +import os +from functools import lru_cache + +import json +import jieba +import shutil +import sentencepiece as spm 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 +153,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="", @@ -114,6 +167,20 @@ def __init__(self, pad_token="", mask_token="", **kwargs): + if "max_len" in kwargs and "model_max_length" in kwargs: + kwargs["max_len"] = kwargs["model_max_length"] + elif "max_len" in kwargs: + kwargs["model_max_length"] = kwargs["max_len"] + + super(BartTokenizer, self).__init__(errors=errors, + bos_token=bos_token, + eos_token=eos_token, + cls_token=cls_token, + sep_token=sep_token, + unk_token=unk_token, + pad_token=pad_token, + mask_token=mask_token, + **kwargs) bos_token = AddedToken(bos_token, lstrip=False, rstrip=False) if isinstance( @@ -147,8 +214,32 @@ def __init__(self, pad_token=pad_token, mask_token=mask_token) - super(BartTokenizer, self).__init__(vocab_file, merges_file, errors, - max_len, pad_token, eos_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 = [] @@ -200,3 +291,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/gpt/tokenizer.py b/paddlenlp/transformers/gpt/tokenizer.py index fad786e33fe2..03972879f400 100644 --- a/paddlenlp/transformers/gpt/tokenizer.py +++ b/paddlenlp/transformers/gpt/tokenizer.py @@ -129,6 +129,13 @@ def __init__( eol_token='\u2583', **kwargs # The token of newline. ): + super(GPTChineseTokenizer, self).__init__(max_len=max_len, + unk_token=unk_token, + bos_token=bos_token, + eos_token=eos_token, + eol_token=eol_token, + **kwargs) + self._model_file = model_file self.eol_token = eol_token if not os.path.isfile(model_file): @@ -369,6 +376,14 @@ def __init__( eol_token='\u010a', **kwargs # The token of newline. ): + super(GPTTokenizer, self).__init__(errors=errors, + max_len=max_len, + pad_token=pad_token, + eos_token=eos_token, + unk_token=unk_token, + eol_token=eol_token, + **kwargs) + pad_token = AddedToken(pad_token, lstrip=False, rstrip=False) if isinstance( pad_token, str) else pad_token @@ -538,3 +553,6 @@ def convert_tokens_to_string(self, tokens): text = bytearray([self.byte_decoder[c] for c in text]).decode('utf-8', errors=self.errors) return text + + def get_vocab(self): + return dict(self.encoder, **self.added_tokens_encoder) diff --git a/tests/transformers/bart/test_modeling.py b/tests/transformers/bart/test_modeling.py index 01693d83dffc..f8a9ee12be98 100644 --- a/tests/transformers/bart/test_modeling.py +++ b/tests/transformers/bart/test_modeling.py @@ -112,13 +112,17 @@ def __init__( def prepare_config_and_inputs(self): input_ids = ids_tensor([self.batch_size, self.seq_length], - self.vocab_size) + self.vocab_size, + dtype="int64") input_ids = paddle.clip( - ids_tensor([self.batch_size, self.seq_length], self.vocab_size), 3) + 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) + self.vocab_size, + dtype="int64") config = self.get_config() inputs_dict = prepare_bart_inputs_dict(config, input_ids, @@ -176,7 +180,9 @@ def create_and_check_decoder_model_past_large_inputs( 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"]) + 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()) @@ -198,7 +204,9 @@ def create_and_check_decoder_model_past_large_inputs( cache=cache) # select random slice - random_slice_idx = ids_tensor((1, ), output_from_past.shape[-1]).item() + 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( ) diff --git a/tests/transformers/bart/test_tokenizer.py b/tests/transformers/bart/test_tokenizer.py index 6feee47da85b..79a94f3da984 100644 --- a/tests/transformers/bart/test_tokenizer.py +++ b/tests/transformers/bart/test_tokenizer.py @@ -15,17 +15,22 @@ import json import os import unittest +import tempfile +import shutil -from paddlenlp.transformers import BartTokenizer, BartTokenizerFast, BatchEncoding -from paddlenlp.transformers.models.roberta.tokenization_roberta import VOCAB_FILES_NAMES +from paddlenlp.transformers import BartTokenizer -from ...test_tokenization_common import TokenizerTesterMixin, filter_roberta_detectors +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 - rust_tokenizer_class = BartTokenizerFast - test_rust_tokenizer = True + test_rust_tokenizer = False from_pretrained_filter = filter_roberta_detectors # from_pretrained_kwargs = {'add_prefix_space': True} @@ -53,12 +58,24 @@ def setUp(self): "\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 = {"unk_token": ""} + 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"]) @@ -73,20 +90,12 @@ def get_tokenizer(self, **kwargs): kwargs.update(self.special_tokens_map) return self.tokenizer_class.from_pretrained(self.tmpdirname, **kwargs) - def get_rust_tokenizer(self, **kwargs): - kwargs.update(self.special_tokens_map) - return self.rust_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 default_tokenizer_fast(self): - return BartTokenizerFast.from_pretrained("bart-large") - def test_prepare_batch(self): src_text = [ "A long paragraph for summarization.", @@ -94,15 +103,14 @@ def test_prepare_batch(self): ] expected_src_tokens = [0, 250, 251, 17818, 13, 39186, 1938, 4, 2] - for tokenizer in [self.default_tokenizer, self.default_tokenizer_fast]: - batch = tokenizer(src_text, + for tokenizer in [BartTokenizer.from_pretrained("bart-large")]: + batch = tokenizer(text=src_text, max_length=len(expected_src_tokens), padding=True, - return_tensors="pt") - self.assertIsInstance(batch, BatchEncoding) - - self.assertEqual((2, 9), batch.input_ids.shape) - self.assertEqual((2, 9), batch.attention_mask.shape) + 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 @@ -112,8 +120,11 @@ def test_prepare_batch_empty_target_text(self): "A long paragraph for summarization.", "Another paragraph for summarization." ] - for tokenizer in [self.default_tokenizer, self.default_tokenizer_fast]: - batch = tokenizer(src_text, padding=True, return_tensors="pt") + 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) @@ -125,21 +136,23 @@ def test_tokenizer_as_target_length(self): "Summary of the text.", "Another summary.", ] - for tokenizer in [self.default_tokenizer, self.default_tokenizer_fast]: - targets = tokenizer(text_target=tgt_text, + for tokenizer in [BartTokenizer.from_pretrained("bart-large")]: + targets = tokenizer(text=tgt_text, max_length=32, padding="max_length", - return_tensors="pt") + return_tensors="pd") self.assertEqual(32, targets["input_ids"].shape[1]) def test_prepare_batch_not_longer_than_maxlen(self): - for tokenizer in [self.default_tokenizer, self.default_tokenizer_fast]: - batch = tokenizer(["I am a small frog" * 1024, "I am a small frog"], - padding=True, - truncation=True, - return_tensors="pt") - self.assertIsInstance(batch, BatchEncoding) - self.assertEqual(batch.input_ids.shape, (2, 1024)) + 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): @@ -147,9 +160,9 @@ def test_special_tokens(self): tgt_text = [ "Summary of the text.", ] - for tokenizer in [self.default_tokenizer, self.default_tokenizer_fast]: - inputs = tokenizer(src_text, return_tensors="pt") - targets = tokenizer(text_target=tgt_text, return_tensors="pt") + 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( @@ -164,52 +177,5 @@ def test_special_tokens(self): def test_pretokenized_inputs(self): pass - def test_embeded_special_tokens(self): - for tokenizer, pretrained_name, kwargs in self.tokenizers_list: - with self.subTest( - f"{tokenizer.__class__.__name__} ({pretrained_name})"): - tokenizer_r = self.rust_tokenizer_class.from_pretrained( - pretrained_name, **kwargs) - tokenizer_p = self.tokenizer_class.from_pretrained( - pretrained_name, **kwargs) - sentence = "A, AllenNLP sentence." - tokens_r = tokenizer_r.encode_plus(sentence, - add_special_tokens=True, - return_token_type_ids=True) - tokens_p = tokenizer_p.encode_plus(sentence, - add_special_tokens=True, - return_token_type_ids=True) - - # token_type_ids should put 0 everywhere - self.assertEqual(sum(tokens_r["token_type_ids"]), - sum(tokens_p["token_type_ids"])) - - # attention_mask should put 1 everywhere, so sum over length should be 1 - self.assertEqual( - sum(tokens_r["attention_mask"]) / - len(tokens_r["attention_mask"]), - sum(tokens_p["attention_mask"]) / - len(tokens_p["attention_mask"]), - ) - - tokens_r_str = tokenizer_r.convert_ids_to_tokens( - tokens_r["input_ids"]) - tokens_p_str = tokenizer_p.convert_ids_to_tokens( - tokens_p["input_ids"]) - - # Rust correctly handles the space before the mask while python doesnt - self.assertSequenceEqual( - tokens_p["input_ids"], - [0, 250, 6, 50264, 3823, 487, 21992, 3645, 4, 2]) - self.assertSequenceEqual( - tokens_r["input_ids"], - [0, 250, 6, 50264, 3823, 487, 21992, 3645, 4, 2]) - - self.assertSequenceEqual(tokens_p_str, [ - "", "A", ",", "", "ĠAllen", "N", "LP", "Ġsentence", - ".", "" - ]) - self.assertSequenceEqual(tokens_r_str, [ - "", "A", ",", "", "ĠAllen", "N", "LP", "Ġsentence", - ".", "" - ]) + def test_offsets_mapping(self): + pass diff --git a/tests/transformers/test_modeling_common.py b/tests/transformers/test_modeling_common.py index 5d69dd26094b..58bdeedf47c0 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="int64", 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 2933a2c5fbd9..bb6c8422e1cb 100644 --- a/tests/transformers/test_tokenizer_common.py +++ b/tests/transformers/test_tokenizer_common.py @@ -489,18 +489,14 @@ def test_save_and_load_tokenizer(self): sample_text = " He is very happy, UNwant\u00E9d,running" before_tokens = tokenizer.encode(sample_text, add_special_tokens=False) - # before_vocab = tokenizer.get_vocab() - before_vocab = dict(tokenizer.vocab._token_to_idx, - **tokenizer.added_tokens_encoder) + before_vocab = tokenizer.get_vocab() tokenizer.save_pretrained(tmpdirname) after_tokenizer = tokenizer.__class__.from_pretrained( tmpdirname) 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) + after_vocab = after_tokenizer.get_vocab() self.assertListEqual(before_tokens["input_ids"], after_tokens["input_ids"]) self.assertDictEqual(before_vocab, after_vocab) @@ -521,18 +517,14 @@ def test_save_and_load_tokenizer(self): {"additional_special_tokens": additional_special_tokens}) before_tokens = tokenizer.encode(sample_text, add_special_tokens=False) - # before_vocab = tokenizer.get_vocab() - before_vocab = dict(tokenizer.vocab._token_to_idx, - **tokenizer.added_tokens_encoder) + before_vocab = tokenizer.get_vocab() tokenizer.save_pretrained(tmpdirname) after_tokenizer = tokenizer.__class__.from_pretrained( tmpdirname) 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) + after_vocab = after_tokenizer.get_vocab() self.assertListEqual(before_tokens["input_ids"], after_tokens["input_ids"]) self.assertDictEqual(before_vocab, after_vocab) @@ -565,18 +557,14 @@ def test_save_and_load_tokenizer(self): {"additional_special_tokens": additional_special_tokens}) before_tokens = tokenizer.encode(sample_text, add_special_tokens=False) - # before_vocab = tokenizer.get_vocab() - before_vocab = dict(tokenizer.vocab._token_to_idx, - **tokenizer.added_tokens_encoder) + before_vocab = tokenizer.get_vocab() tokenizer.save_pretrained(tmpdirname) after_tokenizer = tokenizer.__class__.from_pretrained( tmpdirname) 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) + after_vocab = after_tokenizer.get_vocab() self.assertListEqual(before_tokens, after_tokens) self.assertDictEqual(before_vocab, after_vocab) self.assertIn("bim", after_vocab) @@ -1864,9 +1852,7 @@ def test_get_vocab(self): tokenizers = self.get_tokenizers(do_lower_case=False) for tokenizer in tokenizers: with self.subTest(f"{tokenizer.__class__.__name__}"): - # vocab_dict = tokenizer.get_vocab() - vocab_dict = dict(tokenizer.vocab._token_to_idx, - **tokenizer.added_tokens_encoder) + vocab_dict = tokenizer.get_vocab() self.assertIsInstance(vocab_dict, dict) self.assertGreaterEqual(len(tokenizer), len(vocab_dict)) @@ -1887,9 +1873,7 @@ def test_conversion_reversible(self): tokenizers = self.get_tokenizers(do_lower_case=False) for tokenizer in tokenizers: with self.subTest(f"{tokenizer.__class__.__name__}"): - # vocab = tokenizer.get_vocab() - vocab = dict(tokenizer.vocab._token_to_idx, - **tokenizer.added_tokens_encoder) + vocab = tokenizer.get_vocab() for word, ind in vocab.items(): if word == tokenizer.unk_token: continue @@ -2630,11 +2614,8 @@ def test_special_tokens_initialization_with_non_empty_additional_special_tokens( tokenizer_without_change_in_init.additional_special_tokens) # self.assertIn("an_additional_special_token", tokenizer_without_change_in_init.get_vocab()) - self.assertIn( - "an_additional_special_token", - dict( - tokenizer_without_change_in_init.vocab._token_to_idx, ** - tokenizer_without_change_in_init.added_tokens_encoder)) + self.assertIn("an_additional_special_token", + tokenizer_without_change_in_init.get_vocab()) self.assertEqual( ["an_additional_special_token"], tokenizer_without_change_in_init.convert_ids_to_tokens( From 50cd17cfb415953901474468f940de6d8ce5e63e Mon Sep 17 00:00:00 2001 From: FrostML <380185688@qq.com> Date: Fri, 19 Aug 2022 06:31:46 +0000 Subject: [PATCH 06/15] fix --- paddlenlp/transformers/generation_utils.py | 11 ++++++----- 1 file changed, 6 insertions(+), 5 deletions(-) diff --git a/paddlenlp/transformers/generation_utils.py b/paddlenlp/transformers/generation_utils.py index 53261002c0ce..33fb16ffa481 100644 --- a/paddlenlp/transformers/generation_utils.py +++ b/paddlenlp/transformers/generation_utils.py @@ -526,17 +526,18 @@ def get_decoder_start_token_id(self, decoder_start_token_id = ( decoder_start_token_id if decoder_start_token_id is not None else getattr( - self, pretrained_model_name).config["decoder_start_token_id"]) + getattr(self, pretrained_model_name).config, + "decoder_start_token_id", None)) bos_token_id = bos_token_id if bos_token_id is not None else getattr( self, pretrained_model_name).config["bos_token_id"] if decoder_start_token_id is not None: return decoder_start_token_id - elif getattr(self, pretrained_model_name - ).config["decoder_start_token_id"] is not None: + elif getattr( + getattr(self, pretrained_model_name).config, + "decoder_start_token_id", None) is not None: return getattr( - self, - pretrained_model_name).config["decoder.decoder_start_token_id"] + self, pretrained_model_name).config["decoder_start_token_id"] elif bos_token_id is not None: return bos_token_id elif getattr(self, From 90ba0ba502fe12623af3294c222f602f0354da81 Mon Sep 17 00:00:00 2001 From: FrostML <380185688@qq.com> Date: Fri, 19 Aug 2022 07:16:50 +0000 Subject: [PATCH 07/15] update --- paddlenlp/transformers/bart/tokenizer.py | 17 ----------------- paddlenlp/transformers/generation_utils.py | 11 +++++------ paddlenlp/transformers/gpt/tokenizer.py | 6 ------ tests/transformers/test_modeling_common.py | 2 +- 4 files changed, 6 insertions(+), 30 deletions(-) diff --git a/paddlenlp/transformers/bart/tokenizer.py b/paddlenlp/transformers/bart/tokenizer.py index b32ce5c29890..5783bb533d5e 100644 --- a/paddlenlp/transformers/bart/tokenizer.py +++ b/paddlenlp/transformers/bart/tokenizer.py @@ -167,23 +167,6 @@ def __init__(self, pad_token="", mask_token="", **kwargs): - if "max_len" in kwargs and "model_max_length" in kwargs: - kwargs["max_len"] = kwargs["model_max_length"] - elif "max_len" in kwargs: - kwargs["model_max_length"] = kwargs["max_len"] - - super(BartTokenizer, self).__init__(errors=errors, - bos_token=bos_token, - eos_token=eos_token, - cls_token=cls_token, - sep_token=sep_token, - unk_token=unk_token, - pad_token=pad_token, - mask_token=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( diff --git a/paddlenlp/transformers/generation_utils.py b/paddlenlp/transformers/generation_utils.py index 33fb16ffa481..3bb61f871f79 100644 --- a/paddlenlp/transformers/generation_utils.py +++ b/paddlenlp/transformers/generation_utils.py @@ -524,18 +524,17 @@ def get_decoder_start_token_id(self, .format(type(pretrained_model_name))) decoder_start_token_id = ( - decoder_start_token_id - if decoder_start_token_id is not None else getattr( - getattr(self, pretrained_model_name).config, + decoder_start_token_id if decoder_start_token_id is not None else + getattr(self, pretrained_model_name).config.get( "decoder_start_token_id", None)) bos_token_id = bos_token_id if bos_token_id is not None else getattr( self, pretrained_model_name).config["bos_token_id"] if decoder_start_token_id is not None: return decoder_start_token_id - elif getattr( - getattr(self, pretrained_model_name).config, - "decoder_start_token_id", None) is not None: + elif getattr(self, + pretrained_model_name).config.get("decoder_start_token_id", + None) is not None: return getattr( self, pretrained_model_name).config["decoder_start_token_id"] elif bos_token_id is not None: diff --git a/paddlenlp/transformers/gpt/tokenizer.py b/paddlenlp/transformers/gpt/tokenizer.py index 4a3dd05f20f3..8ce57fe9783c 100644 --- a/paddlenlp/transformers/gpt/tokenizer.py +++ b/paddlenlp/transformers/gpt/tokenizer.py @@ -129,12 +129,6 @@ def __init__( eol_token='\u2583', **kwargs # The token of newline. ): - super(GPTChineseTokenizer, self).__init__(max_len=max_len, - unk_token=unk_token, - bos_token=bos_token, - eos_token=eos_token, - eol_token=eol_token, - **kwargs) self._model_file = model_file self.eol_token = eol_token diff --git a/tests/transformers/test_modeling_common.py b/tests/transformers/test_modeling_common.py index d0967d0b542a..1864ebc2e59e 100644 --- a/tests/transformers/test_modeling_common.py +++ b/tests/transformers/test_modeling_common.py @@ -430,7 +430,7 @@ def test_resize_position_vector_embeddings(self): def test_resize_tokens_embeddings(self): ( - config, + original_config, inputs_dict, ) = self.model_tester.prepare_config_and_inputs_for_common() if not self.test_resize_embeddings: From 0be9411d78c743ef4937b04b00ec04555e01288f Mon Sep 17 00:00:00 2001 From: FrostML <380185688@qq.com> Date: Fri, 19 Aug 2022 07:35:00 +0000 Subject: [PATCH 08/15] update --- paddlenlp/transformers/gpt/tokenizer.py | 7 ------- 1 file changed, 7 deletions(-) diff --git a/paddlenlp/transformers/gpt/tokenizer.py b/paddlenlp/transformers/gpt/tokenizer.py index 8ce57fe9783c..56ec8d0044ef 100644 --- a/paddlenlp/transformers/gpt/tokenizer.py +++ b/paddlenlp/transformers/gpt/tokenizer.py @@ -371,13 +371,6 @@ def __init__( add_prefix_space=False, **kwargs # The token of newline. ): - super(GPTTokenizer, self).__init__(errors=errors, - max_len=max_len, - pad_token=pad_token, - eos_token=eos_token, - unk_token=unk_token, - eol_token=eol_token, - **kwargs) pad_token = AddedToken(pad_token, lstrip=False, rstrip=False) if isinstance( From 52f137c40478c53026235a741d6e4c43dad730ce Mon Sep 17 00:00:00 2001 From: FrostML <380185688@qq.com> Date: Fri, 19 Aug 2022 07:37:02 +0000 Subject: [PATCH 09/15] update --- tests/transformers/bart/test_modeling.py | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/tests/transformers/bart/test_modeling.py b/tests/transformers/bart/test_modeling.py index f8a9ee12be98..1bc1bdb001b6 100644 --- a/tests/transformers/bart/test_modeling.py +++ b/tests/transformers/bart/test_modeling.py @@ -13,7 +13,6 @@ # 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. -""" Testing suite for the PyTorch BART model. """ import copy import tempfile @@ -630,8 +629,8 @@ def test_inference_no_head(self): @slow def test_cnn_summarization_same_as_fairseq(self): model = BartForConditionalGeneration.from_pretrained( - "facebook/bart-large").eval() - tok = BartTokenizer.from_pretrained("facebook/bart-large") + "bart-large").eval() + tok = BartTokenizer.from_pretrained("bart-large") FRANCE_ARTICLE = ( # @noq " Marseille, France (CNN)The French prosecutor leading an investigation into the crash of Germanwings" From f6e755c5c7080186c0d9063ae6783cbc45b0f74c Mon Sep 17 00:00:00 2001 From: FrostML <380185688@qq.com> Date: Fri, 19 Aug 2022 08:43:31 +0000 Subject: [PATCH 10/15] bart test --- tests/transformers/bart/test_modeling.py | 26 +++++++++++++----------- 1 file changed, 14 insertions(+), 12 deletions(-) diff --git a/tests/transformers/bart/test_modeling.py b/tests/transformers/bart/test_modeling.py index 1bc1bdb001b6..5f7e44baed8d 100644 --- a/tests/transformers/bart/test_modeling.py +++ b/tests/transformers/bart/test_modeling.py @@ -24,6 +24,7 @@ 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 @@ -615,11 +616,12 @@ def default_tokenizer(self): def test_inference_no_head(self): model = BartModel.from_pretrained("bart-large") model.eval() - input_ids = _long_tensor( - [[0, 31414, 232, 328, 740, 1140, 12695, 69, 46078, 1588, 2]]) + 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.bart.config["pad_token_id"], + 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) @@ -628,8 +630,9 @@ def test_inference_no_head(self): @slow def test_cnn_summarization_same_as_fairseq(self): - model = BartForConditionalGeneration.from_pretrained( - "bart-large").eval() + + model = BartForConditionalGeneration.from_pretrained("bart-large") + model.eval() tok = BartTokenizer.from_pretrained("bart-large") FRANCE_ARTICLE = ( # @noq @@ -825,20 +828,20 @@ def test_cnn_summarization_same_as_fairseq(self): dct = tok._batch_encode_plus( [FRANCE_ARTICLE, SHORTER_ARTICLE, IRAN_ARTICLE, ARTICLE_SUBWAY], max_length=1024, - padding="max_length", - truncation_strategy="only_first", - truncation=True, - return_tensors="pt", + 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( + hypotheses_batch, _ = model.generate( input_ids=dct["input_ids"], attention_mask=dct["attention_mask"], num_beams=2, decode_strategy="beam_search", + max_length=1024, ) - assert hypotheses_batch[:, 1].eq(0).all().item() EXPECTED = [ "A French prosecutor says he is not aware of any video footage from on board the plane. Two German " @@ -862,4 +865,3 @@ def test_cnn_summarization_same_as_fairseq(self): hypotheses_batch.tolist(), clean_up_tokenization_spaces=True, skip_special_tokens=True) - assert generated_summaries == EXPECTED From 9d37831da53d09d479239875821065c13a7c5970 Mon Sep 17 00:00:00 2001 From: FrostML <380185688@qq.com> Date: Mon, 22 Aug 2022 02:39:27 +0000 Subject: [PATCH 11/15] delete timeout_decorator --- tests/transformers/bart/test_modeling.py | 3 --- 1 file changed, 3 deletions(-) diff --git a/tests/transformers/bart/test_modeling.py b/tests/transformers/bart/test_modeling.py index 5f7e44baed8d..14a875263acc 100644 --- a/tests/transformers/bart/test_modeling.py +++ b/tests/transformers/bart/test_modeling.py @@ -18,8 +18,6 @@ import tempfile import unittest -import timeout_decorator # noqa - from tests.testing_utils import slow from ..test_generation_utils import GenerationTesterMixin @@ -281,7 +279,6 @@ def test_question_answering_forward(self): self.assertEqual(start_logits.shape, input_ids.shape) self.assertEqual(end_logits.shape, input_ids.shape) - @timeout_decorator.timeout(1) def test_lm_forward(self): config, input_ids, batch_size = self._get_config_and_data() bart_model = BartModel(**config) From f6fda319a0a99e9d66ced7bd4dc7e1635ce75af0 Mon Sep 17 00:00:00 2001 From: FrostML <380185688@qq.com> Date: Mon, 22 Aug 2022 07:40:05 +0000 Subject: [PATCH 12/15] update --- tests/transformers/bart/test_modeling.py | 22 +++++++++++++--------- 1 file changed, 13 insertions(+), 9 deletions(-) diff --git a/tests/transformers/bart/test_modeling.py b/tests/transformers/bart/test_modeling.py index 14a875263acc..3402e43a0d0a 100644 --- a/tests/transformers/bart/test_modeling.py +++ b/tests/transformers/bart/test_modeling.py @@ -419,12 +419,11 @@ class FastIntegrationTests(unittest.TestCase): def tok(self): return BartTokenizer.from_pretrained("bart-large") - def xsum_1_1_model(self): - return BartForConditionalGeneration.from_pretrained( - "sshleifer/distilbart-xsum-1-1") + def bart_base(self): + return BartForConditionalGeneration.from_pretrained("bart-base") - def test_xsum_1_1_generation(self): - hf = self.xsum_1_1_model + 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" @@ -464,11 +463,16 @@ def test_xsum_1_1_generation(self): " 2002 to prosecute genocide, crimes against humanity and war crimes." ) EXPECTED = ( - " The International Criminal Court (ICC) has announced that it has been announced by the International" - " Criminal court.") + " 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 = tok(ARTICLE, return_tensors="pt") - generated_ids = hf.generate(**dct, num_beams=4) + 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 From 44f24c48d80212228347360a66f9dae3a2c8556f Mon Sep 17 00:00:00 2001 From: FrostML <380185688@qq.com> Date: Mon, 22 Aug 2022 07:46:12 +0000 Subject: [PATCH 13/15] comments --- paddlenlp/transformers/generation_utils.py | 23 +++----- tests/transformers/test_generation_utils.py | 62 ++++++--------------- 2 files changed, 26 insertions(+), 59 deletions(-) diff --git a/paddlenlp/transformers/generation_utils.py b/paddlenlp/transformers/generation_utils.py index 3bb61f871f79..195efa6e107b 100644 --- a/paddlenlp/transformers/generation_utils.py +++ b/paddlenlp/transformers/generation_utils.py @@ -516,32 +516,25 @@ def prepare_decoder_input_ids_for_generation(self, def get_decoder_start_token_id(self, decoder_start_token_id=None, - bos_token_id=None, - pretrained_model_name=None): - if type(pretrained_model_name) is not type(""): - raise ValueError( - "The parameter pretrained_model_name should be str. but recieved {}" - .format(type(pretrained_model_name))) - + bos_token_id=None): decoder_start_token_id = ( decoder_start_token_id if decoder_start_token_id is not None else - getattr(self, pretrained_model_name).config.get( + 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, pretrained_model_name).config["bos_token_id"] + 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, - pretrained_model_name).config.get("decoder_start_token_id", - None) is not None: + elif getattr(self, self.base_model_prefix).config.get( + "decoder_start_token_id", None) is not None: return getattr( - self, pretrained_model_name).config["decoder_start_token_id"] + self, self.base_model_prefix).config["decoder_start_token_id"] elif bos_token_id is not None: return bos_token_id elif getattr(self, - pretrained_model_name).config["bos_token_id"] is not None: - return getattr(self, pretrained_model_name).config["bos_token_id"] + 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." ) diff --git a/tests/transformers/test_generation_utils.py b/tests/transformers/test_generation_utils.py index c6a4fed063f2..bcf91c33ba42 100644 --- a/tests/transformers/test_generation_utils.py +++ b/tests/transformers/test_generation_utils.py @@ -164,7 +164,6 @@ def _get_encoder_outputs( output_attentions=None, output_hidden_states=None, num_interleave=1, - pretrained_model_name=None, ): model.eval() encoder = model.get_encoder() @@ -176,8 +175,8 @@ def _get_encoder_outputs( axis=0) input_ids = paddle.zeros_like( - input_ids[:, :1], dtype="int64") + model.get_decoder_start_token_id( - pretrained_model_name=pretrained_model_name) + input_ids[:, :1], + dtype="int64") + model.get_decoder_start_token_id() # attention_mask = None return encoder_outputs, input_ids, attention_mask @@ -187,18 +186,17 @@ def _greedy_generate( input_ids, attention_mask, max_length, - pretrained_model_name, ): if self.is_encoder_decoder: max_length = 4 logits_process_kwargs, logits_processor = self._get_logits_processor_and_kwargs( - eos_token_id=getattr(model, - pretrained_model_name).config["eos_token_id"], + eos_token_id=getattr( + model, model.base_model_prefix).config["eos_token_id"], forced_bos_token_id=getattr( - getattr(model, pretrained_model_name).config, + getattr(model, model.base_model_prefix).config, "forced_bos_token_id", None), forced_eos_token_id=getattr( - getattr(model, pretrained_model_name).config, + getattr(model, model.base_model_prefix).config, "forced_eos_token_id", None), max_length=max_length, ) @@ -219,7 +217,6 @@ def _greedy_generate( model, input_ids, attention_mask, - pretrained_model_name=pretrained_model_name, ) kwargs["encoder_output"] = encoder_outputs @@ -230,9 +227,9 @@ def _greedy_generate( attention_mask=attention_mask, logits_processors=logits_processor, pad_token_id=getattr( - model, pretrained_model_name).config["pad_token_id"], + model, model.base_model_prefix).config["pad_token_id"], eos_token_id=getattr( - model, pretrained_model_name).config["eos_token_id"], + model, model.base_model_prefix).config["eos_token_id"], **kwargs, ) return output_greedy, output_generate @@ -247,7 +244,6 @@ def _sample_generate( logits_processors, logits_warper, process_kwargs, - pretrained_model_name, ): with paddle.no_grad(): output_generate = model.generate( @@ -267,7 +263,6 @@ def _sample_generate( input_ids, attention_mask, num_interleave=num_return_sequences, - pretrained_model_name=pretrained_model_name, ) kwargs["encoder_output"] = encoder_outputs input_ids_clone = input_ids_clone.repeat_interleave( @@ -289,9 +284,9 @@ def _sample_generate( input_ids.shape[0], logits_processors=logits_processors, pad_token_id=getattr( - model, pretrained_model_name).config["pad_token_id"], + model, model.base_model_prefix).config["pad_token_id"], eos_token_id=getattr( - model, pretrained_model_name).config["eos_token_id"], + model, model.base_model_prefix).config["eos_token_id"], top_k=1, **process_kwargs, **kwargs, @@ -308,7 +303,6 @@ def _beam_search_generate( beam_kwargs, logits_processor, logits_process_kwargs, - pretrained_model_name, ): with paddle.no_grad(): output_generate = model.generate( @@ -328,7 +322,6 @@ def _beam_search_generate( input_ids, attention_mask, num_interleave=beam_scorer.num_beams, - pretrained_model_name=pretrained_model_name, ) kwargs["encoder_output"] = encoder_outputs input_ids_clone = input_ids_clone.repeat_interleave( @@ -353,9 +346,9 @@ def _beam_search_generate( diversity_rate=getattr(logits_process_kwargs, "diversity_rate", 0.0), pad_token_id=getattr( - model, pretrained_model_name).config["pad_token_id"], + model, model.base_model_prefix).config["pad_token_id"], eos_token_id=getattr( - model, pretrained_model_name).config["eos_token_id"], + model, model.base_model_prefix).config["eos_token_id"], **kwargs, ) return output_generate, output_beam_search @@ -370,7 +363,6 @@ def _group_beam_search_generate( beam_kwargs, logits_processor, logits_process_kwargs, - pretrained_model_name, ): model.eval() with paddle.no_grad(): @@ -391,7 +383,6 @@ def _group_beam_search_generate( input_ids, attention_mask, num_interleave=beam_scorer.num_beams, - pretrained_model_name=pretrained_model_name, ) kwargs["encoder_output"] = encoder_outputs input_ids_clone = input_ids_clone.repeat_interleave( @@ -414,9 +405,9 @@ def _group_beam_search_generate( attention_mask=attention_mask_clone, logits_processors=logits_processor, pad_token_id=getattr( - model, pretrained_model_name).config["pad_token_id"], + model, model.base_model_prefix).config["pad_token_id"], eos_token_id=getattr( - model, pretrained_model_name).config["eos_token_id"], + model, model.base_model_prefix).config["eos_token_id"], **kwargs, ) return output_generate, output_group_beam_search @@ -428,8 +419,6 @@ def test_greedy_generate(self): ) pretrained_model = self.all_generative_model_classes[model_class][ 0](**config) - pretrained_model_name = self.all_generative_model_classes[ - model_class][1] model = model_class(pretrained_model) model.eval() @@ -437,8 +426,7 @@ def test_greedy_generate(self): model=model, input_ids=input_ids, attention_mask=attention_mask, - max_length=max_length, - pretrained_model_name=pretrained_model_name) + max_length=max_length) self.assertListEqual(output_greedy[0].tolist(), output_generate[0].tolist()) @@ -453,8 +441,6 @@ def test_sample_generate(self): ) pretrained_model = self.all_generative_model_classes[model_class][ 0](**config) - pretrained_model_name = self.all_generative_model_classes[ - model_class][1] model = model_class(pretrained_model) model.eval() @@ -462,12 +448,12 @@ def test_sample_generate(self): max_length = 4 process_kwargs, logits_processor = self._get_logits_processor_and_kwargs( - getattr(model, pretrained_model_name).config["eos_token_id"], + getattr(model, model.base_model_prefix).config["eos_token_id"], forced_bos_token_id=getattr( - getattr(model, pretrained_model_name).config, + getattr(model, model.base_model_prefix).config, "forced_bos_token_id", None), forced_eos_token_id=getattr( - getattr(model, pretrained_model_name).config, + getattr(model, model.base_model_prefix).config, "forced_eos_token_id", None), max_length=max_length, ) @@ -483,7 +469,6 @@ def test_sample_generate(self): logits_processors=logits_processor, logits_warper=logits_warper, process_kwargs=process_kwargs, - pretrained_model_name=pretrained_model_name, ) self.assertListEqual(output_sample[0].tolist(), output_generate[0].tolist()) @@ -498,7 +483,6 @@ def test_sample_generate(self): logits_processors=logits_processor, logits_warper=logits_warper, process_kwargs=process_kwargs, - pretrained_model_name=pretrained_model_name, ) self.assertListEqual(output_sample[0].tolist(), output_generate[0].tolist()) @@ -516,8 +500,6 @@ def test_beam_search_generate(self): pretrained_model = self.all_generative_model_classes[model_class][ 0](**config) - pretrained_model_name = self.all_generative_model_classes[ - model_class][1] model = model_class(pretrained_model) model.eval() @@ -545,7 +527,6 @@ def test_beam_search_generate(self): beam_kwargs=beam_kwargs, logits_process_kwargs=logits_process_kwargs, logits_processor=logits_processor, - pretrained_model_name=pretrained_model_name, ) self.assertListEqual(output_generate[0].tolist(), @@ -570,7 +551,6 @@ def test_beam_search_generate(self): beam_kwargs=beam_kwargs, logits_process_kwargs=logits_process_kwargs, logits_processor=logits_processor, - pretrained_model_name=pretrained_model_name, ) self.assertListEqual(output_generate[0].tolist(), output_beam_search[0].tolist()) @@ -585,8 +565,6 @@ def test_generate_without_input_ids(self): for model_class in self.all_generative_model_classes.keys(): pretrained_model = self.all_generative_model_classes[model_class][ 0](**config) - pretrained_model_name = self.all_generative_model_classes[ - model_class][1] model = model_class(pretrained_model) model.eval() @@ -610,8 +588,6 @@ def test_group_beam_search_generate(self): pretrained_model = self.all_generative_model_classes[model_class][ 0](**config) - pretrained_model_name = self.all_generative_model_classes[ - model_class][1] model = model_class(pretrained_model) model.eval() @@ -640,7 +616,6 @@ def test_group_beam_search_generate(self): beam_kwargs=beam_kwargs, logits_processor=logits_processor, logits_process_kwargs=logits_process_kwargs, - pretrained_model_name=pretrained_model_name, ) self.assertListEqual(output_generate[0].tolist(), output_group_beam_search[0].tolist()) @@ -663,7 +638,6 @@ def test_group_beam_search_generate(self): beam_kwargs=beam_kwargs, logits_processor=logits_processor, logits_process_kwargs=logits_process_kwargs, - pretrained_model_name=pretrained_model_name, ) self.assertListEqual(output_generate[0].tolist(), output_group_beam_search[0].tolist()) From 45fcc132eab98f8b6ccff8acdad8b8a41334b558 Mon Sep 17 00:00:00 2001 From: FrostML <380185688@qq.com> Date: Mon, 22 Aug 2022 07:47:11 +0000 Subject: [PATCH 14/15] delete spm --- paddlenlp/transformers/bart/tokenizer.py | 1 - 1 file changed, 1 deletion(-) diff --git a/paddlenlp/transformers/bart/tokenizer.py b/paddlenlp/transformers/bart/tokenizer.py index 5783bb533d5e..c5513d225cda 100644 --- a/paddlenlp/transformers/bart/tokenizer.py +++ b/paddlenlp/transformers/bart/tokenizer.py @@ -19,7 +19,6 @@ import json import jieba import shutil -import sentencepiece as spm from paddle.utils import try_import from .. import PretrainedTokenizer, AddedToken From 674e5c81a91f15fb8fa97153a4f7c1d42dc7e82c Mon Sep 17 00:00:00 2001 From: FrostML <380185688@qq.com> Date: Mon, 22 Aug 2022 07:47:32 +0000 Subject: [PATCH 15/15] delete jieba --- paddlenlp/transformers/bart/tokenizer.py | 1 - 1 file changed, 1 deletion(-) diff --git a/paddlenlp/transformers/bart/tokenizer.py b/paddlenlp/transformers/bart/tokenizer.py index c5513d225cda..f244e5a2ad26 100644 --- a/paddlenlp/transformers/bart/tokenizer.py +++ b/paddlenlp/transformers/bart/tokenizer.py @@ -17,7 +17,6 @@ from functools import lru_cache import json -import jieba import shutil from paddle.utils import try_import from .. import PretrainedTokenizer, AddedToken